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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3ee899e59370bc5f832f3b6aee511cbf61371b40
| 642
|
hpp
|
C++
|
libs/systems/include/sge/systems/detail/has_with_input.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/systems/include/sge/systems/detail/has_with_input.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/systems/include/sge/systems/detail/has_with_input.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_SYSTEMS_DETAIL_HAS_WITH_INPUT_HPP_INCLUDED
#define SGE_SYSTEMS_DETAIL_HAS_WITH_INPUT_HPP_INCLUDED
#include <sge/systems/detail/is_with_input.hpp>
#include <fcppt/mpl/lambda.hpp>
#include <fcppt/mpl/list/any_of.hpp>
namespace sge::systems::detail
{
template <typename Choices>
using has_with_input =
fcppt::mpl::list::any_of<Choices, fcppt::mpl::lambda<sge::systems::detail::is_with_input>>;
}
#endif
| 27.913043
| 95
| 0.753894
|
cpreh
|
3ee9cad19bef55a911e18ab9961e1659b15ce3a4
| 2,943
|
cpp
|
C++
|
aws-cpp-sdk-servicecatalog/source/model/ShareDetails.cpp
|
curiousjgeorge/aws-sdk-cpp
|
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
|
[
"Apache-2.0"
] | 2
|
2019-03-11T15:50:55.000Z
|
2020-02-27T11:40:27.000Z
|
aws-cpp-sdk-servicecatalog/source/model/ShareDetails.cpp
|
curiousjgeorge/aws-sdk-cpp
|
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
|
[
"Apache-2.0"
] | null | null | null |
aws-cpp-sdk-servicecatalog/source/model/ShareDetails.cpp
|
curiousjgeorge/aws-sdk-cpp
|
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
|
[
"Apache-2.0"
] | 1
|
2019-01-18T13:03:55.000Z
|
2019-01-18T13:03:55.000Z
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/servicecatalog/model/ShareDetails.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ServiceCatalog
{
namespace Model
{
ShareDetails::ShareDetails() :
m_successfulSharesHasBeenSet(false),
m_shareErrorsHasBeenSet(false)
{
}
ShareDetails::ShareDetails(JsonView jsonValue) :
m_successfulSharesHasBeenSet(false),
m_shareErrorsHasBeenSet(false)
{
*this = jsonValue;
}
ShareDetails& ShareDetails::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("SuccessfulShares"))
{
Array<JsonView> successfulSharesJsonList = jsonValue.GetArray("SuccessfulShares");
for(unsigned successfulSharesIndex = 0; successfulSharesIndex < successfulSharesJsonList.GetLength(); ++successfulSharesIndex)
{
m_successfulShares.push_back(successfulSharesJsonList[successfulSharesIndex].AsString());
}
m_successfulSharesHasBeenSet = true;
}
if(jsonValue.ValueExists("ShareErrors"))
{
Array<JsonView> shareErrorsJsonList = jsonValue.GetArray("ShareErrors");
for(unsigned shareErrorsIndex = 0; shareErrorsIndex < shareErrorsJsonList.GetLength(); ++shareErrorsIndex)
{
m_shareErrors.push_back(shareErrorsJsonList[shareErrorsIndex].AsObject());
}
m_shareErrorsHasBeenSet = true;
}
return *this;
}
JsonValue ShareDetails::Jsonize() const
{
JsonValue payload;
if(m_successfulSharesHasBeenSet)
{
Array<JsonValue> successfulSharesJsonList(m_successfulShares.size());
for(unsigned successfulSharesIndex = 0; successfulSharesIndex < successfulSharesJsonList.GetLength(); ++successfulSharesIndex)
{
successfulSharesJsonList[successfulSharesIndex].AsString(m_successfulShares[successfulSharesIndex]);
}
payload.WithArray("SuccessfulShares", std::move(successfulSharesJsonList));
}
if(m_shareErrorsHasBeenSet)
{
Array<JsonValue> shareErrorsJsonList(m_shareErrors.size());
for(unsigned shareErrorsIndex = 0; shareErrorsIndex < shareErrorsJsonList.GetLength(); ++shareErrorsIndex)
{
shareErrorsJsonList[shareErrorsIndex].AsObject(m_shareErrors[shareErrorsIndex].Jsonize());
}
payload.WithArray("ShareErrors", std::move(shareErrorsJsonList));
}
return payload;
}
} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws
| 29.138614
| 130
| 0.760788
|
curiousjgeorge
|
3eed5f29951a0430f5474b47cab41f71d44a5821
| 7,314
|
hpp
|
C++
|
test/task_test.hpp
|
jimmiebergmann/wepp
|
beb14c840b80967f909f6a748dd0bfd37b29a456
|
[
"MIT"
] | 2
|
2020-02-19T00:21:55.000Z
|
2020-10-14T21:06:06.000Z
|
test/task_test.hpp
|
jimmiebergmann/wepp
|
beb14c840b80967f909f6a748dd0bfd37b29a456
|
[
"MIT"
] | null | null | null |
test/task_test.hpp
|
jimmiebergmann/wepp
|
beb14c840b80967f909f6a748dd0bfd37b29a456
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "wepp/socket/socket.hpp"
#include "wepp/task.hpp"
#include <thread>
using namespace Wepp;
TEST(Task, Task)
{
{
struct TestStruct
{
TestStruct(int integer, const std::string & string) :
integer(integer), string(string)
{ }
int integer;
std::string string;
};
Task<int> task1;
Task<int> task2(123);
EXPECT_EQ(task2(), 123);
Task<TestStruct> task3(123, "test");
EXPECT_EQ(task3().integer, 123);
EXPECT_STREQ(task3().string.c_str(), "test");
Task<> task4;
Task<> task5(true);
EXPECT_TRUE(task5());
Task<> task6(false);
EXPECT_FALSE(task6());
}
}
TEST(Task, TaskController)
{
{
struct TestStruct
{
TestStruct(int integer, const std::string & string) :
integer(integer), string(string)
{ }
int integer;
std::string string;
};
TaskController<int> taskCtrl1;
TaskController<int> taskCtrl2(123);
EXPECT_TRUE(taskCtrl2() == 123);
TaskController<TestStruct> taskCtrl3(123, "test");
EXPECT_EQ(taskCtrl3().integer, 123);
EXPECT_STREQ(taskCtrl3().string.c_str(), "test");
TaskController<> taskCtrl4;
TaskController<> taskCtrl5(true);
EXPECT_TRUE(taskCtrl5());
TaskController<> taskCtrl6(false);
EXPECT_FALSE(taskCtrl6());
}
{
TaskController<int> taskCtrl(0);
EXPECT_EQ(taskCtrl.status(), TaskStatus::Pending);
taskCtrl.finish();
EXPECT_EQ(taskCtrl.status(), TaskStatus::Successful);
}
{
TaskController<int> taskCtrl(0);
EXPECT_EQ(taskCtrl.status(), TaskStatus::Pending);
taskCtrl.fail();
EXPECT_EQ(taskCtrl.status(), TaskStatus::Failed);
}
{
TaskController<int> taskCtrl(1337);
EXPECT_EQ(taskCtrl.status(), TaskStatus::Pending);
EXPECT_EQ(taskCtrl(), 1337);
Task<int> & task = taskCtrl;
EXPECT_EQ(task.status(), TaskStatus::Pending);
EXPECT_EQ(task(), 1337);
taskCtrl() = 2999;
taskCtrl.finish();
EXPECT_EQ(taskCtrl.status(), TaskStatus::Successful);
EXPECT_EQ(taskCtrl(), 2999);
EXPECT_EQ(task.status(), TaskStatus::Successful);
EXPECT_EQ(task(), 2999);
}
}
TEST(Task, Wait)
{
{
auto func = [](const TaskStatus status, const int value) -> Task<int>
{
TaskController<int> task(value);
switch (status)
{
case TaskStatus::Successful: task.finish(); break;
case TaskStatus::Failed: task.fail(); break;
default: break;
}
return task;
};
{
auto task = func(TaskStatus::Successful, 123).wait();
EXPECT_EQ(task.status(), TaskStatus::Successful);
EXPECT_TRUE(task.successful());
EXPECT_FALSE(task.failed());
EXPECT_FALSE(task.pending());
EXPECT_EQ(task(), 123);
}
{
auto task = func(TaskStatus::Failed, 404).wait();
EXPECT_EQ(task.status(), TaskStatus::Failed);
EXPECT_FALSE(task.successful());
EXPECT_TRUE(task.failed());
EXPECT_FALSE(task.pending());
EXPECT_EQ(task(), 404);
}
{
auto task = func(TaskStatus::Pending, 678);
EXPECT_EQ(task.status(), TaskStatus::Pending);
EXPECT_FALSE(task.successful());
EXPECT_FALSE(task.failed());
EXPECT_TRUE(task.pending());
EXPECT_EQ(task(), 678);
}
}
{
class Waiter
{
public:
~Waiter()
{
if (m_thread.joinable())
{
m_thread.join();
}
}
Task<int> run(const TaskStatus status, const int value, const std::chrono::duration<double> & sleep)
{
TaskController<int> task(value);
m_thread = std::thread([task, status, sleep]() mutable
{
std::this_thread::sleep_for(sleep);
switch (status)
{
case TaskStatus::Successful: task.finish(); break;
default: task.fail(); break;
}
});
return task;
}
private:
std::thread m_thread;
};
{
Waiter waiter;
auto task = waiter.run(TaskStatus::Successful, 123, std::chrono::seconds(3)).wait();
EXPECT_EQ(task.status(), TaskStatus::Successful);
EXPECT_EQ(task(), 123);
}
{
Waiter waiter;
auto task = waiter.run(TaskStatus::Failed, 456, std::chrono::seconds(3));
EXPECT_EQ(task.status(), TaskStatus::Pending);
EXPECT_FALSE(task.successful());
EXPECT_FALSE(task.failed());
EXPECT_TRUE(task.pending());
task.wait();
EXPECT_EQ(task.status(), TaskStatus::Failed);
EXPECT_FALSE(task.successful());
EXPECT_TRUE(task.failed());
EXPECT_FALSE(task.pending());
EXPECT_EQ(task(), 456);
}
{
Waiter waiter;
auto start = std::chrono::high_resolution_clock::now();
auto task = waiter.run(TaskStatus::Failed, 404, std::chrono::seconds(2)).wait();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
EXPECT_GE(elapsed.count(), 1.9);
EXPECT_LT(elapsed.count(), 4.0f);
EXPECT_EQ(task.status(), TaskStatus::Failed);
EXPECT_EQ(task(), 404);
}
{
Waiter waiter;
auto start = std::chrono::high_resolution_clock::now();
auto task = waiter.run(TaskStatus::Failed, 404, std::chrono::seconds(1)).wait(std::chrono::duration<double>(2));
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
EXPECT_GE(elapsed.count(), 0.9f);
EXPECT_LT(elapsed.count(), 1.1f);
EXPECT_FALSE(task.timeout());
EXPECT_EQ(task.status(), TaskStatus::Failed);
EXPECT_EQ(task(), 404);
}
{
Waiter waiter;
auto start = std::chrono::high_resolution_clock::now();
auto task = waiter.run(TaskStatus::Failed, 404, std::chrono::seconds(2)).wait(std::chrono::duration<double>(1));
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
EXPECT_GE(elapsed.count(), 0.9f);
EXPECT_LT(elapsed.count(), 1.1f);
EXPECT_TRUE(task.timeout());
std::cout << "Info: " << elapsed.count() << " 4s sleep, 2s timeout.";
EXPECT_EQ(task.status(), TaskStatus::Pending);
EXPECT_EQ(task(), 404);
}
Socket::Socket::setLastError(0);
}
}
| 29.491935
| 124
| 0.523517
|
jimmiebergmann
|
3ef182abed8520392d22b82ddbcf70edb29813e7
| 2,588
|
cpp
|
C++
|
examples/read-continuous.cpp
|
damercer/libsmu
|
6f141ea37a0778299ad1771cc9385fef14010bc0
|
[
"BSD-3-Clause"
] | 30
|
2015-03-28T23:19:54.000Z
|
2022-03-08T14:44:36.000Z
|
examples/read-continuous.cpp
|
damercer/libsmu
|
6f141ea37a0778299ad1771cc9385fef14010bc0
|
[
"BSD-3-Clause"
] | 147
|
2015-03-06T18:37:11.000Z
|
2022-03-28T08:26:47.000Z
|
examples/read-continuous.cpp
|
damercer/libsmu
|
6f141ea37a0778299ad1771cc9385fef14010bc0
|
[
"BSD-3-Clause"
] | 26
|
2015-03-14T06:04:17.000Z
|
2022-03-12T16:37:48.000Z
|
// Simple example for reading data in a continuous fashion.
//
// When run the example should output from all channels to
// stdout in a continuous fashion. If any sample is dropped the program exits
// with an error code of 1.
//
// Note that slower/older setups and/or slower older terminals can cause sample
// drops, redirecting stdout should eliminate this for most cases.
//
// Sample dropping can be forced by sending the running program SIGQUIT
// (via Ctrl-\), to quit use SIGINT (Ctrl-C).
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include <csignal>
#include <array>
#include <chrono>
#include <iostream>
#include <vector>
#include <system_error>
#include <thread>
#include <libsmu/libsmu.hpp>
#ifndef _WIN32
int (*_isatty)(int) = &isatty;
#endif
using std::cout;
using std::cerr;
using std::endl;
using namespace smu;
void signalHandler(int signum)
{
cerr << endl << "sleeping for a bit to cause an overflow exception in continuous mode" << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
int main(int argc, char **argv)
{
#ifndef _WIN32
// Make SIGQUIT force sample drops.
signal(SIGQUIT, signalHandler);
#endif
// Create session object and add all compatible devices them to the
// session. Note that this currently doesn't handle returned errors.
Session* session = new Session();
session->add_all();
if (session->m_devices.size() == 0) {
cerr << "Plug in a device." << endl;
exit(1);
}
// Grab the first device from the session.
auto dev = *(session->m_devices.begin());
// Run session in continuous mode.
session->start(0);
// Data to be read from the device is formatted into a vector of four
// floats in an array, specifically in the format
// <Chan A voltage, Chan A current, Chan B coltage, Chan B current>.
std::vector<std::array<float, 4>> rxbuf;
while (true) {
try {
// Read 1024 samples at a time from the device.
// Note that the timeout (3rd parameter to read() defaults to 0
// (nonblocking mode) so the number of samples returned won't
// necessarily be 1024.
dev->read(rxbuf, 1024);
} catch (const std::system_error& e) {
if (!_isatty(1)) {
// Exit on dropped samples when stdout isn't a terminal.
cerr << "sample(s) dropped: " << e.what() << endl;
exit(1);
}
}
for (auto i: rxbuf) {
// Overwrite a singular line if stdout is a terminal, otherwise
// output line by line.
if (_isatty(1))
printf("\r% 6f % 6f % 6f % 6f", i[0], i[1], i[2], i[3]);
else
printf("% 6f % 6f % 6f % 6f\n", i[0], i[1], i[2], i[3]);
}
};
}
| 26.408163
| 96
| 0.675039
|
damercer
|
3ef2278923ebe2aad86c142ab4a71eb12f0534a7
| 8,988
|
cc
|
C++
|
lib/models/MailboxStatus.src.cc
|
skywa04885/fsmtp-v2
|
a8023ff92e00e1df12f097f50c9bb3bf05d22d0e
|
[
"Apache-2.0"
] | 1
|
2020-07-11T21:48:52.000Z
|
2020-07-11T21:48:52.000Z
|
lib/models/MailboxStatus.src.cc
|
skywa04885/fsmtp-v2
|
a8023ff92e00e1df12f097f50c9bb3bf05d22d0e
|
[
"Apache-2.0"
] | 1
|
2020-07-13T15:01:30.000Z
|
2020-07-19T21:23:05.000Z
|
lib/models/MailboxStatus.src.cc
|
skywa04885/fsmtp-v2
|
a8023ff92e00e1df12f097f50c9bb3bf05d22d0e
|
[
"Apache-2.0"
] | 1
|
2021-05-24T23:05:59.000Z
|
2021-05-24T23:05:59.000Z
|
/*
Copyright [2020] [Luke A.C.A. Rieff]
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 "MailboxStatus.src.h"
namespace FSMTP::Models
{
static void getPrefix(
const int64_t bucket,
const char *domain,
const CassUuid &uuid,
const char *path,
char *ret
) {
sprintf(
ret, "%ld:%s:%ld:%s",
bucket, domain,
cass_uuid_timestamp(uuid),
path
);
}
MailboxStatus::MailboxStatus(void):
s_Recent(0), s_Total(0), s_Flags(0x0),
s_PerfmaFlags(0x0), s_Unseen(0),
s_Bucket(0)
{}
void MailboxStatus::clearRecent(
RedisConnection *redis, const int64_t s_Bucket,
const string &s_Domain, const CassUuid &uuid,
const string &mailboxPath
) {
char prefix[512], command[1024];
getPrefix(s_Bucket, s_Domain.c_str(), uuid, mailboxPath.c_str(), prefix);
sprintf(command, "%s %s v6 %d", "HMSET", prefix, 0);
// Performs the redis command, and checks for errors, if there is an error
// we throw it
redisReply *reply = reinterpret_cast<redisReply *>(redisCommand(
redis->r_Session, command
));
DEFER(freeReplyObject(reply));
if (reply->type == REDIS_REPLY_ERROR) {
string error = "redisCommand() failed: ";
error += string(reply->str, reply->len);
throw DatabaseException(EXCEPT_DEBUG(error));
}
}
MailboxStatus MailboxStatus::get(
RedisConnection *redis,
CassandraConnection *cassandra,
const int64_t s_Bucket,
const string &s_Domain,
const CassUuid &uuid,
const string &mailboxPath
) {
MailboxStatus res;
char prefix[512], command[1024];
getPrefix(s_Bucket, s_Domain.c_str(), uuid, mailboxPath.c_str(), prefix);
sprintf(command, "%s %s", "HGETALL", prefix);
redisReply *reply = reinterpret_cast<redisReply *>(redisCommand(
redis->r_Session, command
));
DEFER(freeReplyObject(reply));
// Gets the variables from the status stored in redis, if this is not the case
// we will attemp to get it from cassandra, this is more expensive thoigh
if (reply->type != REDIS_REPLY_NIL && reply->elements > 0) {
// Checks if the reply object is valid
if (reply->type != REDIS_REPLY_ARRAY) {
throw DatabaseException(EXCEPT_DEBUG("Expected type array, got something else .."));
}
// Gets the flags
if (reply->element[1]->type != REDIS_REPLY_STRING) {
throw DatabaseException(EXCEPT_DEBUG("Expected type integer, got something else .."));
} res.s_Flags = stoi(reply->element[1]->str);
// Gets the unseen count
if (reply->element[3]->type != REDIS_REPLY_STRING) {
throw DatabaseException(EXCEPT_DEBUG("Expected type integer, got something else .."));
} res.s_Unseen = stoi(reply->element[3]->str);
// Gets the total count
if (reply->element[5]->type != REDIS_REPLY_STRING) {
throw DatabaseException(EXCEPT_DEBUG("Expected type integer, got something else .."));
} res.s_Total = stoi(reply->element[5]->str);
// Gets the perma flags
if (reply->element[7]->type != REDIS_REPLY_STRING) {
throw DatabaseException(EXCEPT_DEBUG("Expected type integer, got something else .."));
} res.s_PerfmaFlags = stoi(reply->element[7]->str);
// Gets the recent
if (reply->element[9]->type != REDIS_REPLY_STRING) {
throw DatabaseException(EXCEPT_DEBUG("Expected type integer, got something else .."));
} res.s_Recent = stoi(reply->element[9]->str);
// Updates the status and sets the recent number, since it now is received
// we want to set it to zero
MailboxStatus::clearRecent(redis, s_Bucket, s_Domain, uuid, mailboxPath);
return res;
};
// Since the previous status could not be found, we attempt to restore it from cassandra
// with the existing messages, this is expensive though
res = MailboxStatus::restoreFromCassandra(
cassandra,
s_Bucket,
s_Domain,
uuid,
mailboxPath
);
res.save(redis, mailboxPath);
return res;
}
void MailboxStatus::save(RedisConnection *redis, const string &mailboxPath) {
char prefix[512], command[1024];
getPrefix(s_Bucket, s_Domain.c_str(), this->s_UUID, mailboxPath.c_str(), prefix);
sprintf(
command, "%s %s v1 %d v2 %d v3 %d v4 %d v5 %d",
"HMSET", prefix, this->s_Flags, this->s_Unseen,
this->s_Total, this->s_PerfmaFlags, this->s_Recent
);
// Executes the command and checks for errors, if something goes
// wrong we throw an database exception
redisReply *reply = reinterpret_cast<redisReply *>(redisCommand(
redis->r_Session,
command
));
DEFER(freeReplyObject(reply));
if (reply->type == REDIS_REPLY_ERROR) {
string error = "redisCommand() failed: ";
error += string(reply->str, reply->len);
throw DatabaseException(EXCEPT_DEBUG(error));
}
}
MailboxStatus MailboxStatus::restoreFromCassandra(
CassandraConnection *cassandra,
const int64_t bucket,
const string &domain,
const CassUuid &uuid,
const string &mailboxPath
) {
const char *query = R"(SELECT e_flags, e_uid FROM fannst.email_shortcuts
WHERE e_domain=? AND e_owners_uuid=? AND e_mailbox=?)";
MailboxStatus res;
cass_bool_t hasMorePages;
res.s_Bucket = bucket;
res.s_Domain = domain;
res.s_UUID = uuid;
// Gets the mailbox itself, to set the flags and message count
// because this is already stored inside of cassandra
Mailbox mailbox = Mailbox::get(cassandra, bucket, domain, uuid, mailboxPath);
res.s_Total = mailbox.e_MessageCount;
res.s_Flags = mailbox.e_Flags;
// Prepares the statement, we will not execute it yet because
// this will be done with pages, and not a single one
CassStatement *statement = cass_statement_new(query, 3);
DEFER(cass_statement_free(statement));
cass_statement_bind_string(statement, 0, domain.c_str());
cass_statement_bind_uuid(statement, 1, uuid);
cass_statement_bind_string(statement, 2, mailboxPath.c_str());
cass_statement_set_paging_size(statement, 50);
do {
// Executes the query and checks for initial errors, if there are some
// we throw an database exception
CassFuture *future = cass_session_execute(cassandra->c_Session, statement);
DEFER(cass_future_free(future));
cass_future_wait(future);
if (cass_future_error_code(future) != CASS_OK) {
string error = "cass_session_execute() failed: ";
error += CassandraConnection::getError(future);
throw DatabaseException(error);
}
// Starts looping over the result, and building the final status
// instance, which will later be stored in redis
const CassResult *result = cass_future_get_result(future);
CassIterator *iterator = cass_iterator_from_result(result);
DEFER({
cass_result_free(result);
cass_iterator_free(iterator);
});
while (cass_iterator_next(iterator)) {
const CassRow *row = cass_iterator_get_row(iterator);
int32_t flags, uid;
cass_value_get_int32(cass_row_get_column_by_name(row, "e_flags"), &flags);
cass_value_get_int32(cass_row_get_column_by_name(row, "e_uid"), &uid);
if (!(BINARY_COMPARE(flags, _EMAIL_FLAG_SEEN))) {
++res.s_Unseen;
}
}
hasMorePages = cass_result_has_more_pages(result);
if (hasMorePages) {
cass_statement_set_paging_state(statement, result);
}
} while (hasMorePages);
// Sets the next uuid as the largest one incremented
// after this we return the constructed status object
return res;
}
void MailboxStatus::addOneMessage(
RedisConnection *redis,
CassandraConnection *cassandra,
const int64_t s_Bucket,
const string &s_Domain,
const CassUuid &uuid,
const string &mailboxPath
) {
// Gets the old message status, and increments
// the next uuid, the total, the recent and unseen
// these are all effected when a new message is received
MailboxStatus old = MailboxStatus::get(redis, cassandra, s_Bucket, s_Domain, uuid, mailboxPath);
old.s_Total++;
old.s_Recent++;
old.s_Unseen++;
// Updates the specified values, these will not be updated in cassandra, but only inside
// redis, since cassandra is not meant for so many updates
char prefix[512], command[1024];
getPrefix(s_Bucket, s_Domain.c_str(), uuid, mailboxPath.c_str(), prefix);
sprintf(
command, "%s %s v2 %d v3 %d v5 %d",
"HMSET", prefix,
old.s_Unseen, old.s_Total, old.s_Recent
);
redisReply *reply = reinterpret_cast<redisReply *>(redisCommand(
redis->r_Session, command
));
DEFER(freeReplyObject(reply));
if (reply->type == REDIS_REPLY_ERROR) {
string error = "redisCommand() failed: ";
error += string(reply->str, reply->len);
throw DatabaseException(EXCEPT_DEBUG(error));
}
}
}
| 31.208333
| 98
| 0.711282
|
skywa04885
|
3ef26c06a9403e46ecd1ee59557a754fa1b681b1
| 4,580
|
cc
|
C++
|
libcef/utility/content_utility_client.cc
|
amirbn7/cef
|
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
|
[
"BSD-3-Clause"
] | 1
|
2019-06-18T13:01:08.000Z
|
2019-06-18T13:01:08.000Z
|
libcef/utility/content_utility_client.cc
|
amirbn7/cef
|
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
|
[
"BSD-3-Clause"
] | null | null | null |
libcef/utility/content_utility_client.cc
|
amirbn7/cef
|
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2014 the Chromium Embedded Framework authors.
// Portions Copyright (c) 2012 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 "libcef/utility/content_utility_client.h"
#include <utility>
#include "build/build_config.h"
#include "chrome/services/printing/printing_service.h"
#include "chrome/services/printing/public/mojom/constants.mojom.h"
#include "components/services/pdf_compositor/public/cpp/pdf_compositor_service_factory.h"
#include "components/services/pdf_compositor/public/interfaces/pdf_compositor.mojom.h"
#include "content/public/child/child_thread.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/simple_connection_filter.h"
#include "content/public/utility/utility_thread.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "services/network/url_request_context_builder_mojo.h"
#include "services/proxy_resolver/proxy_resolver_service.h" // nogncheck
#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h" // nogncheck
#include "services/service_manager/public/cpp/binder_registry.h"
#if defined(OS_WIN)
#include "chrome/utility/printing_handler.h"
#endif
namespace {
void RunServiceAsyncThenTerminateProcess(
std::unique_ptr<service_manager::Service> service) {
service_manager::Service::RunAsyncUntilTermination(
std::move(service),
base::BindOnce([] { content::UtilityThread::Get()->ReleaseProcess(); }));
}
#if !defined(OS_ANDROID)
std::unique_ptr<service_manager::Service> CreateProxyResolverService(
service_manager::mojom::ServiceRequest request) {
return std::make_unique<proxy_resolver::ProxyResolverService>(
std::move(request));
}
#endif
using ServiceFactory =
base::OnceCallback<std::unique_ptr<service_manager::Service>()>;
void RunServiceOnIOThread(ServiceFactory factory) {
base::OnceClosure terminate_process = base::BindOnce(
base::IgnoreResult(&base::SequencedTaskRunner::PostTask),
base::SequencedTaskRunnerHandle::Get(), FROM_HERE,
base::BindOnce([] { content::UtilityThread::Get()->ReleaseProcess(); }));
content::ChildThread::Get()->GetIOTaskRunner()->PostTask(
FROM_HERE,
base::BindOnce(
[](ServiceFactory factory, base::OnceClosure terminate_process) {
service_manager::Service::RunAsyncUntilTermination(
std::move(factory).Run(), std::move(terminate_process));
},
std::move(factory), std::move(terminate_process)));
}
} // namespace
CefContentUtilityClient::CefContentUtilityClient() {
#if defined(OS_WIN)
printing_handler_ = std::make_unique<printing::PrintingHandler>();
#endif
}
CefContentUtilityClient::~CefContentUtilityClient() {}
void CefContentUtilityClient::UtilityThreadStarted() {
content::ServiceManagerConnection* connection =
content::ChildThread::Get()->GetServiceManagerConnection();
// NOTE: Some utility process instances are not connected to the Service
// Manager. Nothing left to do in that case.
if (!connection)
return;
auto registry = std::make_unique<service_manager::BinderRegistry>();
connection->AddConnectionFilter(
std::make_unique<content::SimpleConnectionFilter>(std::move(registry)));
}
bool CefContentUtilityClient::OnMessageReceived(const IPC::Message& message) {
bool handled = false;
#if defined(OS_WIN)
if (printing_handler_->OnMessageReceived(message))
return true;
#endif
return handled;
}
std::unique_ptr<service_manager::Service>
CefContentUtilityClient::MaybeCreateMainThreadService(
const std::string& service_name,
service_manager::mojom::ServiceRequest request) {
if (service_name == printing::mojom::kServiceName) {
return printing::CreatePdfCompositorService(std::move(request));
}
if (service_name == printing::mojom::kChromePrintingServiceName) {
return std::make_unique<printing::PrintingService>(std::move(request));
}
return nullptr;
}
bool CefContentUtilityClient::HandleServiceRequest(
const std::string& service_name,
service_manager::mojom::ServiceRequest request) {
if (service_name == proxy_resolver::mojom::kProxyResolverServiceName) {
RunServiceOnIOThread(
base::BindOnce(&CreateProxyResolverService, std::move(request)));
return true;
}
auto service = MaybeCreateMainThreadService(service_name, std::move(request));
if (service) {
RunServiceAsyncThenTerminateProcess(std::move(service));
return true;
}
return false;
}
| 36.349206
| 89
| 0.758079
|
amirbn7
|
3ef4bba2ab250e82f28b81bc21439a075fc2c1ed
| 342
|
cpp
|
C++
|
ace/Proactor_Impl.cpp
|
azerothcore/lib-ace
|
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
|
[
"DOC"
] | null | null | null |
ace/Proactor_Impl.cpp
|
azerothcore/lib-ace
|
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
|
[
"DOC"
] | null | null | null |
ace/Proactor_Impl.cpp
|
azerothcore/lib-ace
|
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
|
[
"DOC"
] | 1
|
2020-04-26T03:07:12.000Z
|
2020-04-26T03:07:12.000Z
|
#include "ace/Proactor_Impl.h"
#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS)
// This only works on standard Win32 platforms and on Unix platforms supporting
// aio calls.
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_Proactor_Impl::~ACE_Proactor_Impl (void)
{
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif
| 21.375
| 80
| 0.777778
|
azerothcore
|
3ef6fadf3f8330b4a38c9280340217b89fcc1b2c
| 5,081
|
inl
|
C++
|
include/geometry2D/primitives/triangle.inl
|
TheTryton/linear_algebra
|
1975bab581e56451e2a7e45749374f11274248a5
|
[
"MIT"
] | null | null | null |
include/geometry2D/primitives/triangle.inl
|
TheTryton/linear_algebra
|
1975bab581e56451e2a7e45749374f11274248a5
|
[
"MIT"
] | null | null | null |
include/geometry2D/primitives/triangle.inl
|
TheTryton/linear_algebra
|
1975bab581e56451e2a7e45749374f11274248a5
|
[
"MIT"
] | null | null | null |
#pragma once
#include "triangle.hpp"
NAMESPACE_GEOMETRY2D_BEGIN
template<class T>
triangle<T>::triangle() :
_points({ point_type<T>(), point_type<T>(), point_type<T>() })
{
}
template<class T>
triangle<T>::triangle(const T & x1, const T & y1, const T & x2, const T & y2, const T & x3, const T & y3):
_points({ point_type<T>(x1, y1), point_type<T>(x2, y2), point_type<T>(x3, y3) })
{
}
template<class T>
triangle<T>::triangle(const point_type<T>& v1, const point_type<T>& v2, const point_type<T>& v3) :
_points({ v1,v2,v3 })
{
}
template<class T>
triangle<T>::triangle(std::initializer_list<point_type<T>> init_list)
{
size_t C = init_list.size() > 3 ? 3 : init_list.size();
std::copy(init_list.begin(), init_list.begin() + C, _points);
}
template<class T>
triangle<T>::triangle(std::initializer_list<T> init_list)
{
if (init_list.size() == 1)
{
_points[0][0] = *init_list.begin();
if (init_list.size() == 2)
{
_points[0][1] = *(init_list.begin() + 1);
if (init_list.size() == 3)
{
_points[1][0] = *(init_list.begin() + 2);
if (init_list.size() == 4)
{
_points[1][1] = *(init_list.begin() + 3);
if (init_list.size() == 5)
{
_points[2][0] = *(init_list.begin() + 4);
if (init_list.size() == 6)
{
_points[2][1] = *(init_list.begin() + 5);
}
}
}
}
}
}
}
template<class T>
point_type<T>* triangle<T>::data()
{
return _points.data();
}
template<class T>
const point_type<T>* triangle<T>::data() const
{
return _points.data();
}
template<class T>
constexpr size_t triangle<T>::size() const
{
return _points.size();
}
template<class T>
point_type<T>& triangle<T>::operator[](size_t i)
{
return _points[i];
}
template<class T>
const point_type<T>& triangle<T>::operator[](size_t i) const
{
return _points[i];
}
template<class T>
auto triangle<T>::begin()
{
return _points.begin();
}
template<class T>
auto triangle<T>::begin() const
{
return _points.begin();
}
template<class T>
auto triangle<T>::end()
{
return _points.end();
}
template<class T>
auto triangle<T>::end() const
{
return _points.end();
}
template<class T>
point_type<T> triangle<T>::center() const
{
return (_points[0] + _points[1] + _points[2]) / static_cast<T>(3);
}
template<class T>
point_type<T>& triangle<T>::p1()
{
return _points[0];
}
template<class T>
const point_type<T>& triangle<T>::p1() const
{
return _points[0];
}
template<class T>
void triangle<T>::set_p1(const point_type<T>& p)
{
_points[0] = p;
}
template<class T>
point_type<T>& triangle<T>::p2()
{
return _points[1];
}
template<class T>
const point_type<T>& triangle<T>::p2() const
{
return _points[1];
}
template<class T>
void triangle<T>::set_p2(const point_type<T>& p)
{
_points[1] = p;
}
template<class T>
point_type<T>& triangle<T>::p3()
{
return _points[2];
}
template<class T>
const point_type<T>& triangle<T>::p3() const
{
return _points[2];
}
template<class T>
void triangle<T>::set_p3(const point_type<T>& p)
{
_points[2] = p;
}
template<class T>
inline T perp_dot_product(const point_type<T>& v1, const point_type<T>& v2)
{
return v1[0] * v2[1] - v1[1] * v2[0];
}
template<class T>
template<inclusion_mode mode>
bool triangle<T>::contains(const point_type<T>& p) const
{
//plane way
auto p1p2 = _points[1] - _points[0];
auto p1p3 = _points[2] - _points[0];
auto p1p = p - _points[0];
auto w = p1p2[0] * p1p3[1] - p1p2[1] * p1p3[0];
if(std::abs(w) <= std::numeric_limits<T>::epsilon())
{
return segment<T>(_points[0], _points[1]).contains<mode>(p, static_cast<T>(1));
}
auto ws = p1p[0] * p1p3[1] - p1p[1] * p1p3[0];
auto wt = p1p[1] * p1p2[0] - p1p[0] * p1p2[1];
auto s = ws / w;
auto t = wt / w;
if constexpr (mode == inclusion_mode::full)
{
return s >= static_cast<T>(0) && t >= static_cast<T>(0) && (s + t) <= static_cast<T>(1);
}
if constexpr (mode == inclusion_mode::edgeless)
{
return s > static_cast<T>(0) && t > static_cast<T>(0) && (s + t) < static_cast<T>(1);
}
if constexpr (mode == inclusion_mode::edge_only)
{
return s == static_cast<T>(0) && t == static_cast<T>(0) && (s + t) == static_cast<T>(1);
}
return false;
}
template<class T>
bool triangle<T>::operator==(const triangle& other) const
{
for (size_t d = 0; d < 3; d++)
{
if (other._points[d] != _points[d])
{
return false;
}
}
return true;
}
template<class T>
bool triangle<T>::operator!=(const triangle& other) const
{
for (size_t d = 0; d < 3; d++)
{
if (other._points[d] != _points[d])
{
return true;
}
}
return false;
}
NAMESPACE_GEOMETRY2D_END
| 20.738776
| 106
| 0.563865
|
TheTryton
|
3efaf2f4e0804dccb6059b8da0924278a52accf3
| 6,022
|
hpp
|
C++
|
src/Video/Renderer.hpp
|
Chainsawkitten/HymnToBeauty
|
b0c431869fee4314eca2aee65d93e78f7e707f10
|
[
"MIT"
] | 10
|
2019-01-13T05:51:54.000Z
|
2022-02-02T14:34:47.000Z
|
src/Video/Renderer.hpp
|
Chainsawkitten/HymnToBeauty
|
b0c431869fee4314eca2aee65d93e78f7e707f10
|
[
"MIT"
] | 46
|
2016-12-30T11:14:25.000Z
|
2021-09-04T12:50:40.000Z
|
src/Video/Renderer.hpp
|
Chainsawkitten/HymnToBeauty
|
b0c431869fee4314eca2aee65d93e78f7e707f10
|
[
"MIT"
] | 4
|
2017-09-28T09:00:58.000Z
|
2019-10-22T05:28:32.000Z
|
#pragma once
#include <glm/glm.hpp>
#include <vector>
#include "Lighting/Light.hpp"
#include "PostProcessing/PostProcessing.hpp"
struct GLFWwindow;
namespace Video {
class StaticRenderProgram;
class Texture2D;
class Shader;
class ShaderProgram;
class RenderPass;
class Buffer;
class VertexDescription;
class GeometryBinding;
class LowLevelRenderer;
class CommandBuffer;
class Texture;
class ZBinning;
namespace Geometry {
class Geometry3D;
} // namespace Geometry
/// Handles rendering using a low-level renderer.
class Renderer {
public:
/// The supported graphics APIs.
enum class GraphicsAPI {
OPENGL, ///< OpenGL
VULKAN ///< Vulkan
};
/// Create new renderer.
/**
* @param graphicsAPI Which graphics API to use for rendering.
* @param window Window to render to.
*/
Renderer(GraphicsAPI graphicsAPI, GLFWwindow* window);
/// Destructor.
~Renderer();
/// Get the low-level renderer.
/**
* @return The low-level renderer.
*/
LowLevelRenderer* GetLowLevelRenderer();
/// Set the size of the render surface.
/**
* @param size The size of the render surface.
*/
void SetRenderSurfaceSize(const glm::uvec2& size);
/// Get the size of the render surface.
/**
* @return The size of the render surface.
*/
const glm::uvec2& GetRenderSurfaceSize() const;
/// Begin new frame.
void BeginFrame();
/// Start depth pre-pass.
void StartDepthPrePass();
/// Start the main forward shading pass.
void StartMainPass();
/// Prepare for depth rendering static meshes.
/**
* @param viewMatrix The camera's view matrix.
* @param projectionMatrix The camera's projection matrix.
*/
void PrepareStaticMeshDepthRendering(const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix);
/// Render a static mesh.
/**
* @param geometry The geometry to render.
* @param modelMatrix Model matrix.
*/
void DepthRenderStaticMesh(Geometry::Geometry3D* geometry, const glm::mat4& modelMatrix);
/// Prepare for rendering static meshes.
/**
* @param viewMatrix The camera's view matrix.
* @param projectionMatrix The camera's projection matrix.
* @param cameraNear Camera near plane distance.
* @param cameraFar Camera far plane distance.
*/
void PrepareStaticMeshRendering(const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix, float cameraNear, float cameraFar);
/// Render a static mesh.
/**
* @param geometry The geometry to render.
* @param albedo Albedo texture.
* @param normal Normal map.
* @param roughnessMetallic Roughness-metallic texture.
* @param modelMatrix Model matrix.
*/
void RenderStaticMesh(Geometry::Geometry3D* geometry, Texture2D* albedo, Texture2D* normal, Texture2D* roughnessMetallic, const glm::mat4 modelMatrix);
/// Update light buffer.
/**
* @param directionalLights Vector of directional lights to push to the directional light buffer.
* @param lights Vector of lights to push to the light buffer.
* @param projectionMatrix Projection matrix.
* @param zNear Near field.
* @param zFar Far field.
*/
void SetLights(const std::vector<DirectionalLight>& directionalLights, const std::vector<Light>& lights, const glm::mat4& projectionMatrix, float zNear, float zFar);
/// Apply post-processing.
void ApplyPostProcessing();
/// Display the rendered results to back buffer and swap back and front buffers.
void Present();
/// Wait until rendering and presentation is done.
/**
* \note
* Needs to be done before destroying render resources or they could still be in use.
*/
void WaitForRender();
/// Begin rendering icons.
/**
* \note
* Needs to be called before RenderIcon.
* @param viewProjectionMatrix The camera's view projection matrix.
* @param cameraPosition The camera's position.
* @param cameraUp The camera's up vector.
*/
void PrepareRenderingIcons(const glm::mat4& viewProjectionMatrix, const glm::vec3& cameraPosition, const glm::vec3& cameraUp);
/// Render a billboarded icon.
/**
* \note
* PrepareRenderingIcons must be called before.
* @param position World position to render at.
* @param icon The icon to render.
*/
void RenderIcon(const glm::vec3& position, Texture2D* icon);
/// Configure the post-processing.
/**
* @param configuration The configuration.
*/
void ConfigurePostProcessing(const PostProcessing::Configuration& configuration);
/// Gamma correction.
/**
* @param gamma Gamma to apply.
*/
void SetGamma(float gamma);
/// Gamma correction.
/**
* @return gamma Gamma value.
*/
float GetGamma() const;
/// Get the command buffer where commands are being recorded.
/**
* @return The command buffer to record into.
*/
CommandBuffer* GetCommandBuffer();
private:
Renderer(const Renderer& other) = delete;
void CreateRenderTextures();
void FreeRenderTextures();
LowLevelRenderer* lowLevelRenderer;
glm::uvec2 renderSurfaceSize;
Texture* colorTexture;
Texture* depthTexture;
Texture* postProcessingTexture;
RenderPass* depthRenderPass;
RenderPass* mainRenderPass;
RenderPass* iconRenderPass;
CommandBuffer* commandBuffer;
StaticRenderProgram* staticRenderProgram;
ZBinning* zBinning;
PostProcessing* postProcessing;
// Icon rendering.
Shader* iconVertexShader;
Shader* iconFragmentShader;
ShaderProgram* iconShaderProgram;
GraphicsPipeline* iconGraphicsPipeline;
Buffer* iconVertexBuffer;
VertexDescription* iconVertexDescription;
GeometryBinding* iconGeometryBinding;
const Texture2D* currentIcon = nullptr;
Buffer* iconMatricesBuffer;
glm::vec3 cameraPosition;
glm::vec3 cameraUp;
};
} // namespace Video
| 28.540284
| 169
| 0.682165
|
Chainsawkitten
|
3efd40b7834a7527f25380bdafe0957957c67ed0
| 40,442
|
cpp
|
C++
|
main_d1/editor/medwall.cpp
|
ziplantil/CacaoticusDescent
|
b4299442bc43310690a666e181dd983c1491dce1
|
[
"MIT"
] | 22
|
2019-08-19T21:09:29.000Z
|
2022-03-25T23:19:15.000Z
|
main_d1/editor/medwall.cpp
|
ziplantil/CacaoticusDescent
|
b4299442bc43310690a666e181dd983c1491dce1
|
[
"MIT"
] | 6
|
2019-11-08T22:17:03.000Z
|
2022-03-10T05:02:59.000Z
|
main_d1/editor/medwall.cpp
|
ziplantil/CacaoticusDescent
|
b4299442bc43310690a666e181dd983c1491dce1
|
[
"MIT"
] | 6
|
2019-08-24T08:03:14.000Z
|
2022-02-04T15:04:52.000Z
|
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
#ifdef EDITOR
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "medwall.h"
#include "main_d1/inferno.h"
#include "editor.h"
#include "main_d1/segment.h"
#include "misc/error.h"
#include "main_d1/gameseg.h"
#include "main_d1/textures.h"
#include "main_d1/screens.h"
#include "main_d1/switch.h"
#include "eswitch.h"
#include "main_d1/texmerge.h"
#include "medrobot.h"
#include "platform/timer.h"
#include "platform/mono.h"
//#include "fuelcen.h"
#include "platform/key.h"
#include "ehostage.h"
#include "centers.h"
#include "main_d1/piggy.h"
int wall_add_to_side(segment* segp, int side, int8_t type);
int wall_add_door_flag(int8_t flag);
int wall_remove_door_flag(int8_t flag);
//-------------------------------------------------------------------------
// Variables for this module...
//-------------------------------------------------------------------------
static UI_WINDOW *MainWindow = NULL;
static UI_GADGET_USERBOX *WallViewBox;
static UI_GADGET_BUTTON *QuitButton;
static UI_GADGET_CHECKBOX *DoorFlag[4];
static UI_GADGET_RADIO *KeyFlag[4];
static int old_wall_num;
static fix Time;
static int framenum=0;
static int Current_door_type=1;
typedef struct count_wall {
short wallnum;
short segnum,sidenum;
} count_wall;
//---------------------------------------------------------------------
// Add a wall (removable 2 sided)
int add_wall(segment *seg, short side)
{
int Connectside;
segment *csegp;
if (Num_walls < MAX_WALLS-2)
if (IS_CHILD(seg->children[side])) {
if (seg->sides[side].wall_num == -1) {
seg->sides[side].wall_num = Num_walls;
Num_walls++;
}
csegp = &Segments[seg->children[side]];
Connectside = find_connect_side(seg, csegp);
if (csegp->sides[Connectside].wall_num == -1) {
csegp->sides[Connectside].wall_num = Num_walls;
Num_walls++;
}
create_removable_wall( seg, side, CurrentTexture );
create_removable_wall( csegp, Connectside, CurrentTexture );
return 1;
}
return 0;
}
int wall_assign_door(int door_type)
{
int Connectside;
segment *csegp;
if (Cursegp->sides[Curside].wall_num == -1) {
editor_status("Cannot assign door. No wall at Curside.");
return 0;
}
if (Walls[Cursegp->sides[Curside].wall_num].type != WALL_DOOR && Walls[Cursegp->sides[Curside].wall_num].type != WALL_BLASTABLE) {
editor_status("Cannot assign door. No door at Curside.");
return 0;
}
Current_door_type = door_type;
csegp = &Segments[Cursegp->children[Curside]];
Connectside = find_connect_side(Cursegp, csegp);
Walls[Cursegp->sides[Curside].wall_num].clip_num = door_type;
Walls[csegp->sides[Connectside].wall_num].clip_num = door_type;
if (WallAnims[door_type].flags & WCF_TMAP1) {
Cursegp->sides[Curside].tmap_num = WallAnims[door_type].frames[0];
csegp->sides[Connectside].tmap_num = WallAnims[door_type].frames[0];
Cursegp->sides[Curside].tmap_num2 = 0;
csegp->sides[Connectside].tmap_num2 = 0;
}
else {
Cursegp->sides[Curside].tmap_num2 = WallAnims[door_type].frames[0];
csegp->sides[Connectside].tmap_num2 = WallAnims[door_type].frames[0];
}
Update_flags |= UF_WORLD_CHANGED;
return 1;
}
int wall_add_blastable()
{
return wall_add_to_side(Cursegp, Curside, WALL_BLASTABLE);
}
int wall_add_door()
{
return wall_add_to_side(Cursegp, Curside, WALL_DOOR);
}
int wall_add_closed_wall()
{
return wall_add_to_side(Cursegp, Curside, WALL_CLOSED);
}
int wall_add_external_wall()
{
if (Cursegp->children[Curside] == -2) {
editor_status( "Wall is already external!" );
return 1;
}
if (IS_CHILD(Cursegp->children[Curside])) {
editor_status( "Cannot add external wall here - seg has children" );
return 0;
}
Cursegp->children[Curside] = -2;
return 1;
}
int wall_add_illusion()
{
return wall_add_to_side(Cursegp, Curside, WALL_ILLUSION);
}
int wall_lock_door()
{
return wall_add_door_flag(WALL_DOOR_LOCKED);
}
int wall_unlock_door()
{
return wall_remove_door_flag(WALL_DOOR_LOCKED);
}
int wall_automate_door()
{
return wall_add_door_flag(WALL_DOOR_AUTO);
}
int wall_deautomate_door()
{
return wall_remove_door_flag(WALL_DOOR_AUTO);
}
int GotoPrevWall() {
int current_wall;
if (Cursegp->sides[Curside].wall_num < 0)
current_wall = Num_walls;
else
current_wall = Cursegp->sides[Curside].wall_num;
current_wall--;
if (current_wall < 0) current_wall = Num_walls-1;
if (current_wall >= Num_walls) current_wall = Num_walls-1;
if (Walls[current_wall].segnum == -1) {
mprintf((0, "Trying to goto wall at bogus segnum\n"));
return 0;
}
if (Walls[current_wall].sidenum == -1) {
mprintf((0, "Trying to goto wall at bogus sidenum\n"));
return 0;
}
Cursegp = &Segments[Walls[current_wall].segnum];
Curside = Walls[current_wall].sidenum;
return 1;
}
int GotoNextWall() {
int current_wall;
current_wall = Cursegp->sides[Curside].wall_num; // It's ok to be -1 because it will immediately become 0
current_wall++;
if (current_wall >= Num_walls) current_wall = 0;
if (current_wall < 0) current_wall = 0;
if (Walls[current_wall].segnum == -1) {
mprintf((0, "Trying to goto wall at bogus segnum\n"));
return 0;
}
if (Walls[current_wall].sidenum == -1) {
mprintf((0, "Trying to goto wall at bogus sidenum\n"));
return 0;
}
Cursegp = &Segments[Walls[current_wall].segnum];
Curside = Walls[current_wall].sidenum;
return 1;
}
int PrevWall() {
int wall_type;
if (Cursegp->sides[Curside].wall_num == -1) {
editor_status("Cannot assign new wall. No wall on curside.");
return 0;
}
wall_type = Walls[Cursegp->sides[Curside].wall_num].clip_num;
if (Walls[Cursegp->sides[Curside].wall_num].type == WALL_DOOR) {
do {
wall_type--;
if (wall_type < 0)
wall_type = Num_wall_anims-1;
if (wall_type == Walls[Cursegp->sides[Curside].wall_num].clip_num)
Error("Cannot find clip for door.");
} while (WallAnims[wall_type].num_frames == -1 || WallAnims[wall_type].flags & WCF_BLASTABLE);
}
else if (Walls[Cursegp->sides[Curside].wall_num].type == WALL_BLASTABLE) {
do {
wall_type--;
if (wall_type < 0)
wall_type = Num_wall_anims-1;
if (wall_type == Walls[Cursegp->sides[Curside].wall_num].clip_num)
Error("Cannot find clip for blastable wall.");
} while (WallAnims[wall_type].num_frames == -1 || !(WallAnims[wall_type].flags & WCF_BLASTABLE));
}
wall_assign_door(wall_type);
Update_flags |= UF_WORLD_CHANGED;
return 1;
}
int NextWall() {
int wall_type;
if (Cursegp->sides[Curside].wall_num == -1) {
editor_status("Cannot assign new wall. No wall on curside.");
return 0;
}
wall_type = Walls[Cursegp->sides[Curside].wall_num].clip_num;
if (Walls[Cursegp->sides[Curside].wall_num].type == WALL_DOOR) {
do {
wall_type++;
if (wall_type >= Num_wall_anims) {
wall_type = 0;
if (Walls[Cursegp->sides[Curside].wall_num].clip_num==-1)
Error("Cannot find clip for door.");
}
} while (WallAnims[wall_type].num_frames == -1 || WallAnims[wall_type].flags & WCF_BLASTABLE);
}
else if (Walls[Cursegp->sides[Curside].wall_num].type == WALL_BLASTABLE) {
do {
wall_type++;
if (wall_type >= Num_wall_anims) {
wall_type = 0;
if (Walls[Cursegp->sides[Curside].wall_num].clip_num==-1)
Error("Cannot find clip for blastable wall.");
}
} while (WallAnims[wall_type].num_frames == -1 || !(WallAnims[wall_type].flags & WCF_BLASTABLE));
}
wall_assign_door(wall_type);
Update_flags |= UF_WORLD_CHANGED;
return 1;
}
//-------------------------------------------------------------------------
// Called from the editor... does one instance of the wall dialog box
//-------------------------------------------------------------------------
int do_wall_dialog()
{
int i;
// Only open 1 instance of this window...
if ( MainWindow != NULL ) return 0;
// Close other windows.
close_all_windows();
// Open a window with a quit button
MainWindow = ui_open_window( TMAPBOX_X+20, TMAPBOX_Y+20, 765-TMAPBOX_X, 545-TMAPBOX_Y, WIN_DIALOG );
QuitButton = ui_add_gadget_button( MainWindow, 20, 252, 48, 40, "Done", NULL );
// These are the checkboxes for each door flag.
i = 80;
DoorFlag[0] = ui_add_gadget_checkbox( MainWindow, 22, i, 16, 16, 0, "Locked" ); i += 24;
DoorFlag[1] = ui_add_gadget_checkbox( MainWindow, 22, i, 16, 16, 0, "Auto" ); i += 24;
DoorFlag[2] = ui_add_gadget_checkbox( MainWindow, 22, i, 16, 16, 0, "Illusion OFF" ); i += 24;
KeyFlag[0] = ui_add_gadget_radio( MainWindow, 22, i, 16, 16, 0, "NONE" ); i += 24;
KeyFlag[1] = ui_add_gadget_radio( MainWindow, 22, i, 16, 16, 0, "Blue" ); i += 24;
KeyFlag[2] = ui_add_gadget_radio( MainWindow, 22, i, 16, 16, 0, "Red" ); i += 24;
KeyFlag[3] = ui_add_gadget_radio( MainWindow, 22, i, 16, 16, 0, "Yellow" ); i += 24;
// The little box the wall will appear in.
WallViewBox = ui_add_gadget_userbox( MainWindow, 155, 5, 64, 64 );
// A bunch of buttons...
i = 80;
ui_add_gadget_button( MainWindow,155,i,70, 22, "<< Clip", PrevWall );
ui_add_gadget_button( MainWindow,155+70,i,70, 22, "Clip >>", NextWall );i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Add Blastable", wall_add_blastable ); i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Add Door", wall_add_door ); i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Add Illusory", wall_add_illusion); i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Add Closed Wall", wall_add_closed_wall ); i+=25;
// ui_add_gadget_button( MainWindow,155,i,140, 22, "Restore All Walls", wall_restore_all ); i += 25;
ui_add_gadget_button( MainWindow,155,i,70, 22, "<< Prev", GotoPrevWall );
ui_add_gadget_button( MainWindow,155+70,i,70, 22, "Next >>", GotoNextWall );i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Remove Wall", wall_remove ); i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Bind to Trigger", bind_wall_to_trigger ); i += 25;
ui_add_gadget_button( MainWindow,155,i,140, 22, "Bind to Control", bind_wall_to_control_center ); i+=25;
old_wall_num = -2; // Set to some dummy value so everything works ok on the first frame.
return 1;
}
void close_wall_window()
{
if ( MainWindow!=NULL ) {
ui_close_window( MainWindow );
MainWindow = NULL;
}
}
void do_wall_window()
{
int i;
int8_t type;
fix DeltaTime, Temp;
if ( MainWindow == NULL ) return;
//------------------------------------------------------------
// Call the ui code..
//------------------------------------------------------------
ui_button_any_drawn = 0;
ui_window_do_gadgets(MainWindow);
//------------------------------------------------------------
// If we change walls, we need to reset the ui code for all
// of the checkboxes that control the wall flags.
//------------------------------------------------------------
if (old_wall_num != Cursegp->sides[Curside].wall_num) {
for ( i=0; i < 3; i++ ) {
DoorFlag[i]->flag = 0; // Tells ui that this button isn't checked
DoorFlag[i]->status = 1; // Tells ui to redraw button
}
for ( i=0; i < 4; i++ ) {
KeyFlag[i]->flag = 0; // Tells ui that this button isn't checked
KeyFlag[i]->status = 1; // Tells ui to redraw button
}
if ( Cursegp->sides[Curside].wall_num != -1) {
if (Walls[Cursegp->sides[Curside].wall_num].flags & WALL_DOOR_LOCKED)
DoorFlag[0]->flag = 1; // Mark this button as checked
if (Walls[Cursegp->sides[Curside].wall_num].flags & WALL_DOOR_AUTO)
DoorFlag[1]->flag = 1; // Mark this button as checked
if (Walls[Cursegp->sides[Curside].wall_num].flags & WALL_ILLUSION_OFF)
DoorFlag[2]->flag = 1; // Mark this button as checked
if (Walls[Cursegp->sides[Curside].wall_num].keys & KEY_NONE)
KeyFlag[0]->flag = 1;
if (Walls[Cursegp->sides[Curside].wall_num].keys & KEY_BLUE)
KeyFlag[1]->flag = 1;
if (Walls[Cursegp->sides[Curside].wall_num].keys & KEY_RED)
KeyFlag[2]->flag = 1;
if (Walls[Cursegp->sides[Curside].wall_num].keys & KEY_GOLD)
KeyFlag[3]->flag = 1;
}
}
//------------------------------------------------------------
// If any of the checkboxes that control the wallflags are set, then
// update the corresponding wall flag.
//------------------------------------------------------------
if (Walls[Cursegp->sides[Curside].wall_num].type == WALL_DOOR) {
if ( DoorFlag[0]->flag == 1 )
Walls[Cursegp->sides[Curside].wall_num].flags |= WALL_DOOR_LOCKED;
else
Walls[Cursegp->sides[Curside].wall_num].flags &= ~WALL_DOOR_LOCKED;
if ( DoorFlag[1]->flag == 1 )
Walls[Cursegp->sides[Curside].wall_num].flags |= WALL_DOOR_AUTO;
else
Walls[Cursegp->sides[Curside].wall_num].flags &= ~WALL_DOOR_AUTO;
//------------------------------------------------------------
// If any of the radio buttons that control the mode are set, then
// update the corresponding key.
//------------------------------------------------------------
for ( i=0; i < 4; i++ ) {
if ( KeyFlag[i]->flag == 1 ) {
Walls[Cursegp->sides[Curside].wall_num].keys = 1<<i; // Set the ai_state to the cooresponding radio button
// mprintf((0, "1<<%d = %d\n", i, 1<<i));
}
}
} else {
for ( i=0; i < 2; i++ )
if (DoorFlag[i]->flag == 1) {
DoorFlag[i]->flag = 0; // Tells ui that this button isn't checked
DoorFlag[i]->status = 1; // Tells ui to redraw button
}
for ( i=0; i < 4; i++ ) {
if ( KeyFlag[i]->flag == 1 ) {
KeyFlag[i]->flag = 0;
KeyFlag[i]->status = 1;
}
}
}
if (Walls[Cursegp->sides[Curside].wall_num].type == WALL_ILLUSION) {
if ( DoorFlag[2]->flag == 1 )
Walls[Cursegp->sides[Curside].wall_num].flags |= WALL_ILLUSION_OFF;
else
Walls[Cursegp->sides[Curside].wall_num].flags &= ~WALL_ILLUSION_OFF;
} else
for ( i=2; i < 3; i++ )
if (DoorFlag[i]->flag == 1) {
DoorFlag[i]->flag = 0; // Tells ui that this button isn't checked
DoorFlag[i]->status = 1; // Tells ui to redraw button
}
//------------------------------------------------------------
// A simple frame time counter for animating the walls...
//------------------------------------------------------------
Temp = timer_get_fixed_seconds();
DeltaTime = Temp - Time;
//------------------------------------------------------------
// Draw the wall in the little 64x64 box
//------------------------------------------------------------
gr_set_current_canvas( WallViewBox->canvas );
if (Cursegp->sides[Curside].wall_num != -1) {
type = Walls[Cursegp->sides[Curside].wall_num].type;
if ((type == WALL_DOOR) || (type == WALL_BLASTABLE)) {
if (DeltaTime > ((F1_0*200)/1000)) {
framenum++;
Time = Temp;
}
if (framenum >= WallAnims[Walls[Cursegp->sides[Curside].wall_num].clip_num].num_frames)
framenum=0;
PIGGY_PAGE_IN(Textures[WallAnims[Walls[Cursegp->sides[Curside].wall_num].clip_num].frames[framenum]]);
gr_ubitmap(0,0, &GameBitmaps[Textures[WallAnims[Walls[Cursegp->sides[Curside].wall_num].clip_num].frames[framenum]].index]);
} else {
if (type == WALL_OPEN)
gr_clear_canvas( CBLACK );
else {
if (Cursegp->sides[Curside].tmap_num2 > 0)
gr_ubitmap(0,0, texmerge_get_cached_bitmap( Cursegp->sides[Curside].tmap_num, Cursegp->sides[Curside].tmap_num2));
else {
PIGGY_PAGE_IN(Textures[Cursegp->sides[Curside].tmap_num]);
gr_ubitmap(0,0, &GameBitmaps[Textures[Cursegp->sides[Curside].tmap_num].index]);
}
}
}
} else
gr_clear_canvas( CGREY );
//------------------------------------------------------------
// If anything changes in the ui system, redraw all the text that
// identifies this wall.
//------------------------------------------------------------
if (ui_button_any_drawn || (old_wall_num != Cursegp->sides[Curside].wall_num) ) {
if ( Cursegp->sides[Curside].wall_num > -1 ) {
ui_wprintf_at( MainWindow, 12, 6, "Wall: %d ", Cursegp->sides[Curside].wall_num);
switch (Walls[Cursegp->sides[Curside].wall_num].type) {
case WALL_NORMAL:
ui_wprintf_at( MainWindow, 12, 23, " Type: Normal " );
break;
case WALL_BLASTABLE:
ui_wprintf_at( MainWindow, 12, 23, " Type: Blastable" );
break;
case WALL_DOOR:
ui_wprintf_at( MainWindow, 12, 23, " Type: Door " );
ui_wprintf_at( MainWindow, 223, 6, "%s", WallAnims[Walls[Cursegp->sides[Curside].wall_num].clip_num].filename);
break;
case WALL_ILLUSION:
ui_wprintf_at( MainWindow, 12, 23, " Type: Illusion " );
break;
case WALL_OPEN:
ui_wprintf_at( MainWindow, 12, 23, " Type: Open " );
break;
case WALL_CLOSED:
ui_wprintf_at( MainWindow, 12, 23, " Type: Closed " );
break;
default:
ui_wprintf_at( MainWindow, 12, 23, " Type: Unknown " );
break;
}
if (Walls[Cursegp->sides[Curside].wall_num].type != WALL_DOOR)
ui_wprintf_at( MainWindow, 223, 6, " " );
ui_wprintf_at( MainWindow, 12, 40, " Clip: %d ", Walls[Cursegp->sides[Curside].wall_num].clip_num );
ui_wprintf_at( MainWindow, 12, 57, " Trigger: %d ", Walls[Cursegp->sides[Curside].wall_num].trigger );
} else {
ui_wprintf_at( MainWindow, 12, 6, "Wall: none ");
ui_wprintf_at( MainWindow, 12, 23, " Type: none ");
ui_wprintf_at( MainWindow, 12, 40, " Clip: none ");
ui_wprintf_at( MainWindow, 12, 57, " Trigger: none ");
}
Update_flags |= UF_WORLD_CHANGED;
}
if ( QuitButton->pressed || (last_keypress==KEY_ESC) ) {
close_wall_window();
return;
}
old_wall_num = Cursegp->sides[Curside].wall_num;
}
//---------------------------------------------------------------------
// Restore all walls to original status (closed doors, repaired walls)
int wall_restore_all()
{
int i, j;
int wall_num;
for (i=0;i<Num_walls;i++) {
if (Walls[i].flags & WALL_BLASTED) {
Walls[i].hps = WALL_HPS;
Walls[i].flags &= ~WALL_BLASTED;
}
if (Walls[i].flags & WALL_DOOR_OPENED)
Walls[i].flags &= ~WALL_DOOR_OPENED;
if (Walls[i].flags & WALL_DOOR_OPENING)
Walls[i].flags &= ~WALL_DOOR_OPENING;
}
for (i=0;i<Num_open_doors;i++)
wall_close_door(i);
for (i=0;i<Num_segments;i++)
for (j=0;j<MAX_SIDES_PER_SEGMENT;j++) {
wall_num = Segments[i].sides[j].wall_num;
if (wall_num != -1)
if ((Walls[wall_num].type == WALL_BLASTABLE) ||
(Walls[wall_num].type == WALL_DOOR))
Segments[i].sides[j].tmap_num2 = WallAnims[Walls[wall_num].clip_num].frames[0];
}
for (i=0;i<Num_triggers;i++)
Triggers[i].flags |= TRIGGER_ON;
Update_flags |= UF_GAME_VIEW_CHANGED;
return 1;
}
//---------------------------------------------------------------------
// Delete a specific wall.
int wall_delete_bogus(short wall_num)
{
int w;
int seg, side;
if ((Walls[wall_num].segnum != -1) && (Walls[wall_num].sidenum != -1)) {
mprintf((0,"WALL IS NOT BOGUS.\n"));
return 0;
}
// Delete bogus wall and slide all above walls down one slot
for (w=wall_num; w<Num_walls; w++) {
Walls[w] = Walls[w+1];
}
Num_walls--;
for (seg=0;seg<=Highest_segment_index;seg++)
if (Segments[seg].segnum != -1)
for (side=0;side<MAX_SIDES_PER_SEGMENT;side++)
if (Segments[seg].sides[side].wall_num > wall_num)
Segments[seg].sides[side].wall_num--;
mprintf((0,"BOGUS WALL DELETED!!!!\n"));
return 1;
}
//---------------------------------------------------------------------
// Remove a specific side.
int wall_remove_side(segment *seg, short side)
{
int Connectside;
segment *csegp;
int lower_wallnum;
int w, s, t, l, t1;
if (IS_CHILD(seg->children[side]) && IS_CHILD(seg->sides[side].wall_num)) {
csegp = &Segments[seg->children[side]];
Connectside = find_connect_side(seg, csegp);
remove_trigger(seg, side);
remove_trigger(csegp, Connectside);
// Remove walls 'wall_num' and connecting side 'wall_num'
// from Walls array.
lower_wallnum = seg->sides[side].wall_num;
if (csegp->sides[Connectside].wall_num < lower_wallnum)
lower_wallnum = csegp->sides[Connectside].wall_num;
if (Walls[lower_wallnum].linked_wall != -1)
Walls[Walls[lower_wallnum].linked_wall].linked_wall = -1;
if (Walls[lower_wallnum+1].linked_wall != -1)
Walls[Walls[lower_wallnum+1].linked_wall].linked_wall = -1;
for (w=lower_wallnum;w<Num_walls-2;w++)
Walls[w] = Walls[w+2];
Num_walls -= 2;
for (s=0;s<=Highest_segment_index;s++)
if (Segments[s].segnum != -1)
for (w=0;w<MAX_SIDES_PER_SEGMENT;w++)
if (Segments[s].sides[w].wall_num > lower_wallnum+1)
Segments[s].sides[w].wall_num -= 2;
// Destroy any links to the deleted wall.
for (t=0;t<Num_triggers;t++)
for (l=0;l<Triggers[t].num_links;l++)
if ((Triggers[t].seg[l] == seg-Segments) && (Triggers[t].side[l] == side)) {
for (t1=0;t1<Triggers[t].num_links-1;t1++) {
Triggers[t].seg[t1] = Triggers[t].seg[t1+1];
Triggers[t].side[t1] = Triggers[t].side[t1+1];
}
Triggers[t].num_links--;
}
// Destroy control center links as well.
for (l=0;l<ControlCenterTriggers.num_links;l++)
if ((ControlCenterTriggers.seg[l] == seg-Segments) && (ControlCenterTriggers.side[l] == side)) {
for (t1=0;t1<ControlCenterTriggers.num_links-1;t1++) {
ControlCenterTriggers.seg[t1] = ControlCenterTriggers.seg[t1+1];
ControlCenterTriggers.side[t1] = ControlCenterTriggers.side[t1+1];
}
ControlCenterTriggers.num_links--;
}
seg->sides[side].wall_num = -1;
csegp->sides[Connectside].wall_num = -1;
Update_flags |= UF_WORLD_CHANGED;
return 1;
}
editor_status( "Can't remove wall. No wall present.");
return 0;
}
//---------------------------------------------------------------------
// Remove a special wall.
int wall_remove()
{
return wall_remove_side(Cursegp, Curside);
}
//---------------------------------------------------------------------
// Add a wall to curside
int wall_add_to_side(segment *segp, int side, int8_t type)
{
int connectside;
segment *csegp;
if (add_wall(segp, side)) {
csegp = &Segments[segp->children[side]];
connectside = find_connect_side(segp, csegp);
Walls[segp->sides[side].wall_num].segnum = segp-Segments;
Walls[csegp->sides[connectside].wall_num].segnum = csegp-Segments;
Walls[segp->sides[side].wall_num].sidenum = side;
Walls[csegp->sides[connectside].wall_num].sidenum = connectside;
Walls[segp->sides[side].wall_num].flags = 0;
Walls[csegp->sides[connectside].wall_num].flags = 0;
Walls[segp->sides[side].wall_num].type = type;
Walls[csegp->sides[connectside].wall_num].type = type;
// Walls[segp->sides[side].wall_num].trigger = -1;
// Walls[csegp->sides[connectside].wall_num].trigger = -1;
Walls[segp->sides[side].wall_num].clip_num = -1;
Walls[csegp->sides[connectside].wall_num].clip_num = -1;
Walls[segp->sides[side].wall_num].keys = KEY_NONE;
Walls[csegp->sides[connectside].wall_num].keys = KEY_NONE;
if (type == WALL_BLASTABLE) {
Walls[segp->sides[side].wall_num].hps = WALL_HPS;
Walls[csegp->sides[connectside].wall_num].hps = WALL_HPS;
//Walls[segp->sides[side].wall_num].clip_num = 0;
//Walls[csegp->sides[connectside].wall_num].clip_num = 0;
}
if (type != WALL_DOOR) {
segp->sides[side].tmap_num2 = 0;
csegp->sides[connectside].tmap_num2 = 0;
}
if (type == WALL_DOOR) {
Walls[segp->sides[side].wall_num].flags |= WALL_DOOR_AUTO;
Walls[csegp->sides[connectside].wall_num].flags |= WALL_DOOR_AUTO;
Walls[segp->sides[side].wall_num].clip_num = Current_door_type;
Walls[csegp->sides[connectside].wall_num].clip_num = Current_door_type;
}
//Update_flags |= UF_WORLD_CHANGED;
//return 1;
// return NextWall(); //assign a clip num
return wall_assign_door(Current_door_type);
} else {
editor_status( "Cannot add wall here, no children" );
return 0;
}
return 0;
}
//---------------------------------------------------------------------
// Add a wall to markedside
int wall_add_to_markedside(int8_t type)
{
int Connectside;
segment *csegp;
if (add_wall(Markedsegp, Markedside)) {
int wall_num, cwall_num;
csegp = &Segments[Markedsegp->children[Markedside]];
Connectside = find_connect_side(Markedsegp, csegp);
wall_num = Markedsegp->sides[Markedside].wall_num;
cwall_num = csegp->sides[Connectside].wall_num;
Walls[wall_num].segnum = Markedsegp-Segments;
Walls[cwall_num].segnum = csegp-Segments;
Walls[wall_num].sidenum = Markedside;
Walls[cwall_num].sidenum = Connectside;
Walls[wall_num].flags = 0;
Walls[cwall_num].flags = 0;
Walls[wall_num].type = type;
Walls[cwall_num].type = type;
Walls[wall_num].trigger = -1;
Walls[cwall_num].trigger = -1;
Walls[wall_num].clip_num = -1;
Walls[cwall_num].clip_num = -1;
Walls[wall_num].keys = KEY_NONE;
Walls[cwall_num].keys = KEY_NONE;
if (type == WALL_BLASTABLE) {
Walls[wall_num].hps = WALL_HPS;
Walls[cwall_num].hps = WALL_HPS;
Walls[wall_num].clip_num = 0;
Walls[cwall_num].clip_num = 0;
}
if (type != WALL_DOOR) {
Markedsegp->sides[Markedside].tmap_num2 = 0;
csegp->sides[Connectside].tmap_num2 = 0;
}
Update_flags |= UF_WORLD_CHANGED;
return 1;
} else {
editor_status( "Cannot add wall here, no children" );
return 0;
}
}
int wall_add_door_flag(int8_t flag)
{
int Connectside;
segment *csegp;
if (Cursegp->sides[Curside].wall_num == -1)
{
editor_status("Cannot change flag. No wall at Curside.");
return 0;
}
if (Walls[Cursegp->sides[Curside].wall_num].type != WALL_DOOR)
{
editor_status("Cannot change flag. No door at Curside.");
return 0;
}
csegp = &Segments[Cursegp->children[Curside]];
Connectside = find_connect_side(Cursegp, csegp);
Walls[Cursegp->sides[Curside].wall_num].flags |= flag;
Walls[csegp->sides[Connectside].wall_num].flags |= flag;
Update_flags |= UF_ED_STATE_CHANGED;
return 1;
}
int wall_remove_door_flag(int8_t flag)
{
int Connectside;
segment *csegp;
if (Cursegp->sides[Curside].wall_num == -1)
{
editor_status("Cannot change flag. No wall at Curside.");
return 0;
}
if (Walls[Cursegp->sides[Curside].wall_num].type != WALL_DOOR)
{
editor_status("Cannot change flag. No door at Curside.");
return 0;
}
csegp = &Segments[Cursegp->children[Curside]];
Connectside = find_connect_side(Cursegp, csegp);
Walls[Cursegp->sides[Curside].wall_num].flags &= ~flag;
Walls[csegp->sides[Connectside].wall_num].flags &= ~flag;
Update_flags |= UF_ED_STATE_CHANGED;
return 1;
}
int bind_wall_to_control_center() {
int link_num;
int i;
if (Cursegp->sides[Curside].wall_num == -1) {
editor_status("No wall at Curside.");
return 0;
}
link_num = ControlCenterTriggers.num_links;
for (i=0;i<link_num;i++)
if ((Cursegp-Segments == ControlCenterTriggers.seg[i]) && (Curside == ControlCenterTriggers.side[i])) {
editor_status("Curside already bound to Control Center.");
return 0;
}
// Error checking completed, actual binding begins
ControlCenterTriggers.seg[link_num] = Cursegp - Segments;
ControlCenterTriggers.side[link_num] = Curside;
ControlCenterTriggers.num_links++;
mprintf((0, "seg %d:side %d linked to control center link_num %d\n",
ControlCenterTriggers.seg[link_num], ControlCenterTriggers.side[link_num], link_num));
editor_status("Wall linked to control center");
return 1;
}
//link two doors, curseg/curside and markedseg/markedside
int wall_link_doors()
{
wall *w1=NULL,*w2=NULL;
if (Cursegp->sides[Curside].wall_num != -1)
w1 = &Walls[Cursegp->sides[Curside].wall_num];
if (Markedsegp->sides[Markedside].wall_num != -1)
w2 = &Walls[Markedsegp->sides[Markedside].wall_num];
if (!w1 || w1->type != WALL_DOOR) {
editor_status("Curseg/curside is not a door");
return 0;
}
if (!w2 || w2->type != WALL_DOOR) {
editor_status("Markedseg/markedside is not a door");
return 0;
}
if (w1->linked_wall != -1)
editor_status("Curseg/curside is already linked");
if (w2->linked_wall != -1)
editor_status("Markedseg/markedside is already linked");
w1->linked_wall = w2-Walls;
w2->linked_wall = w1-Walls;
return 1;
}
int wall_unlink_door()
{
wall *w1=NULL;
if (Cursegp->sides[Curside].wall_num != -1)
w1 = &Walls[Cursegp->sides[Curside].wall_num];
if (!w1 || w1->type != WALL_DOOR) {
editor_status("Curseg/curside is not a door");
return 0;
}
if (w1->linked_wall == -1)
editor_status("Curseg/curside is not linked");
Assert(Walls[w1->linked_wall].linked_wall == w1-Walls);
Walls[w1->linked_wall].linked_wall = -1;
w1->linked_wall = -1;
return 1;
}
#define DIAGNOSTIC_MESSAGE_MAX 150
int check_walls()
{
int w, seg, side, wall_count, trigger_count;
int w1, w2, t, l;
count_wall CountedWalls[MAX_WALLS];
char Message[DIAGNOSTIC_MESSAGE_MAX];
int matcen_num;
wall_count = 0;
for (seg=0;seg<=Highest_segment_index;seg++)
if (Segments[seg].segnum != -1) {
// Check fuelcenters
matcen_num = Segments[seg].matcen_num;
if (matcen_num == 0)
if (RobotCenters[0].segnum != seg) {
mprintf((0,"Fixing Matcen 0\n"));
Segments[seg].matcen_num = -1;
}
if (matcen_num > -1)
if (RobotCenters[matcen_num].segnum != seg) {
mprintf((0,"Matcen [%d] (seg %d) doesn't point back to correct segment %d\n", matcen_num, RobotCenters[matcen_num].segnum, seg));
mprintf((0,"Fixing....\n"));
RobotCenters[matcen_num].segnum = seg;
}
for (side=0;side<MAX_SIDES_PER_SEGMENT;side++)
if (Segments[seg].sides[side].wall_num != -1) {
CountedWalls[wall_count].wallnum = Segments[seg].sides[side].wall_num;
CountedWalls[wall_count].segnum = seg;
CountedWalls[wall_count].sidenum = side;
// Check if segnum is bogus
if (Walls[Segments[seg].sides[side].wall_num].segnum == -1) {
mprintf((0, "Wall %d at seg:side %d:%d is BOGUS\n", Segments[seg].sides[side].wall_num, seg, side));
}
if (Walls[Segments[seg].sides[side].wall_num].type == WALL_NORMAL) {
mprintf((0, "Wall %d at seg:side %d:%d is NORMAL (BAD)\n", Segments[seg].sides[side].wall_num, seg, side));
}
wall_count++;
}
}
mprintf((0,"Wall Count = %d\n", wall_count));
if (wall_count != Num_walls) {
sprintf( Message, "Num_walls is bogus\nDo you wish to correct it?\n");
if (MessageBox( -2, -2, 2, Message, "Yes", "No" )==1) {
Num_walls = wall_count;
editor_status("Num_walls set to %d\n", Num_walls);
}
}
// Check validity of Walls array.
for (w=0; w<Num_walls; w++) {
if ((Walls[CountedWalls[w].wallnum].segnum != CountedWalls[w].segnum) ||
(Walls[CountedWalls[w].wallnum].sidenum != CountedWalls[w].sidenum)) {
mprintf((0,"Unmatched walls on wall_num %d\n", CountedWalls[w].wallnum));
sprintf( Message, "Unmatched wall detected\nDo you wish to correct it?\n");
if (MessageBox( -2, -2, 2, Message, "Yes", "No" )==1) {
Walls[CountedWalls[w].wallnum].segnum = CountedWalls[w].segnum;
Walls[CountedWalls[w].wallnum].sidenum = CountedWalls[w].sidenum;
}
}
if (CountedWalls[w].wallnum >= Num_walls)
mprintf((0,"wallnum %d in Segments exceeds Num_walls!\n", CountedWalls[w].wallnum));
if (Walls[w].segnum == -1) {
mprintf((0, "Wall[%d] is BOGUS\n", w));
for (seg=0;seg<=Highest_segment_index;seg++)
for (side=0;side<MAX_SIDES_PER_SEGMENT;side++)
if (Segments[seg].sides[side].wall_num == w) {
mprintf((0, " BOGUS WALL found at seg:side %d:%d\n", seg, side));
}
}
}
trigger_count = 0;
for (w1=0; w1<wall_count; w1++) {
for (w2=w1+1; w2<wall_count; w2++)
if (CountedWalls[w1].wallnum == CountedWalls[w2].wallnum) {
mprintf((0, "Duplicate Walls %d and %d. Wallnum=%d. ", w1, w2, CountedWalls[w1].wallnum));
mprintf((0, "Seg1:sides1 %d:%d ", CountedWalls[w1].segnum, CountedWalls[w1].sidenum));
mprintf((0, "Seg2:sides2 %d:%d\n", CountedWalls[w2].segnum, CountedWalls[w2].sidenum));
}
if (Walls[w1].trigger != -1) trigger_count++;
}
if (trigger_count != Num_triggers) {
sprintf( Message, "Num_triggers is bogus\nDo you wish to correct it?\n");
if (MessageBox( -2, -2, 2, Message, "Yes", "No" )==1) {
Num_triggers = trigger_count;
editor_status("Num_triggers set to %d\n", Num_triggers);
}
}
mprintf((0,"Trigger Count = %d\n", trigger_count));
for (t=0; t<trigger_count; t++) {
if (Triggers[t].flags & TRIGGER_MATCEN)
if (Triggers[t].num_links < 1)
mprintf((0,"No valid links on Matcen Trigger %d\n", t));
else
for (l=0;l<Triggers[t].num_links;l++) {
if (!Segments[Triggers[t].seg[l]].special & SEGMENT_IS_ROBOTMAKER)
mprintf((0,"Bogus Matcen trigger detected on Trigger %d, No matcen at seg %d\n", t, Triggers[t].seg[l]));
}
if (Triggers[t].flags & TRIGGER_EXIT)
if (Triggers[t].num_links != 0)
mprintf((0,"Bogus links detected on Exit Trigger %d\n", t));
if (Triggers[t].flags & TRIGGER_CONTROL_DOORS)
for (l=0;l<Triggers[t].num_links;l++) {
if (Segments[Triggers[t].seg[l]].sides[Triggers[t].side[l]].wall_num == -1) {
mprintf((0,"Bogus Link detected on Door Control Trigger %d, link %d\n", t, l));
mprintf((0,"Bogus Link at seg %d, side %d\n", Triggers[t].seg[l], Triggers[t].side[l]));
}
}
}
for (l=0;l<ControlCenterTriggers.num_links;l++)
if (Segments[ControlCenterTriggers.seg[l]].sides[ControlCenterTriggers.side[l]].wall_num == -1) {
mprintf((0,"Bogus Link detected on Control Center Trigger, link %d\n", l));
mprintf((0,"Bogus Link at seg %d, side %d\n", Triggers[t].seg[l], Triggers[t].side[l]));
}
return 1;
}
int delete_all_walls()
{
char Message[DIAGNOSTIC_MESSAGE_MAX];
int seg, side;
sprintf( Message, "Are you sure that walls are hosed so\n badly that you want them ALL GONE!?\n");
if (MessageBox( -2, -2, 2, Message, "YES!", "No" )==1) {
for (seg=0;seg<=Highest_segment_index;seg++)
for (side=0;side<MAX_SIDES_PER_SEGMENT;side++)
Segments[seg].sides[side].wall_num = -1;
Num_walls=0;
Num_triggers=0;
return 1;
}
return 0;
}
int delete_all_triggers()
{
char Message[DIAGNOSTIC_MESSAGE_MAX];
int w;
sprintf( Message, "Are you sure that triggers are hosed so\n badly that you want them ALL GONE!?\n");
if (MessageBox( -2, -2, 2, Message, "YES!", "No" )==1) {
for (w=0; w<Num_walls; w++)
Walls[w].trigger=-1;
Num_triggers=0;
return 1;
}
return 0;
}
int dump_walls_info()
{
int w;
FILE *fp;
fp = fopen("WALL.OUT", "wt");
fprintf(fp, "Num_walls %d\n", Num_walls);
for (w=0; w<Num_walls; w++) {
fprintf(fp, "WALL #%d\n", w);
fprintf(fp, " seg: %d\n", Walls[w].segnum);
fprintf(fp, " sidenum: %d\n", Walls[w].sidenum);
switch (Walls[w].type) {
case WALL_NORMAL:
fprintf(fp, " type: NORMAL\n");
break;
case WALL_BLASTABLE:
fprintf(fp, " type: BLASTABLE\n");
break;
case WALL_DOOR:
fprintf(fp, " type: DOOR\n");
break;
case WALL_ILLUSION:
fprintf(fp, " type: ILLUSION\n");
break;
case WALL_OPEN:
fprintf(fp, " type: OPEN\n");
break;
case WALL_CLOSED:
fprintf(fp, " type: CLOSED\n");
break;
default:
fprintf(fp, " type: ILLEGAL!!!!! <-----------------\n");
break;
}
fprintf(fp, " flags:\n");
if (Walls[w].flags & WALL_BLASTED)
fprintf(fp, " BLASTED\n");
if (Walls[w].flags & WALL_DOOR_OPENED)
fprintf(fp, " DOOR_OPENED <----------------- BAD!!!\n");
if (Walls[w].flags & WALL_DOOR_OPENING)
fprintf(fp, " DOOR_OPENING <---------------- BAD!!!\n");
if (Walls[w].flags & WALL_DOOR_LOCKED)
fprintf(fp, " DOOR_LOCKED\n");
if (Walls[w].flags & WALL_DOOR_AUTO)
fprintf(fp, " DOOR_AUTO\n");
if (Walls[w].flags & WALL_ILLUSION_OFF)
fprintf(fp, " ILLUSION_OFF <---------------- OUTDATED\n");
//if (Walls[w].flags & WALL_FUELCEN)
// fprintf(fp, " FUELCEN <--------------------- OUTDATED\n");
fprintf(fp, " trigger: %d\n", Walls[w].trigger);
fprintf(fp, " clip_num: %d\n", Walls[w].clip_num);
switch (Walls[w].keys) {
case KEY_NONE:
fprintf(fp, " key: NONE\n");
break;
case KEY_BLUE:
fprintf(fp, " key: BLUE\n");
break;
case KEY_RED:
fprintf(fp, " key: RED\n");
break;
case KEY_GOLD:
fprintf(fp, " key: NONE\n");
break;
default:
fprintf(fp, " key: ILLEGAL!!!!!! <-----------------\n");
break;
}
fprintf(fp, " linked_wall %d\n", Walls[w].linked_wall);
}
fclose(fp);
return 1;
}
// ------------------------------------------------------------------------------------------------
void copy_old_wall_data_to_new(int owall, int nwall)
{
Walls[nwall].flags = Walls[owall].flags;
Walls[nwall].type = Walls[owall].type;
Walls[nwall].clip_num = Walls[owall].clip_num;
Walls[nwall].keys = Walls[owall].keys;
Walls[nwall].hps = Walls[owall].hps;
Walls[nwall].state = Walls[owall].state;
Walls[nwall].linked_wall = -1;
Walls[nwall].trigger = -1;
if (Walls[owall].trigger != -1) {
editor_status("Warning: Trigger not copied in group copy.");
}
}
//typedef struct trigger {
// byte type;
// short flags;
// fix value;
// fix time;
// byte link_num;
// short num_links;
// short seg[MAX_WALLS_PER_LINK];
// short side[MAX_WALLS_PER_LINK];
// } trigger;
// ------------------------------------------------------------------------------------------------
void copy_group_walls(int old_group, int new_group)
{
int i,j,old_seg, new_seg;
for (i=0; i<GroupList[old_group].num_segments; i++) {
old_seg = GroupList[old_group].segments[i];
new_seg = GroupList[new_group].segments[i];
for (j=0; j<MAX_SIDES_PER_SEGMENT; j++) {
if (Segments[old_seg].sides[j].wall_num != -1) {
mprintf((0, "Going to add wall to seg:side = %i:%i\n", new_seg, j));
Segments[new_seg].sides[j].wall_num = Num_walls;
copy_old_wall_data_to_new(Segments[old_seg].sides[j].wall_num, Num_walls);
Walls[Num_walls].segnum = new_seg;
Walls[Num_walls].sidenum = j;
Num_walls++;
Assert(Num_walls < MAX_WALLS);
}
}
}
}
int Validate_walls=1;
// --------------------------------------------------------------------------------------------------------
// This function should be in medwall.c.
// Make sure all wall/segment connections are valid.
void check_wall_validity(void)
{
int i, j;
int segnum, sidenum, wall_num;
int8_t wall_flags[MAX_WALLS];
if (!Validate_walls)
return;
for (i=0; i<Num_walls; i++) {
segnum = Walls[i].segnum;
sidenum = Walls[i].sidenum;
if (Segments[segnum].sides[sidenum].wall_num != i) {
if (!Validate_walls)
return;
Int3(); // Error! Your mine has been invalidated!
// Do not continue! Do not save!
// Remember your last action and Contact Mike!
// To continue, set the variable Validate_walls to 1 by doing:
// /Validate_walls = 1
// Then do the usual /eip++;g
}
}
for (i=0; i<MAX_WALLS; i++)
wall_flags[i] = 0;
for (i=0; i<=Highest_segment_index; i++) {
if (Segments[i].segnum != -1)
for (j=0; j<MAX_SIDES_PER_SEGMENT; j++) {
// Check walls
wall_num = Segments[i].sides[j].wall_num;
if (wall_num != -1) {
if (wall_flags[wall_num] != 0) {
if (!Validate_walls)
return;
Int3(); // Error! Your mine has been invalidated!
// Do not continue! Do not save!
// Remember your last action and Contact Mike!
// To continue, set the variable Validate_walls to 1 by doing:
// /Validate_walls = 1
// Then do the usual /eip++;g
}
if ((Walls[wall_num].segnum != i) || (Walls[wall_num].sidenum != j)) {
if (!Validate_walls)
return;
Int3(); // Error! Your mine has been invalidated!
// Do not continue! Do not save!
// Remember your last action and Contact Mike!
// To continue, set the variable Validate_walls to 1 by doing:
// /Validate_walls = 1
// Then do the usual /eip++;g
}
wall_flags[wall_num] = 1;
}
}
}
}
#endif
| 29.178932
| 134
| 0.633129
|
ziplantil
|
4107569e638c60b14b0d272292d4653772e64347
| 6,281
|
cc
|
C++
|
lib/Packet.cc
|
dashagratz/simple_network
|
d881b095a59e2fe3a508af3f7f40aebd5ae3f346
|
[
"MIT"
] | 2
|
2020-04-15T16:34:09.000Z
|
2020-04-15T16:37:55.000Z
|
lib/Packet.cc
|
dashagratz/simple_network
|
d881b095a59e2fe3a508af3f7f40aebd5ae3f346
|
[
"MIT"
] | null | null | null |
lib/Packet.cc
|
dashagratz/simple_network
|
d881b095a59e2fe3a508af3f7f40aebd5ae3f346
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
Author: Alexey Frolov (alexwin32@mail.ru)
This software is distributed freely under the terms of the MIT License.
See "LICENSE" or "http://copyfree.org/content/standard/licenses/mit/license.txt".
*******************************************************************************/
#include <Packet.h>
#include <Serializing.h>
namespace Network
{
template< class Type, Network::PacketVariableType VarType, typename Parser = NumericParser<Type> >
class Caster
{
public:
static Type type_cast(const char *data, Network::PacketVariableType TestType)
{
if(TestType != VarType)
throw InvalidVariableDataTypeException("Wrong data type");
return Parser::FromBinary(data);
}
};
Packet::Variable::operator int8_t() const throw (Exception)
{
return Caster<int8_t, VAR_TYPE_INT8>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator int16_t() const throw (Exception)
{
return Caster<int16_t, VAR_TYPE_INT16>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator int32_t() const throw (Exception)
{
return Caster<int32_t, VAR_TYPE_INT32>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator int64_t () const throw (Exception)
{
return Caster<int64_t, VAR_TYPE_INT64>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator float () const throw (Exception)
{
return Caster<float, VAR_TYPE_FLOAT>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator double () const throw (Exception)
{
return Caster<double, VAR_TYPE_DOUBLE>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::string() const throw (Exception)
{
return Caster<std::string, VAR_TYPE_STRING, StringParser>::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<int8_t>() const throw (Exception)
{
return Caster<std::vector<int8_t>,
VAR_TYPE_ARRAY_OF_INT8,
ArrayParser<NumericParser<int8_t> > >::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<int16_t>() const throw (Exception)
{
return Caster<std::vector<int16_t>,
VAR_TYPE_ARRAY_OF_INT16,
ArrayParser<NumericParser<int16_t> > >::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<int32_t>() const throw (Exception)
{
return Caster<std::vector<int32_t>,
VAR_TYPE_ARRAY_OF_INT32,
ArrayParser<NumericParser<int32_t> > >::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<int64_t>() const throw (Exception)
{
return Caster<std::vector<int64_t>,
VAR_TYPE_ARRAY_OF_INT64,
ArrayParser<NumericParser<int64_t> > >::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<float>() const throw (Exception)
{
return Caster<std::vector<float>,
VAR_TYPE_ARRAY_OF_FLOAT,
ArrayParser<NumericParser<float> > >::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<double>() const throw (Exception)
{
return Caster<std::vector<double>,
VAR_TYPE_ARRAY_OF_DOUBLE,
ArrayParser<NumericParser<double> > >::type_cast(&rawData[0], type); //AAA Vector addr
}
Packet::Variable::operator std::vector<std::string>() const throw (Exception)
{
return Caster<std::vector<std::string>,
VAR_TYPE_ARRAY_OF_STRING,
ArrayParser<StringParser> >::type_cast(&rawData[0], type); //AAA Vector addr
}
void Packet::AddVariable(VariableId Id, const Variable &NewVariable)
{
variables[Id] = NewVariable;
}
bool Packet::FindVariable(VariableId Id, Variable &FoundVariable)
{
VariablesStorage::const_iterator ci = variables.find(Id);
if(ci == variables.end())
return false;
FoundVariable = ci->second;
return true;
}
const Packet::Variable &Packet::operator [] (VariableId Id) const throw (Exception)
{
VariablesStorage::const_iterator ci = variables.find(Id);
if(ci == variables.end())
throw VariableNotFoundException("variable " + NumericParser<VariableId>::ToString(Id) + " not found");
return ci->second;
}
Packet CommonPackets::Error(ActionId Code, const std::string &Message)
{
Packet packet(ACTION_ERROR);
packet.CreateVariable(VAR_ERROR_CODE, Code);
packet.CreateVariable(VAR_ERROR_STRING, Message);
return packet;
}
}
Network::PacketVariableType EnumParser<Network::PacketVariableType>::FromInt(int32_t Val) throw (Exception)
{
if(Val == Network::VAR_TYPE_INT8)
return Network::VAR_TYPE_INT8;
else if(Val == Network::VAR_TYPE_INT8)
return Network::VAR_TYPE_INT8;
else if(Val == Network::VAR_TYPE_INT16)
return Network::VAR_TYPE_INT16;
else if(Val == Network::VAR_TYPE_INT32)
return Network::VAR_TYPE_INT32;
else if(Val == Network::VAR_TYPE_INT64)
return Network::VAR_TYPE_INT64;
else if(Val == Network::VAR_TYPE_FLOAT)
return Network::VAR_TYPE_FLOAT;
else if(Val == Network::VAR_TYPE_DOUBLE)
return Network::VAR_TYPE_DOUBLE;
else if(Val == Network::VAR_TYPE_STRING)
return Network::VAR_TYPE_STRING;
else if(Val == Network::VAR_TYPE_ARRAY_OF_INT8)
return Network::VAR_TYPE_ARRAY_OF_INT8;
else if(Val == Network::VAR_TYPE_ARRAY_OF_INT16)
return Network::VAR_TYPE_ARRAY_OF_INT16;
else if(Val == Network::VAR_TYPE_ARRAY_OF_INT32)
return Network::VAR_TYPE_ARRAY_OF_INT32;
else if(Val == Network::VAR_TYPE_ARRAY_OF_INT64)
return Network::VAR_TYPE_ARRAY_OF_INT64;
else if(Val == Network::VAR_TYPE_ARRAY_OF_FLOAT)
return Network::VAR_TYPE_ARRAY_OF_FLOAT;
else if(Val == Network::VAR_TYPE_ARRAY_OF_DOUBLE)
return Network::VAR_TYPE_ARRAY_OF_DOUBLE;
else if(Val == Network::VAR_TYPE_ARRAY_OF_STRING)
return Network::VAR_TYPE_ARRAY_OF_STRING;
else
throw EnumException("Invalid variable type");
}
| 35.089385
| 110
| 0.670753
|
dashagratz
|
4107e59a94d142d1637ef516399d04713694b1e9
| 490
|
cpp
|
C++
|
source/embedded/Src/main_loop.cpp
|
azais-corentin/SliderBar
|
e7bd1b2623f54f10d616e5ac5e2ba47891c10cd2
|
[
"MIT"
] | 1
|
2018-10-18T06:14:31.000Z
|
2018-10-18T06:14:31.000Z
|
source/embedded/Src/main_loop.cpp
|
azais-corentin/SliderBar
|
e7bd1b2623f54f10d616e5ac5e2ba47891c10cd2
|
[
"MIT"
] | 8
|
2018-11-06T21:56:50.000Z
|
2019-01-22T08:31:55.000Z
|
source/embedded/Src/main_loop.cpp
|
azais-corentin/SliderBar
|
e7bd1b2623f54f10d616e5ac5e2ba47891c10cd2
|
[
"MIT"
] | null | null | null |
#include "main_loop.h"
#include <SliderBar/sliderbar.h>
#include <USB/CDC.h>
// Initializes global instances
void* cdc = CDC::self();
void* sliderbar = SliderBar::self();
void main_loop() {
auto&& cdcInstance = static_cast<CDC*>(cdc);
auto&& sliderbarInstance = static_cast<SliderBar*>(sliderbar);
cdcInstance->initialize();
cdcInstance->setReceiver(sliderbarInstance);
sliderbarInstance->setTransmitter(cdcInstance);
while (true) {
sliderbarInstance->decode();
}
}
| 21.304348
| 64
| 0.718367
|
azais-corentin
|
410b73aff7834cb3f2fe831c896a620c093eb90c
| 2,459
|
cpp
|
C++
|
src/eepp/network/socket.cpp
|
jayrulez/eepp
|
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
|
[
"MIT"
] | 37
|
2020-01-20T06:21:24.000Z
|
2022-03-21T17:44:50.000Z
|
src/eepp/network/socket.cpp
|
jayrulez/eepp
|
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
|
[
"MIT"
] | null | null | null |
src/eepp/network/socket.cpp
|
jayrulez/eepp
|
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
|
[
"MIT"
] | 9
|
2019-03-22T00:33:07.000Z
|
2022-03-01T01:35:59.000Z
|
#include <eepp/network/platform/platformimpl.hpp>
#include <eepp/network/socket.hpp>
#include <eepp/system/log.hpp>
namespace EE { namespace Network {
Socket::Socket( Type type ) :
mType( type ), mSocket( Private::SocketImpl::invalidSocket() ), mIsBlocking( true ) {}
Socket::~Socket() {
// Close the socket before it gets destructed
close();
}
void Socket::setBlocking( bool blocking ) {
// Apply if the socket is already created
if ( mSocket != Private::SocketImpl::invalidSocket() )
Private::SocketImpl::setBlocking( mSocket, blocking );
mIsBlocking = blocking;
}
bool Socket::isBlocking() const {
return mIsBlocking;
}
SocketHandle Socket::getHandle() const {
return mSocket;
}
void Socket::create() {
// Don't create the socket if it already exists
if ( mSocket == Private::SocketImpl::invalidSocket() ) {
SocketHandle handle = socket( PF_INET, mType == Tcp ? SOCK_STREAM : SOCK_DGRAM, 0 );
create( handle );
}
}
void Socket::create( SocketHandle handle ) {
// Don't create the socket if it already exists
if ( mSocket == Private::SocketImpl::invalidSocket() ) {
// Assign the new handle
mSocket = handle;
// Set the current blocking state
setBlocking( mIsBlocking );
if ( mType == Tcp ) {
// Disable the Nagle algorithm (ie. removes buffering of TCP packets)
int yes = 1;
if ( setsockopt( mSocket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>( &yes ),
sizeof( yes ) ) == -1 ) {
Log::error(
"Failed to set socket option \"TCP_NODELAY\" ; all your TCP packets will "
"be buffered" );
}
// On Mac OS X, disable the SIGPIPE signal on disconnection
#if EE_PLATFORM == EE_PLATFORM_MACOSX
if ( setsockopt( mSocket, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast<char*>( &yes ),
sizeof( yes ) ) == -1 ) {
Log::error( "Failed to set socket option \"SO_NOSIGPIPE\"" );
}
#endif
} else {
// Enable broadcast by default for UDP sockets
int yes = 1;
if ( setsockopt( mSocket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>( &yes ),
sizeof( yes ) ) == -1 ) {
Log::error( "Failed to enable broadcast on UDP socket" );
}
}
}
}
void Socket::close() {
// Close the socket
if ( mSocket != Private::SocketImpl::invalidSocket() ) {
Private::SocketImpl::close( mSocket );
mSocket = Private::SocketImpl::invalidSocket();
}
}
}} // namespace EE::Network
| 28.264368
| 88
| 0.646604
|
jayrulez
|
410ba645fedf4484e358fd97d3ad27f26944454a
| 4,621
|
cpp
|
C++
|
src/spgwu/simpleswitch/pfcp_far.cpp
|
vetletm/openair-spgwu-tiny
|
c6c4e189d4ec32f84a326af39e37ecd32e962022
|
[
"Apache-2.0"
] | 1
|
2021-06-22T08:11:20.000Z
|
2021-06-22T08:11:20.000Z
|
src/spgwu/simpleswitch/pfcp_far.cpp
|
vetletm/openair-spgwu-tiny
|
c6c4e189d4ec32f84a326af39e37ecd32e962022
|
[
"Apache-2.0"
] | null | null | null |
src/spgwu/simpleswitch/pfcp_far.cpp
|
vetletm/openair-spgwu-tiny
|
c6c4e189d4ec32f84a326af39e37ecd32e962022
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/*! \file pfcp_far.cpp
\author Lionel GAUTHIER
\date 2019
\email: lionel.gauthier@eurecom.fr
*/
#include "pfcp_far.hpp"
#include "pfcp_switch.hpp"
#include "spgwu_config.hpp"
#include "spgwu_s1u.hpp"
using namespace pfcp;
using namespace spgwu;
extern pfcp_switch* pfcp_switch_inst;
extern spgwu_s1u* spgwu_s1u_inst;
extern spgwu_config spgwu_cfg;
//------------------------------------------------------------------------------
void pfcp_far::apply_forwarding_rules(
struct iphdr* const iph, const std::size_t num_bytes, bool& nocp,
bool& buff) {
// TODO dupl
// TODO nocp
// TODO buff
// Logger::pfcp_switch().info( "pfcp_far::apply_forwarding_rules FAR id %4x ",
// far_id.far_id);
if (apply_action.forw) {
if (forwarding_parameters.first) {
if (forwarding_parameters.second.destination_interface.first) {
if (forwarding_parameters.second.destination_interface.second
.interface_value == INTERFACE_VALUE_ACCESS) {
if (forwarding_parameters.second.outer_header_creation.first) {
switch (forwarding_parameters.second.outer_header_creation.second
.outer_header_creation_description) {
case OUTER_HEADER_CREATION_GTPU_UDP_IPV4:
spgwu_s1u_inst->send_g_pdu(
forwarding_parameters.second.outer_header_creation.second
.ipv4_address,
spgwu_cfg.s1_up.port,
forwarding_parameters.second.outer_header_creation.second
.teid,
reinterpret_cast<const char*>(iph), num_bytes);
break;
case OUTER_HEADER_CREATION_GTPU_UDP_IPV6:
spgwu_s1u_inst->send_g_pdu(
forwarding_parameters.second.outer_header_creation.second
.ipv6_address,
spgwu_cfg.s1_up.port,
forwarding_parameters.second.outer_header_creation.second
.teid,
reinterpret_cast<const char*>(iph), num_bytes);
break;
case OUTER_HEADER_CREATION_UDP_IPV4: // TODO
case OUTER_HEADER_CREATION_UDP_IPV6: // TODO
default:;
}
}
} else if (
forwarding_parameters.second.destination_interface.second
.interface_value == INTERFACE_VALUE_CORE) {
if (pfcp_switch_inst->no_internal_loop(iph, num_bytes)) {
pfcp_switch_inst->send_to_core(
reinterpret_cast<char* const>(iph), num_bytes);
}
} else {
}
} else {
// Mandatory IE
}
} else {
// Mandatory if FW set in apply action
}
} else if (apply_action.drop) {
// DONE !
} else if (apply_action.buff) {
buff = true;
}
if (apply_action.nocp) {
nocp = true;
}
}
//------------------------------------------------------------------------------
bool pfcp_far::update(const pfcp::update_far& update, uint8_t& cause_value) {
update.get(apply_action);
if (update.update_forwarding_parameters.first) {
forwarding_parameters.second.update(
update.update_forwarding_parameters.second);
if (update.update_forwarding_parameters.second.pfcpsmreq_flags.first) {
// TODO
}
}
if (update.update_duplicating_parameters.first) {
duplicating_parameters.second.update(
update.update_duplicating_parameters.second);
}
if (update.get(bar_id.second)) bar_id.first = true;
return true;
}
| 37.266129
| 81
| 0.62454
|
vetletm
|
410bb50bcf1b67b32be43f246d0642c83e9c57a5
| 37,045
|
cpp
|
C++
|
src/server/scripts/Northrend/Ulduar/ulduar/boss_flame_leviathan.cpp
|
Zone-Emu/ZoneEmuCataclysm
|
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
|
[
"OpenSSL"
] | 1
|
2019-03-23T19:32:57.000Z
|
2019-03-23T19:32:57.000Z
|
src/server/scripts/Northrend/Ulduar/ulduar/boss_flame_leviathan.cpp
|
Zone-Emu/ZoneEmuCataclysm
|
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
|
[
"OpenSSL"
] | null | null | null |
src/server/scripts/Northrend/Ulduar/ulduar/boss_flame_leviathan.cpp
|
Zone-Emu/ZoneEmuCataclysm
|
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
|
[
"OpenSSL"
] | null | null | null |
/*
* Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/>
*
* Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/>
*
* Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Comment: there is missing code on triggers,
* brann bronzebeard needs correct gossip info.
* requires more work involving area triggers.
* if reached brann speaks through his radio..
*/
#include "ScriptPCH.h"
#include "ScriptedEscortAI.h"
#include "ulduar.h"
#include "Vehicle.h"
enum Spells {
SPELL_PURSUED = 62374,
SPELL_GATHERING_SPEED = 62375,
SPELL_BATTERING_RAM = 62376,
SPELL_FLAME_VENTS = 62396,
SPELL_MISSILE_BARRAGE = 62400,
SPELL_SYSTEMS_SHUTDOWN = 62475,
SPELL_OVERLOAD_CIRCUIT = 62399,
SPELL_START_THE_ENGINE = 62472,
SPELL_SEARING_FLAME = 62402,
SPELL_BLAZE = 62292,
SPELL_TAR_PASSIVE = 62288,
SPELL_SMOKE_TRAIL = 63575,
SPELL_ELECTROSHOCK = 62522,
SPELL_NAPALM = 63666,
//TOWER Additional SPELLS
SPELL_THORIM_S_HAMMER = 62911, // Tower of Storms
SPELL_MIMIRON_S_INFERNO = 62909, // Tower of Flames
SPELL_HODIR_S_FURY = 62533, // Tower of Frost
SPELL_FREYA_S_WARD = 62906, // Tower of Nature
SPELL_FREYA_SUMMONS = 62947, // Tower of Nature
//TOWER ap & health spells
SPELL_BUFF_TOWER_OF_STORMS = 65076,
SPELL_BUFF_TOWER_OF_FLAMES = 65075,
SPELL_BUFF_TOWER_OF_FR0ST = 65077,
SPELL_BUFF_TOWER_OF_LIFE = 64482,
//Additional Spells
SPELL_LASH = 65062,
SPELL_FREYA_S_WARD_EFFECT_1 = 62947,
SPELL_FREYA_S_WARD_EFFECT_2 = 62907,
SPELL_AUTO_REPAIR = 62705,
AURA_DUMMY_BLUE = 63294,
AURA_DUMMY_GREEN = 63295,
AURA_DUMMY_YELLOW = 63292,
SPELL_LIQUID_PYRITE = 62494,
};
enum Creatures {
MOB_MECHANOLIFT = 33214,
MOB_LIQUID = 33189,
MOB_CONTAINER = 33218,
MOB_THORIM_BEACON = 33365,
MOB_MIMIRON_BEACON = 33370,
MOB_HODIR_BEACON = 33212,
MOB_FREYA_BEACON = 33367,
NPC_THORIM_TARGET_BEACON = 33364,
NPC_MIMIRON_TARGET_BEACON = 33369,
NPC_HODIR_TARGET_BEACON = 33108,
NPC_FREYA_TARGET_BEACON = 33366,
NPC_LOREKEEPER = 33686, //Hard mode starter
NPC_BRANZ_BRONZBEARD = 33579,
NPC_DELORAH = 33701,
NPC_ULDUAR_GAUNTLET_GENERATOR = 33571,
// Trigger tied to towers
};
enum Towers {
GO_TOWER_OF_STORMS = 194377,
GO_TOWER_OF_FLAMES = 194371,
GO_TOWER_OF_FROST = 194370,
GO_TOWER_OF_LIFE = 194375,
};
enum Events {
EVENT_NONE,
EVENT_PURSUE,
EVENT_MISSILE,
EVENT_VENT,
EVENT_SPEED,
EVENT_SUMMON,
EVENT_SHUTDOWN,
EVENT_REPAIR,
EVENT_THORIM_S_HAMMER, // Tower of Storms
EVENT_MIMIRON_S_INFERNO, // Tower of Flames
EVENT_HODIR_S_FURY, // Tower of Frost
EVENT_FREYA_S_WARD,
// Tower of Nature
};
enum Seats {
SEAT_PLAYER = 0, SEAT_TURRET = 1, SEAT_DEVICE = 2, SEAT_CANNON = 7,
};
enum Vehicles {
VEHICLE_SIEGE = 33060, VEHICLE_CHOPPER = 33062, VEHICLE_DEMOLISHER = 33109,
};
#define EMOTE_PURSUE "Flame Leviathan pursues $N."
#define EMOTE_OVERLOAD "Flame Leviathan's circuits overloaded."
#define EMOTE_REPAIR "Automatic repair sequence initiated."
enum Yells {
SAY_AGGRO = -1603060,
SAY_SLAY = -1603061,
SAY_DEATH = -1603062,
SAY_TARGET_1 = -1603063,
SAY_TARGET_2 = -1603064,
SAY_TARGET_3 = -1603065,
SAY_HARDMODE = -1603066,
SAY_TOWER_NONE = -1603067,
SAY_TOWER_FROST = -1603068,
SAY_TOWER_FLAME = -1603069,
SAY_TOWER_NATURE = -1603070,
SAY_TOWER_STORM = -1603071,
SAY_PLAYER_RIDING = -1603072,
SAY_OVERLOAD_1 = -1603073,
SAY_OVERLOAD_2 = -1603074,
SAY_OVERLOAD_3 = -1603075,
};
enum eAchievementData {
ACHIEV_10_NUKED_FROM_ORBIT = 2915,
ACHIEV_25_NUKED_FROM_ORBIT = 2917,
ACHIEV_10_ORBITAL_BOMBARDMENT = 2913,
ACHIEV_25_ORBITAL_BOMBARDMENT = 2918,
ACHIEV_10_ORBITAL_DEVASTATION = 2914,
ACHIEV_25_ORBITAL_DEVASTATION = 2916,
ACHIEV_10_ORBIT_UARY = 3056,
ACHIEV_25_ORBIT_UARY = 3057,
ACHIEV_10_SHUTOUT = 2911,
ACHIEV_25_SHUTOUT = 2912,
ACHIEV_10_SIEGE_OF_ULDUAR = 2886,
ACHIEV_25_SIEGE_OF_ULDUAR = 2887,
ACHIEV_10_THREE_CAR_GARAGE = 2907, //no core support for using a vehicle
ACHIEV_25_THREE_CAR_GARAGE = 2908, //no core support for using a vehicle
ACHIEV_10_UNBROKEN = 2905,
ACHIEV_25_UNBROKEN = 2906,
};
static Position Center[] = { { 354.8771f, -12.90240f, 409.803650f, 0.0f }, };
const Position PosSiege[5] = { { -814.59f, -64.54f, 429.92f, 5.969f }, {
-784.37f, -33.31f, 429.92f, 5.096f }, { -808.99f, -52.10f, 429.92f,
5.668f }, { -798.59f, -44.00f, 429.92f, 5.663f }, { -812.83f, -77.71f,
429.92f, 0.046f }, };
const Position PosChopper[5] = { { -717.83f, -106.56f, 430.02f, 0.122f }, {
-717.83f, -114.23f, 430.44f, 0.122f }, { -717.83f, -109.70f, 430.22f,
0.122f }, { -718.45f, -118.24f, 430.26f, 0.052f }, { -718.45f, -123.58f,
430.41f, 0.085f }, };
const Position PosDemolisher[5] = { { -724.12f, -176.64f, 430.03f, 2.543f }, {
-766.70f, -225.03f, 430.50f, 1.710f }, { -729.54f, -186.26f, 430.12f,
1.902f }, { -756.01f, -219.23f, 430.50f, 2.369f }, { -798.01f, -227.24f,
429.84f, 1.446f }, };
class boss_flame_leviathan: public CreatureScript {
public:
boss_flame_leviathan() :
CreatureScript("boss_flame_leviathan") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_flame_leviathanAI(pCreature);
}
struct boss_flame_leviathanAI: public BossAI {
boss_flame_leviathanAI(Creature* pCreature) :
BossAI(pCreature, TYPE_LEVIATHAN), vehicle(
pCreature->GetVehicleKit()) {
assert(vehicle);
uiActiveTowers = 4;
uiShutdown = 0;
ActiveTowers = false;
towerOfStorms = false;
towerOfLife = false;
towerOfFlames = false;
towerOfFrost = false;
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK,
true);
me->ApplySpellImmune(0, IMMUNITY_ID, 49560, true); //deathgrip
me->SetFlag(
UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE
| UNIT_FLAG_STUNNED);
me->SetReactState(REACT_PASSIVE);
}
Vehicle* vehicle;
uint8 uiActiveTowers;
uint8 uiShutdown;
bool ActiveTowers;
bool towerOfStorms;
bool towerOfLife;
bool towerOfFlames;
bool towerOfFrost;
void Reset() {
_Reset();
me->SetReactState(REACT_DEFENSIVE);
InstallAdds(true);
}
void EnterCombat(Unit* /*who*/) {
_EnterCombat();
me->SetReactState(REACT_AGGRESSIVE);
events.ScheduleEvent(EVENT_PURSUE, 30 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_MISSILE, 1500);
events.ScheduleEvent(EVENT_VENT, 20 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SPEED, 15 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SUMMON, 1 * IN_MILLISECONDS);
ActiveTower(false); //void ActiveTower
InstallAdds(false);
}
void ActiveTower(bool bReset = false) {
if (!bReset) {
if (ActiveTowers) {
if (towerOfStorms) {
me->AddAura(SPELL_BUFF_TOWER_OF_STORMS, me);
events.ScheduleEvent(EVENT_THORIM_S_HAMMER,
35 * IN_MILLISECONDS);
}
if (towerOfFlames) {
me->AddAura(SPELL_BUFF_TOWER_OF_FLAMES, me);
events.ScheduleEvent(EVENT_MIMIRON_S_INFERNO,
70 * IN_MILLISECONDS);
}
if (towerOfFrost) {
me->AddAura(SPELL_BUFF_TOWER_OF_FR0ST, me);
events.ScheduleEvent(EVENT_HODIR_S_FURY,
105 * IN_MILLISECONDS);
}
if (towerOfLife) {
me->AddAura(SPELL_BUFF_TOWER_OF_LIFE, me);
events.ScheduleEvent(EVENT_FREYA_S_WARD,
140 * IN_MILLISECONDS);
}
if (!towerOfLife && !towerOfFrost && !towerOfFlames
&& !towerOfStorms)
DoScriptText(SAY_TOWER_NONE, me);
else
DoScriptText(SAY_HARDMODE, me);
} else
DoScriptText(SAY_AGGRO, me);
}
}
void InstallAdds(bool bReset = false) {
if (!bReset) {
std::list<Creature*> lSeats;
me->GetCreatureListWithEntryInGrid(lSeats, 33114, 17.0f);
if (lSeats.empty())
return;
for (std::list<Creature*>::const_iterator itr = lSeats.begin();
itr != lSeats.end(); itr++) {
Vehicle* pSeat = (*itr)->GetVehicleKit();
if (Creature* pTurret = (me->SummonCreature(33142, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_MANUAL_DESPAWN)))
pTurret->EnterVehicle(pSeat, SEAT_TURRET);
if (Creature* pDevice = (me->SummonCreature(33143, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_MANUAL_DESPAWN)))
pDevice->EnterVehicle(pSeat, SEAT_DEVICE);
}
} else {
std::list<Creature*> lSeats;
me->GetCreatureListWithEntryInGrid(lSeats, 33114, 17.0f);
if (lSeats.empty())
return;
for (std::list<Creature*>::const_iterator itr = lSeats.begin();
itr != lSeats.end(); itr++) {
Vehicle* pSeat = (*itr)->GetVehicleKit();
if (Unit* pTurret = (pSeat->GetPassenger(SEAT_TURRET)))
pTurret->RemoveFromWorld();
if (Unit* pDevice = (pSeat->GetPassenger(SEAT_DEVICE)))
pDevice->RemoveFromWorld();
}
}
}
// TODO: effect 0 and effect 1 may be on different target
void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) {
if (pSpell->Id == SPELL_PURSUED)
AttackStart(pTarget);
}
void JustDied(Unit* /*victim*/) {
_JustDied();
DoScriptText(SAY_DEATH, me);
if (ActiveTowers) {
switch (uiActiveTowers) {
case 4:
instance->DoCompleteAchievement(
RAID_MODE(ACHIEV_10_ORBIT_UARY,
ACHIEV_25_ORBIT_UARY));
case 3:
instance->DoCompleteAchievement(
RAID_MODE(ACHIEV_10_NUKED_FROM_ORBIT,
ACHIEV_25_NUKED_FROM_ORBIT));
case 2:
instance->DoCompleteAchievement(
RAID_MODE(ACHIEV_10_ORBITAL_DEVASTATION,
ACHIEV_25_ORBITAL_DEVASTATION));
case 1:
instance->DoCompleteAchievement(
RAID_MODE(ACHIEV_10_ORBITAL_BOMBARDMENT,
ACHIEV_25_ORBITAL_BOMBARDMENT));
}
}
}
void SpellHit(Unit* /*caster*/, const SpellEntry* pSpell) {
if (pSpell->Id == SPELL_START_THE_ENGINE)
vehicle->InstallAllAccessories(me->GetEntry());
if (pSpell->Id == SPELL_ELECTROSHOCK)
me->InterruptSpell(CURRENT_CHANNELED_SPELL);
if (pSpell->Id == SPELL_OVERLOAD_CIRCUIT)
uiShutdown++;
}
void UpdateAI(const uint32 diff) {
if (!me->isInCombat())
return;
if (me->getThreatManager().isThreatListEmpty()) {
EnterEvadeMode();
return;
}
if (uiShutdown == RAID_MODE(2, 4)) {
uiShutdown = 0;
events.ScheduleEvent(EVENT_SHUTDOWN, 0);
events.ScheduleEvent(EVENT_REPAIR, 0);
me->RemoveAurasDueToSpell(SPELL_OVERLOAD_CIRCUIT);
me->InterruptNonMeleeSpells(true);
return;
}
if (me->HasAura(SPELL_SYSTEMS_SHUTDOWN)) {
me->SetReactState(REACT_PASSIVE);
me->AddUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT);
return;
}
if (me->HasUnitState(UNIT_STAT_CASTING))
return;
if (me->HasAura(SPELL_SYSTEMS_SHUTDOWN)) {
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
return;
} else {
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
}
events.Update(diff);
uint32 eventId = events.GetEvent();
if (!me->getVictim())
UpdateVictim();
switch (eventId) {
case 0:
break; // this is a must
case EVENT_PURSUE:
DoScriptText(RAND(SAY_TARGET_1, SAY_TARGET_2, SAY_TARGET_3),
me);
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM)) {
if (pTarget->GetTypeId() == TYPEID_PLAYER
|| pTarget->HasFlag(UNIT_NPC_FLAGS,
UNIT_NPC_FLAG_PLAYER_VEHICLE)) {
me->AddAura(SPELL_PURSUED, pTarget);
me->MonsterTextEmote(EMOTE_PURSUE, pTarget->GetGUID(),
true);
}
}
events.RepeatEvent(30 * IN_MILLISECONDS);
break;
case EVENT_MISSILE:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(pTarget, SPELL_MISSILE_BARRAGE);
events.RepeatEvent(1500);
break;
case EVENT_VENT:
DoCastAOE(SPELL_FLAME_VENTS);
events.RepeatEvent(20 * IN_MILLISECONDS);
break;
case EVENT_SPEED:
DoCastAOE(SPELL_GATHERING_SPEED);
events.RepeatEvent(15 * IN_MILLISECONDS);
break;
case EVENT_SUMMON:
if (summons.size() < 15) // 4seat+1turret+10lift
if (Creature* pLift = DoSummonFlyer(MOB_MECHANOLIFT, me, 30.0f, 50.0f, 0))
pLift->GetMotionMaster()->MoveRandom(100);
events.RepeatEvent(2 * IN_MILLISECONDS);
break;
case EVENT_SHUTDOWN:
DoScriptText(
RAND(SAY_OVERLOAD_1, SAY_OVERLOAD_2, SAY_OVERLOAD_3),
me);
InstallAdds(true);
me->MonsterTextEmote(EMOTE_OVERLOAD, 0, true);
me->AddAura(SPELL_SYSTEMS_SHUTDOWN, me);
me->RemoveAurasDueToSpell(SPELL_GATHERING_SPEED);
events.CancelEvent(EVENT_SHUTDOWN);
break;
case EVENT_REPAIR:
me->MonsterTextEmote(EMOTE_REPAIR, 0, true);
me->ClearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT);
InstallAdds(false);
events.CancelEvent(EVENT_REPAIR);
break;
case EVENT_THORIM_S_HAMMER: // Tower of Storms
for (uint8 i = 0; i < 7; ++i) {
if (Creature* pThorim = DoSummon(MOB_THORIM_BEACON, me, float(urand(20, 60)), 20000, TEMPSUMMON_TIMED_DESPAWN))
pThorim->GetMotionMaster()->MoveRandom(100);
}
DoScriptText(SAY_TOWER_STORM, me);
events.CancelEvent(EVENT_THORIM_S_HAMMER);
break;
case EVENT_MIMIRON_S_INFERNO: // Tower of Flames
me->SummonCreature(MOB_MIMIRON_BEACON, 390.93f, -13.91f,
409.81f);
DoScriptText(SAY_TOWER_FLAME, me);
events.CancelEvent(EVENT_MIMIRON_S_INFERNO);
break;
case EVENT_HODIR_S_FURY: // Tower of Frost
for (uint8 i = 0; i < 7; ++i) {
if (Creature* pHodir = DoSummon(MOB_HODIR_BEACON, me, 50, 0))
pHodir->GetMotionMaster()->MoveRandom(100);
}
DoScriptText(SAY_TOWER_FROST, me);
events.CancelEvent(EVENT_HODIR_S_FURY);
break;
case EVENT_FREYA_S_WARD: // Tower of Nature
DoScriptText(SAY_TOWER_NATURE, me);
StartFreyaEvent();
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(pTarget, SPELL_FREYA_S_WARD);
events.CancelEvent(EVENT_FREYA_S_WARD);
break;
default:
events.PopEvent();
break;
}
/*if (me->IsWithinMeleeRange(me->getVictim())) //bugged spell casts on units that are boarded on leviathan
DoSpellAttackIfReady(SPELL_BATTERING_RAM);*/
DoMeleeAttackIfReady();
}
void StartFreyaEvent() //summon these 4 on each corner wich wil spawn additional hostile mobs
{
me->SummonCreature(MOB_FREYA_BEACON, 377.02f, -119.10f, 409.81f);
me->SummonCreature(MOB_FREYA_BEACON, 377.02f, 54.78f, 409.81f);
me->SummonCreature(MOB_FREYA_BEACON, 185.62f, 54.78f, 409.81f);
me->SummonCreature(MOB_FREYA_BEACON, 185.62f, -119.10f, 409.81f);
}
void DoAction(const int32 uiAction) {
// Start encounter
if (uiAction == 10) {
me->SetHomePosition(354.8771f, -12.90240f, 409.803f, 0);
me->GetMotionMaster()->MoveCharge(354.8771f, -12.90240f,
409.803f); //position center
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(
UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE
| UNIT_FLAG_STUNNED);
return;
}
if (uiAction && uiAction <= 4) // Tower destruction, debuff leviathan loot and reduce active tower
{
if (me->HasLootMode(31) && uiActiveTowers == 4) {
me->RemoveLootMode(LOOT_MODE_HARD_MODE_4);
--uiActiveTowers;
}
if (me->HasLootMode(15) && uiActiveTowers == 3) {
me->RemoveLootMode(LOOT_MODE_HARD_MODE_3);
--uiActiveTowers;
}
if (me->HasLootMode(7) && uiActiveTowers == 2) {
me->RemoveLootMode(LOOT_MODE_HARD_MODE_2);
--uiActiveTowers;
}
if (me->HasLootMode(3) && uiActiveTowers == 1) {
me->RemoveLootMode(LOOT_MODE_HARD_MODE_1);
--uiActiveTowers;
}
}
switch (uiAction) {
case 0: // Activate hard-mode setting counter to 4 towers, enable all towers apply buffs on levithian
ActiveTowers = true;
towerOfStorms = true;
towerOfLife = true;
towerOfFlames = true;
towerOfFrost = true;
me->SetLootMode(31);
break;
case 1: // Tower of Storms destroyed
towerOfStorms = false;
break;
case 2: // Tower of Flames destroyed
towerOfFlames = false;
break;
case 3: // Tower of Frost destroyed
towerOfFrost = false;
break;
case 4: // Tower of Nature destroyed
towerOfLife = false;
break;
}
}
};
};
//#define BOSS_DEBUG
class boss_flame_leviathan_seat: public CreatureScript {
public:
boss_flame_leviathan_seat() :
CreatureScript("boss_flame_leviathan_seat") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_flame_leviathan_seatAI(pCreature);
}
struct boss_flame_leviathan_seatAI: public PassiveAI {
boss_flame_leviathan_seatAI(Creature* pCreature) :
PassiveAI(pCreature), vehicle(pCreature->GetVehicleKit()) {
assert(vehicle);
#ifdef BOSS_DEBUG
me->SetReactState(REACT_AGGRESSIVE);
#endif
}
Vehicle* vehicle;
#ifdef BOSS_DEBUG
void MoveInLineOfSight(Unit *who)
{
if (who->GetTypeId() == TYPEID_PLAYER && CAST_PLR(who)->isGameMaster()
&& !who->GetVehicle() && vehicle->GetPassenger(SEAT_TURRET))
who->EnterVehicle(vehicle, SEAT_PLAYER);
}
#endif
void PassengerBoarded(Unit* who, int8 seatId, bool apply) {
if (!me->GetVehicle())
return;
if (seatId == SEAT_PLAYER) {
if (!apply)
return;
else
DoScriptText(SAY_PLAYER_RIDING, me);
if (Creature* pTurret = CAST_CRE(vehicle->GetPassenger(SEAT_TURRET))) {
pTurret->setFaction(me->GetVehicleBase()->getFaction());
pTurret->SetUInt32Value(UNIT_FIELD_FLAGS, 0); // unselectable
pTurret->AI()->AttackStart(who);
}
if (Unit* pDevice = CAST_CRE(vehicle->GetPassenger(SEAT_DEVICE))) {
pDevice->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
pDevice->RemoveFlag(UNIT_FIELD_FLAGS,
UNIT_FLAG_NOT_SELECTABLE);
}
}
//else //throw passenger bugged, when fixed uncomment this part.
// if (seatId == SEAT_TURRET)
// {
// if (apply)
// return;
// if (Unit* device = vehicle->GetPassenger(SEAT_DEVICE))
// {
// device->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
// device->SetUInt32Value(UNIT_FIELD_FLAGS, 0); // unselectable
// }
// }
}
};
};
class boss_flame_leviathan_defense_cannon: public CreatureScript {
public:
boss_flame_leviathan_defense_cannon() :
CreatureScript("boss_flame_leviathan_defense_cannon") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_flame_leviathan_defense_cannonAI(pCreature);
}
struct boss_flame_leviathan_defense_cannonAI: public ScriptedAI {
boss_flame_leviathan_defense_cannonAI(Creature* pCreature) :
ScriptedAI(pCreature) {
}
uint32 NapalmTimer;
void Reset() {
NapalmTimer = 5000;
}
void UpdateAI(const uint32 diff) {
if (!UpdateVictim())
return;
if (NapalmTimer <= diff) {
if (Unit* pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0)) {
if (CanAIAttack(pTarget))
DoCast(pTarget, SPELL_NAPALM, true);
}
NapalmTimer = 5000;
} else
NapalmTimer -= diff;
}
bool CanAIAttack(const Unit *who) const {
if (who->GetTypeId() != TYPEID_PLAYER || !who->GetVehicle()
|| who->GetVehicleBase()->GetEntry() != 33114)
return false;
return true;
}
};
};
class boss_flame_leviathan_defense_turret: public CreatureScript {
public:
boss_flame_leviathan_defense_turret() :
CreatureScript("boss_flame_leviathan_defense_turret") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_flame_leviathan_defense_turretAI(pCreature);
}
struct boss_flame_leviathan_defense_turretAI: public TurretAI {
boss_flame_leviathan_defense_turretAI(Creature *c) :
TurretAI(c) {
}
void DamageTaken(Unit* who, uint32 &damage) {
if (!CanAIAttack(who))
damage = 0;
}
bool CanAIAttack(const Unit *who) const {
if (who->GetTypeId() != TYPEID_PLAYER || !who->GetVehicle()
|| who->GetVehicleBase()->GetEntry() != 33114)
return false;
return true;
}
};
};
class boss_flame_leviathan_overload_device: public CreatureScript {
public:
boss_flame_leviathan_overload_device() :
CreatureScript("boss_flame_leviathan_overload_device") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_flame_leviathan_overload_deviceAI(pCreature);
}
struct boss_flame_leviathan_overload_deviceAI: public PassiveAI {
boss_flame_leviathan_overload_deviceAI(Creature* pCreature) :
PassiveAI(pCreature) {
instance = pCreature->GetInstanceScript();
}
InstanceScript *instance;
void DoAction(const int32 param) {
if (param == EVENT_SPELLCLICK) {
if (me->GetVehicle()) {
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
if (Unit* pPlayer = me->GetVehicle()->GetPassenger(SEAT_PLAYER)) {
me->GetVehicleBase()->CastSpell(pPlayer,
SPELL_SMOKE_TRAIL, true);
pPlayer->GetMotionMaster()->MoveKnockbackFrom(
me->GetVehicleBase()->GetPositionX(),
me->GetVehicleBase()->GetPositionY(), 30, 30);
pPlayer->ExitVehicle();
}
}
}
}
};
};
class boss_flame_leviathan_safety_container: public CreatureScript {
public:
boss_flame_leviathan_safety_container() :
CreatureScript("boss_flame_leviathan_safety_container") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_flame_leviathan_safety_containerAI(pCreature);
}
struct boss_flame_leviathan_safety_containerAI: public PassiveAI {
boss_flame_leviathan_safety_containerAI(Creature* pCreature) :
PassiveAI(pCreature) {
}
void JustDied(Unit* /*killer*/) {
float x, y, z;
me->GetPosition(x, y, z);
z = me->GetMap()->GetHeight(x, y, z);
me->GetMotionMaster()->MovePoint(0, x, y, z);
me->GetMap()->CreatureRelocation(me, x, y, z, 0);
}
void UpdateAI(const uint32 /*diff*/) {
}
};
};
class npc_mechanolift: public CreatureScript {
public:
npc_mechanolift() :
CreatureScript("npc_mechanolift") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_mechanoliftAI(pCreature);
}
struct npc_mechanoliftAI: public PassiveAI {
npc_mechanoliftAI(Creature* pCreature) :
PassiveAI(pCreature), vehicle(pCreature->GetVehicleKit()) {
assert(vehicle);
}
Vehicle* vehicle;
uint32 MoveTimer;
void Reset() {
MoveTimer = 0;
me->GetMotionMaster()->MoveRandom(50);
}
void JustDied(Unit* pKiller) {
me->GetMotionMaster()->MoveTargetedHome();
Creature* pLiquid = DoSummon(MOB_LIQUID, me, 0);
if (pLiquid) {
pLiquid->CastSpell(pLiquid, SPELL_LIQUID_PYRITE, true);
pLiquid->GetMotionMaster()->MoveFall(pKiller->GetPositionZ());
}
}
void MovementInform(uint32 /*type*/, uint32 id) {
if (id == 1) {
Creature* pContainer = me->FindNearestCreature(MOB_CONTAINER, 5,
true);
if (pContainer)
pContainer->EnterVehicle(me);
}
}
void UpdateAI(const uint32 diff) {
if (MoveTimer <= diff) {
if (me->GetVehicleKit()->HasEmptySeat(-1)) {
Creature* pContainer = me->FindNearestCreature(
MOB_CONTAINER, 50, true);
if (pContainer && !pContainer->GetVehicle())
me->GetMotionMaster()->MovePoint(1,
pContainer->GetPositionX(),
pContainer->GetPositionY(),
pContainer->GetPositionZ());
}
MoveTimer = 30000; //check next 30 seconds
} else
MoveTimer -= diff;
}
};
};
class spell_pool_of_tar: public CreatureScript {
public:
spell_pool_of_tar() :
CreatureScript("spell_pool_of_tar") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new spell_pool_of_tarAI(pCreature);
}
struct spell_pool_of_tarAI: public PassiveAI {
spell_pool_of_tarAI(Creature* pCreature) :
PassiveAI(pCreature) {
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->AddAura(SPELL_TAR_PASSIVE, me);
}
void DamageTaken(Unit * /*who*/, uint32 &damage) {
damage = 0;
}
void SpellHit(Unit* /*caster*/, const SpellEntry* pSpell) {
if (pSpell->SchoolMask & SPELL_SCHOOL_MASK_FIRE
&& !me->HasAura(SPELL_BLAZE))
me->CastSpell(me, SPELL_BLAZE, true);
}
};
};
class npc_colossus: public CreatureScript {
public:
npc_colossus() :
CreatureScript("npc_colossus") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_colossusAI(pCreature);
}
struct npc_colossusAI: public ScriptedAI {
npc_colossusAI(Creature* pCreature) :
ScriptedAI(pCreature) {
instance = pCreature->GetInstanceScript();
}
InstanceScript *instance;
void JustDied(Unit* /*Who*/) {
if (me->GetHomePosition().IsInDist(Center, 50.f))
instance->SetData(TYPE_COLOSSUS,
instance->GetData(TYPE_COLOSSUS) + 1);
}
void UpdateAI(const uint32 /*diff*/) {
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
};
};
class npc_thorims_hammer: public CreatureScript {
public:
npc_thorims_hammer() :
CreatureScript("npc_thorims_hammer") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_thorims_hammerAI(pCreature);
}
struct npc_thorims_hammerAI: public ScriptedAI {
npc_thorims_hammerAI(Creature* pCreature) :
ScriptedAI(pCreature) {
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->AddAura(AURA_DUMMY_BLUE, me);
}
void MoveInLineOfSight(Unit* who) {
if (who->GetTypeId() == TYPEID_PLAYER && who->IsVehicle()
&& me->IsInRange(who, 0, 10, false)) {
if (Creature* pTrigger = DoSummonFlyer(NPC_THORIM_TARGET_BEACON, me, 20, 0, 1000, TEMPSUMMON_TIMED_DESPAWN))
pTrigger->CastSpell(who, SPELL_THORIM_S_HAMMER, true);
}
}
void Reset() {
}
void UpdateAI(const uint32 /*diff*/) {
if (!me->HasAura(AURA_DUMMY_BLUE))
me->AddAura(AURA_DUMMY_BLUE, me);
if (!UpdateVictim())
return;
}
};
};
class npc_mimirons_inferno: public CreatureScript {
public:
npc_mimirons_inferno() :
CreatureScript("npc_mimirons_inferno") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_mimirons_infernoAI(pCreature);
}
struct npc_mimirons_infernoAI: public npc_escortAI {
npc_mimirons_infernoAI(Creature* pCreature) :
npc_escortAI(pCreature) {
me->SetFlag(UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
me->AddAura(AURA_DUMMY_YELLOW, me);
me->SetReactState(REACT_PASSIVE);
}
void WaypointReached(uint32 /*i*/) {
}
void Reset() {
infernoTimer = 2000;
}
uint32 infernoTimer;
void UpdateAI(const uint32 diff) {
npc_escortAI::UpdateAI(diff);
if (!HasEscortState(STATE_ESCORT_ESCORTING)) {
Start(false, true, 0, NULL, false, true);
} else {
if (infernoTimer <= diff) {
if (Creature* pTrigger = DoSummonFlyer(NPC_MIMIRON_TARGET_BEACON, me, 20, 0, 1000, TEMPSUMMON_TIMED_DESPAWN)) {
pTrigger->CastSpell(me->GetPositionX(),
me->GetPositionY(), me->GetPositionZ(),
SPELL_MIMIRON_S_INFERNO, true);
infernoTimer = 2000;
}
} else
infernoTimer -= diff;
if (!me->HasAura(AURA_DUMMY_YELLOW))
me->AddAura(AURA_DUMMY_YELLOW, me);
}
}
};
};
class npc_hodirs_fury: public CreatureScript {
public:
npc_hodirs_fury() :
CreatureScript("npc_hodirs_fury") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_hodirs_furyAI(pCreature);
}
struct npc_hodirs_furyAI: public ScriptedAI {
npc_hodirs_furyAI(Creature* pCreature) :
ScriptedAI(pCreature) {
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->AddAura(AURA_DUMMY_GREEN, me);
}
void MoveInLineOfSight(Unit* who) {
if (who->GetTypeId() == TYPEID_PLAYER && who->IsVehicle()
&& me->IsInRange(who, 0, 5, false)) {
if (Creature* pTrigger = DoSummonFlyer(NPC_HODIR_TARGET_BEACON, me, 20, 0, 1000, TEMPSUMMON_TIMED_DESPAWN))
pTrigger->CastSpell(who, SPELL_HODIR_S_FURY, true);
}
}
void Reset() {
}
void UpdateAI(const uint32 /*diff*/) {
if (!me->HasAura(AURA_DUMMY_GREEN))
me->AddAura(AURA_DUMMY_GREEN, me);
if (!UpdateVictim())
return;
}
};
};
class npc_freyas_ward: public CreatureScript {
public:
npc_freyas_ward() :
CreatureScript("npc_freyas_ward") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_freyas_wardAI(pCreature);
}
struct npc_freyas_wardAI: public ScriptedAI {
npc_freyas_wardAI(Creature* pCreature) :
ScriptedAI(pCreature) {
me->AddAura(AURA_DUMMY_GREEN, me);
}
uint32 summonTimer;
void Reset() {
summonTimer = 5000;
}
void UpdateAI(const uint32 diff) {
if (summonTimer <= diff) {
DoCast(SPELL_FREYA_S_WARD_EFFECT_1);
DoCast(SPELL_FREYA_S_WARD_EFFECT_2);
summonTimer = 20000;
} else
summonTimer -= diff;
if (!me->HasAura(AURA_DUMMY_GREEN))
me->AddAura(AURA_DUMMY_GREEN, me);
if (!UpdateVictim())
return;
}
};
};
class npc_freya_ward_summon: public CreatureScript {
public:
npc_freya_ward_summon() :
CreatureScript("npc_freya_ward_summon") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_freya_ward_summonAI(pCreature);
}
struct npc_freya_ward_summonAI: public ScriptedAI {
npc_freya_ward_summonAI(Creature* pCreature) :
ScriptedAI(pCreature) {
pCreature->GetMotionMaster()->MoveRandom(100);
}
uint32 lashTimer;
void Reset() {
lashTimer = 5000;
}
void UpdateAI(const uint32 diff) {
if (!UpdateVictim())
return;
if (lashTimer <= diff) {
DoCast(SPELL_LASH);
lashTimer = 20000;
} else
lashTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
//npc lore keeper
#define GOSSIP_ITEM_1 "Activate secondary defensive systems"
#define GOSSIP_ITEM_2 "Confirmed"
class npc_lorekeeper: public CreatureScript {
public:
npc_lorekeeper() :
CreatureScript("npc_lorekeeper") {
}
bool OnGossipSelect(Player* pPlayer, Creature* pCreature,
uint32 /*uiSender*/, uint32 uiAction) {
pPlayer->PlayerTalkClass->ClearMenus();
InstanceScript* instance = pCreature->GetInstanceScript();
switch (uiAction) {
case GOSSIP_ACTION_INFO_DEF + 1:
if (pPlayer) {
pPlayer->PrepareGossipMenu(pCreature);
instance->instance->LoadGrid(364, -16); //make sure leviathan is loaded
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID());
}
break;
case GOSSIP_ACTION_INFO_DEF + 2:
if (pPlayer)
pPlayer->CLOSE_GOSSIP_MENU();
if (Creature* pLeviathan = instance->instance->GetCreature(instance->GetData64(TYPE_LEVIATHAN))) {
CAST_AI(boss_flame_leviathan::boss_flame_leviathanAI, (pLeviathan->AI()))->DoAction(
0); //enable hard mode activating the 4 additional events spawning additional vehicles
pCreature->SetVisible(false);
pCreature->AI()->DoAction(0); // spawn the vehicles
if (Creature* Delorah = pCreature->FindNearestCreature(NPC_DELORAH, 1000, true)) {
if (Creature* Branz = pCreature->FindNearestCreature(NPC_BRANZ_BRONZBEARD, 1000, true)) {
Delorah->GetMotionMaster()->MovePoint(0,
Branz->GetPositionX() - 4,
Branz->GetPositionY(), Branz->GetPositionZ());
//TODO DoScriptText(xxxx, Delorah, Branz); when reached at branz
}
}
}
break;
}
return true;
}
bool OnGossipHello(Player* pPlayer, Creature* pCreature) {
InstanceScript* instance = pCreature->GetInstanceScript();
if (instance && instance->GetData(TYPE_LEVIATHAN) != DONE && pPlayer) {
pPlayer->PrepareGossipMenu(pCreature);
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID());
}
return true;
}
CreatureAI* GetAI(Creature* pCreature) const {
return new npc_lorekeeperAI(pCreature);
}
struct npc_lorekeeperAI: public ScriptedAI {
npc_lorekeeperAI(Creature* pCreature) :
ScriptedAI(pCreature) {
instance = pCreature->GetInstanceScript();
}
InstanceScript* instance;
void DoAction(const int32 uiAction) {
// Start encounter
if (uiAction == 0) {
for (int32 i = 0; i < RAID_MODE(2, 5); ++i)
DoSummon(VEHICLE_SIEGE, PosSiege[i], 3000,
TEMPSUMMON_CORPSE_TIMED_DESPAWN);
for (int32 i = 0; i < RAID_MODE(2, 5); ++i)
DoSummon(VEHICLE_CHOPPER, PosChopper[i], 3000,
TEMPSUMMON_CORPSE_TIMED_DESPAWN);
for (int32 i = 0; i < RAID_MODE(2, 5); ++i)
DoSummon(VEHICLE_DEMOLISHER, PosDemolisher[i], 3000,
TEMPSUMMON_CORPSE_TIMED_DESPAWN);
return;
}
}
};
};
//enable hardmode
////npc_brann_bronzebeard this requires more work involving area triggers. if reached this guy speaks through his radio..
//#define GOSSIP_ITEM_1 "xxxxx"
//#define GOSSIP_ITEM_2 "xxxxx"
//
/*
class npc_brann_bronzebeard : public CreatureScript
{
public:
npc_brann_bronzebeard() : CreatureScript("npc_brann_bronzebeard") { }
//bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction)
//{
// pPlayer->PlayerTalkClass->ClearMenus();
// switch(uiAction)
// {
// case GOSSIP_ACTION_INFO_DEF+1:
// if (pPlayer)
// {
// pPlayer->PrepareGossipMenu(pCreature);
//
// pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
// pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID());
// }
// break;
// case GOSSIP_ACTION_INFO_DEF+2:
// if (pPlayer)
// pPlayer->CLOSE_GOSSIP_MENU();
// if (Creature* Lorekeeper = pCreature->FindNearestCreature(NPC_LOREKEEPER, 1000, true)) //lore keeper of lorgannon
// Lorekeeper->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
// break;
// }
// return true;
//}
//bool OnGossipHello(Player* pPlayer, Creature* pCreature)
//{
// InstanceScript* instance = pCreature->GetInstanceScript();
// if (instance && instance->GetData(TYPE_LEVIATHAN) !=DONE)
// {
// pPlayer->PrepareGossipMenu(pCreature);
//
// pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
// pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID());
// }
// return true;
//}
//
}
*/
class go_ulduar_tower: public GameObjectScript {
public:
go_ulduar_tower() :
GameObjectScript("go_ulduar_tower") {
}
void OnDestroyed(Player* /*pPlayer*/, GameObject* pGO, uint32 /*value*/) {
InstanceScript* instance = pGO->GetInstanceScript();
switch (pGO->GetEntry()) {
case GO_TOWER_OF_STORMS:
instance->ProcessEvent(pGO, EVENT_TOWER_OF_STORM_DESTROYED);
break;
case GO_TOWER_OF_FLAMES:
instance->ProcessEvent(pGO, EVENT_TOWER_OF_FLAMES_DESTROYED);
break;
case GO_TOWER_OF_FROST:
instance->ProcessEvent(pGO, EVENT_TOWER_OF_FROST_DESTROYED);
break;
case GO_TOWER_OF_LIFE:
instance->ProcessEvent(pGO, EVENT_TOWER_OF_LIFE_DESTROYED);
break;
}
Creature* trigger = pGO->FindNearestCreature(
NPC_ULDUAR_GAUNTLET_GENERATOR, 15.0f, true);
if (trigger)
trigger->DisappearAndDie();
}
};
class at_RX_214_repair_o_matic_station: public AreaTriggerScript {
public:
at_RX_214_repair_o_matic_station() :
AreaTriggerScript("at_RX_214_repair_o_matic_station") {
}
bool OnTrigger(Player* pPlayer, const AreaTriggerEntry* /*pAt*/) {
if (Creature* vehicle = pPlayer->GetVehicleCreatureBase()) {
if (!vehicle->HasAura(SPELL_AUTO_REPAIR)) {
pPlayer->MonsterTextEmote(EMOTE_REPAIR, pPlayer->GetGUID(),
true);
pPlayer->CastSpell(vehicle, SPELL_AUTO_REPAIR, true);
}
}
return true;
}
};
void AddSC_boss_flame_leviathan() {
new boss_flame_leviathan();
new boss_flame_leviathan_seat();
new boss_flame_leviathan_defense_turret();
new boss_flame_leviathan_overload_device();
new boss_flame_leviathan_safety_container();
new npc_mechanolift();
new spell_pool_of_tar();
new npc_colossus();
new npc_thorims_hammer();
new npc_mimirons_inferno();
new npc_hodirs_fury();
new npc_freyas_ward();
new npc_freya_ward_summon();
new npc_lorekeeper();
// new npc_brann_bronzebeard();
new go_ulduar_tower();
new at_RX_214_repair_o_matic_station();
}
| 28.650425
| 147
| 0.697395
|
Zone-Emu
|
410d006626309f201c89f562c383f311198a0a96
| 1,057
|
cpp
|
C++
|
proxygen/lib/utils/test/UtilTest.cpp
|
JackBoosY/proxygen
|
ad5252b83514f3550380229adfd24beae0fa510d
|
[
"BSD-3-Clause"
] | 1
|
2021-01-15T01:55:53.000Z
|
2021-01-15T01:55:53.000Z
|
proxygen/lib/utils/test/UtilTest.cpp
|
JackBoosY/proxygen
|
ad5252b83514f3550380229adfd24beae0fa510d
|
[
"BSD-3-Clause"
] | null | null | null |
proxygen/lib/utils/test/UtilTest.cpp
|
JackBoosY/proxygen
|
ad5252b83514f3550380229adfd24beae0fa510d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/portability/GTest.h>
#include <proxygen/lib/utils/UtilInl.h>
using namespace proxygen;
TEST(UtilTest, CaseInsensitiveEqual) {
ASSERT_TRUE(caseInsensitiveEqual("foo", "FOO"));
ASSERT_TRUE(caseInsensitiveEqual(std::string("foo"), "FOO"));
ASSERT_FALSE(caseInsensitiveEqual(std::string("foo"), "FOO2"));
ASSERT_FALSE(caseInsensitiveEqual("fo", "FOO"));
ASSERT_FALSE(caseInsensitiveEqual("FO", "FOO"));
}
TEST(UtilTest, findLastOf) {
folly::StringPiece p1("");
folly::StringPiece p2(".");
folly::StringPiece p3("..");
folly::StringPiece p4("abc");
folly::StringPiece p5("abc.def");
EXPECT_EQ(findLastOf(p1, '.'), std::string::npos);
EXPECT_EQ(findLastOf(p2, '.'), 0);
EXPECT_EQ(findLastOf(p3, '.'), 1);
EXPECT_EQ(findLastOf(p4, '.'), std::string::npos);
EXPECT_EQ(findLastOf(p5, '.'), 3);
}
| 29.361111
| 72
| 0.690634
|
JackBoosY
|
410d999061a714e752d2b0f6c15236dd1454014c
| 30,634
|
cpp
|
C++
|
src/Renderer.cpp
|
demarle/VisRTX
|
abd6a7040c2d7521750b9b787b9085c053894d17
|
[
"BSD-3-Clause"
] | 4
|
2019-04-04T17:23:18.000Z
|
2019-09-29T11:32:56.000Z
|
src/Renderer.cpp
|
straaljager/VisRTX
|
abd6a7040c2d7521750b9b787b9085c053894d17
|
[
"BSD-3-Clause"
] | null | null | null |
src/Renderer.cpp
|
straaljager/VisRTX
|
abd6a7040c2d7521750b9b787b9085c053894d17
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 "Renderer.h"
#include "FrameBuffer.h"
#include "Model.h"
#include "ProgramLoader.h"
#include "Camera.h"
#include "Texture.h"
#include "Material.h"
#include "Light.h"
#include "Geometry.h"
#include "Config.h"
#include "Pathtracer/Light.h"
#include "Pathtracer/Common.h"
#include "Pathtracer/Pick.h"
#include <fstream>
#include <algorithm>
#include <cstring>
namespace VisRTX
{
namespace Impl
{
Renderer::Renderer()
{
// Load programs
ProgramLoader& loader = ProgramLoader::Get();
this->rayGenProgram = loader.LoadPathtracerProgram("RayGen");
this->rayGenPickProgram = loader.LoadPathtracerProgram("RayGenPick");
this->missProgram = loader.LoadPathtracerProgram("Miss");
this->missPickProgram = loader.LoadPathtracerProgram("MissPick");
this->bufferCastProgram = loader.LoadPathtracerProgram("BufferCast");
// Defaults
this->SetSamplesPerPixel(1);
this->SetAlphaCutoff(1e-3f);
this->SetWriteBackground(true);
uint32_t minBounces = 4;
uint32_t maxBounces = 8;
float epsilon = 1e-3f;
bool toneMapping = true;
DenoiserType denoiser = DenoiserType::NONE;
float clampDirect = 0.0f;
float clampIndirect = 0.0f;
bool sampleAllLights = true;
// Env var overrides
if (const char* str = std::getenv("VISRTX_MIN_BOUNCES"))
{
minBounces = (uint32_t)atoi(str);
this->minBouncesFixed = true;
}
if (const char* str = std::getenv("VISRTX_MAX_BOUNCES"))
{
maxBounces = (uint32_t)atoi(str);
this->maxBouncesFixed = true;
}
if (const char* str = std::getenv("VISRTX_EPSILON"))
{
epsilon = (float)atof(str);
this->epsilonFixed = true;
}
if (const char* str = std::getenv("VISRTX_TONE_MAPPING"))
{
toneMapping = atoi(str) > 0;
this->toneMappingFixed = true;
}
if (const char* str = std::getenv("VISRTX_DENOISER"))
{
denoiser = (atoi(str) > 0) ? DenoiserType::AI : DenoiserType::NONE;
this->denoiserFixed = true;
}
if (const char* str = std::getenv("VISRTX_CLAMP_DIRECT"))
{
clampDirect = (float)atof(str);
this->clampDirectFixed = true;
}
if (const char* str = std::getenv("VISRTX_CLAMP_INDIRECT"))
{
clampIndirect = (float)atof(str);
this->clampIndirectFixed = true;
}
if (const char* str = std::getenv("VISRTX_SAMPLE_ALL_LIGHTS"))
{
sampleAllLights = atoi(str) > 0;
this->sampleAllLightsFixed = true;
}
this->ignoreOverrides = true;
this->SetNumBounces(minBounces, maxBounces);
this->SetEpsilon(epsilon);
this->SetToneMapping(toneMapping, 2.2f, Vec3f(1.0f, 1.0f, 1.0f), 1.0f, 0.8f, 0.2f, 1.2f, 0.8f);
this->SetDenoiser(denoiser);
this->SetFireflyClamping(clampDirect, clampIndirect);
this->SetSampleAllLights(sampleAllLights);
this->ignoreOverrides = false;
// Debug warnings
#ifdef TEST_DIRECT_ONLY
std::cout << "*** Warning: Testing mode! Brute force (light evaluation) only ***" << std::endl;
#endif
#ifdef TEST_NEE_ONLY
std::cout << "*** Warning: Testing mode! Next event estimation (light sampling) only ***" << std::endl;
#endif
#ifdef TEST_MIS
std::cout << "*** Warning: Testing mode! Multiple importance sampling ***" << std::endl;
#endif
}
Renderer::~Renderer()
{
if (this->model)
this->model->Release();
if (this->camera)
this->camera->Release();
for (VisRTX::Light* light : this->lights)
if (light)
light->Release();
Destroy(rayGenProgram.get());
Destroy(rayGenPickProgram.get());
Destroy(missProgram.get());
Destroy(missPickProgram.get());
Destroy(bufferCastProgram.get());
Destroy(basicMaterialParametersBuffer.get());
Destroy(mdlMaterialParametersBuffer.get());
Destroy(directLightsBuffer.get());
Destroy(missLightsBuffer.get());
Destroy(pickBuffer.get());
}
void Renderer::Render(VisRTX::FrameBuffer* frameBuffer)
{
if (!frameBuffer)
return;
// Initialization prepass
if (!this->Init())
return;
optix::Context context = OptiXContext::Get();
/*
* Framebuffer
*/
VisRTX::Impl::FrameBuffer* fb = dynamic_cast<VisRTX::Impl::FrameBuffer*>(frameBuffer);
this->rayGenProgram["accumulationBuffer"]->setBuffer(fb->accumulationBuffer);
this->rayGenProgram["frameBuffer"]->setBuffer(fb->frameBuffer);
this->rayGenProgram["ucharFrameBuffer"]->setBuffer(fb->ucharFrameBuffer);
this->rayGenProgram["depthBuffer"]->setBuffer(fb->depthBuffer);
//this->rayGenProgram["albedoBuffer"]->setBuffer(fb->albedoBuffer);
this->bufferCastProgram["frameBuffer"]->setBuffer(fb->frameBuffer);
this->bufferCastProgram["ucharFrameBuffer"]->setBuffer(fb->ucharFrameBuffer);
/*
* Material buffers
*/
if (BasicMaterial::parametersDirty)
{
this->basicMaterialParametersBuffer->setSize(BasicMaterial::parameters.GetNumElements());
const uint32_t numBytes = BasicMaterial::parameters.GetNumBytes();
if (numBytes > 0)
{
memcpy(this->basicMaterialParametersBuffer->map(0, RT_BUFFER_MAP_WRITE_DISCARD), BasicMaterial::parameters.GetData(), numBytes);
this->basicMaterialParametersBuffer->unmap();
}
BasicMaterial::parametersDirty = false;
}
if (MDLMaterial::parametersDirty)
{
this->mdlMaterialParametersBuffer->setSize(MDLMaterial::parameters.GetNumElements());
const uint32_t numBytes = MDLMaterial::parameters.GetNumBytes();
if (numBytes > 0)
{
memcpy(this->mdlMaterialParametersBuffer->map(0, RT_BUFFER_MAP_WRITE_DISCARD), MDLMaterial::parameters.GetData(), numBytes);
this->mdlMaterialParametersBuffer->unmap();
}
MDLMaterial::parametersDirty = false;
}
/*
* Depth clipping/normalization
*/
this->rayGenProgram["clipMin"]->setFloat(fb->depthClipMin);
this->rayGenProgram["clipMax"]->setFloat(fb->depthClipMax);
this->rayGenProgram["clipDiv"]->setFloat(fb->depthClipDiv);
/*
* Camera
*/
VisRTX::Impl::Camera* camera = dynamic_cast<VisRTX::Impl::Camera*>(this->camera);
if (camera->dirty)
{
const optix::float3 cam_W = optix::normalize(camera->direction);
const optix::float3 cam_U = optix::normalize(optix::cross(camera->direction, camera->up));
const optix::float3 cam_V = optix::normalize(optix::cross(cam_U, cam_W));
if (this->camera->GetType() == CameraType::PERSPECTIVE)
{
VisRTX::Impl::PerspectiveCamera* perspectiveCam = dynamic_cast<VisRTX::Impl::PerspectiveCamera*>(this->camera);
const float vlen = tanf(0.5f * perspectiveCam->fovy * M_PIf / 180.0f);
const float ulen = vlen * perspectiveCam->aspect;
this->rayGenProgram["cameraType"]->setInt(PERSPECTIVE_CAMERA);
this->rayGenProgram["pos"]->setFloat(perspectiveCam->position);
this->rayGenProgram["U"]->setFloat(cam_U * ulen);
this->rayGenProgram["V"]->setFloat(cam_V * vlen);
this->rayGenProgram["W"]->setFloat(cam_W);
}
else if (this->camera->GetType() == CameraType::ORTHOGRAPHIC)
{
VisRTX::Impl::OrthographicCamera* orthoCam = dynamic_cast<VisRTX::Impl::OrthographicCamera*>(this->camera);
this->rayGenProgram["cameraType"]->setInt(ORTHOGRAPHIC_CAMERA);
this->rayGenProgram["pos"]->setFloat(orthoCam->position);
this->rayGenProgram["U"]->setFloat(cam_U);
this->rayGenProgram["V"]->setFloat(cam_V);
this->rayGenProgram["W"]->setFloat(cam_W);
this->rayGenProgram["orthoWidth"]->setFloat(orthoCam->height * orthoCam->aspect);
this->rayGenProgram["orthoHeight"]->setFloat(orthoCam->height);
}
camera->dirty = false;
}
/*
* Denoiser
*/
bool useAIDenoiser = (this->denoiser == DenoiserType::AI) && fb->denoiserStage;
this->rayGenProgram["useAIDenoiser"]->setInt(useAIDenoiser);
/*
* Misc variables
*/
this->rayGenProgram["writeFrameBuffer"]->setInt((fb->format == FrameBufferFormat::RGBA32F || useAIDenoiser) ? 1 : 0);
this->rayGenProgram["writeUcharFrameBuffer"]->setInt((fb->format == FrameBufferFormat::RGBA8 && !useAIDenoiser) ? 1 : 0);
this->rayGenProgram["occlusionEpsilon"]->setFloat(this->epsilon);
this->rayGenProgram["alphaCutoff"]->setFloat(this->alphaCutoff);
this->rayGenProgram["numBouncesMin"]->setInt(this->minBounces);
this->rayGenProgram["numBouncesMax"]->setInt(this->maxBounces);
this->rayGenProgram["writeBackground"]->setInt(this->writeBackground);
this->rayGenProgram["fireflyClampingDirect"]->setFloat(this->fireflyClampingDirect);
this->rayGenProgram["fireflyClampingIndirect"]->setFloat(this->fireflyClampingIndirect);
this->rayGenProgram["sampleAllLights"]->setInt(this->sampleAllLights ? 1 : 0);
if (this->toneMapping)
{
this->rayGenProgram["toneMapping"]->setInt(1);
this->rayGenProgram["colorBalance"]->setFloat(this->colorBalance.r, this->colorBalance.g, this->colorBalance.b);
this->rayGenProgram["invGamma"]->setFloat(1.0f / this->gamma);
this->rayGenProgram["invWhitePoint"]->setFloat(this->brightness / this->whitePoint);
this->rayGenProgram["burnHighlights"]->setFloat(this->burnHighlights);
this->rayGenProgram["crushBlacks"]->setFloat(this->crushBlacks + this->crushBlacks + 1.0f);
this->rayGenProgram["saturation"]->setFloat(this->saturation);
}
else
{
this->rayGenProgram["toneMapping"]->setInt(0);
}
/*
* Depth of Field
*/
float focalDistance = 0.0f;
float apertureRadius = 0.0f;
if (this->camera->GetType() == CameraType::PERSPECTIVE)
{
VisRTX::Impl::PerspectiveCamera* perspectiveCam = dynamic_cast<VisRTX::Impl::PerspectiveCamera*>(this->camera);
focalDistance = perspectiveCam->focalDistance;
apertureRadius = perspectiveCam->apertureRadius;
}
/*
* Launch context
*/
const bool dofEnabled = focalDistance > 0.0f && apertureRadius > 0.0f;
this->LaunchAndDenoise(fb, this->samplesPerPixel, useAIDenoiser, dofEnabled, focalDistance, apertureRadius);
}
/*
* Common per-frame initialization used by both render and pick.
*/
bool Renderer::Init()
{
if (!this->model)
return false;
if (!this->camera)
return false;
optix::Context context = OptiXContext::Get();
/*
* On-demand initialization
*/
if (!this->initialized)
{
#ifdef VISRTX_USE_DEBUG_EXCEPTIONS
context->setExceptionProgram(RENDER_ENTRY_POINT, ProgramLoader::Get().exceptionProgram);
#endif
// Material buffers (global buffers shared across renderers/materials)
this->basicMaterialParametersBuffer = context->createBuffer(RT_BUFFER_INPUT, RT_FORMAT_USER);
this->basicMaterialParametersBuffer->setElementSize(sizeof(BasicMaterialParameters));
this->basicMaterialParametersBuffer->setSize(0);
context["basicMaterialParameters"]->setBuffer(this->basicMaterialParametersBuffer);
this->mdlMaterialParametersBuffer = context->createBuffer(RT_BUFFER_INPUT, RT_FORMAT_USER);
this->mdlMaterialParametersBuffer->setElementSize(sizeof(MDLMaterialParameters));
this->mdlMaterialParametersBuffer->setSize(0);
context["mdlMaterialParameters"]->setBuffer(this->mdlMaterialParametersBuffer);
// Light buffers
this->directLightsBuffer = context->createBuffer(RT_BUFFER_INPUT, RT_FORMAT_USER);
this->directLightsBuffer->setElementSize(sizeof(::Light));
this->directLightsBuffer->setSize(0);
this->missLightsBuffer = context->createBuffer(RT_BUFFER_INPUT, RT_FORMAT_USER);
this->missLightsBuffer->setElementSize(sizeof(::Light));
this->missLightsBuffer->setSize(0);
this->rayGenProgram["lights"]->setBuffer(this->directLightsBuffer);
this->missProgram["lights"]->setBuffer(this->missLightsBuffer);
this->missPickProgram["lights"]->setBuffer(this->missLightsBuffer);
this->rayGenProgram["numLights"]->setInt(0);
this->missProgram["numLights"]->setInt(0);
this->missPickProgram["numLights"]->setInt(0);
// Pick buffer
this->pickBuffer = context->createBuffer(RT_BUFFER_OUTPUT, RT_FORMAT_USER);
this->pickBuffer->setElementSize(sizeof(PickStruct));
this->pickBuffer->setSize(1);
this->rayGenPickProgram["pickResult"]->setBuffer(this->pickBuffer);
this->initialized = true;
}
/*
* Programs
*/
context->setRayGenerationProgram(RENDER_ENTRY_POINT, this->rayGenProgram);
context->setMissProgram(RADIANCE_RAY_TYPE, this->missProgram);
context->setRayGenerationProgram(BUFFER_CAST_ENTRY_POINT, this->bufferCastProgram);
context->setRayGenerationProgram(PICK_ENTRY_POINT, this->rayGenPickProgram);
context->setMissProgram(PICK_RAY_TYPE, this->missPickProgram);
/*
* Lights
*/
// Update dirty lights
for (VisRTX::Light* light : this->lights)
{
VisRTX::Impl::Light* l = dynamic_cast<VisRTX::Impl::Light*>(light);
if (l->dirty)
{
this->lightsNeedUpdate = true;
l->dirty = false;
}
}
// Keep list of light geometries up to date
dynamic_cast<VisRTX::Impl::Model*>(this->model)->UpdateLightGeometries(&this->lights);
// Update light buffers
if (this->lightsNeedUpdate)
{
this->lightsNeedUpdate = false;
std::vector<::Light> activeDirectLights;
std::vector<::Light> activeMissLights;
this->pickLights.clear();
for (VisRTX::Light* light : this->lights)
{
::Light tmp;
if (dynamic_cast<VisRTX::Impl::Light*>(light)->Set(tmp))
{
// Add light to light buffer
if (tmp.type == ::Light::POSITIONAL
|| tmp.type == ::Light::QUAD
|| tmp.type == ::Light::SPOT
|| tmp.type == ::Light::DIRECTIONAL)
{
activeDirectLights.push_back(tmp);
}
if (tmp.type == ::Light::AMBIENT
|| tmp.type == ::Light::HDRI
|| (tmp.type == ::Light::DIRECTIONAL && tmp.angularDiameter > 0.0f))
{
activeMissLights.push_back(tmp);
}
// Update pick lights
this->pickLights[tmp.id] = light;
}
}
// Update buffers
this->directLightsBuffer->setSize(activeDirectLights.size());
if (!activeDirectLights.empty())
{
memcpy(this->directLightsBuffer->map(0, RT_BUFFER_MAP_WRITE_DISCARD), &activeDirectLights[0], activeDirectLights.size() * sizeof(::Light));
this->directLightsBuffer->unmap();
}
this->missLightsBuffer->setSize(activeMissLights.size());
if (!activeMissLights.empty())
{
memcpy(this->missLightsBuffer->map(0, RT_BUFFER_MAP_WRITE_DISCARD), &activeMissLights[0], activeMissLights.size() * sizeof(::Light));
this->missLightsBuffer->unmap();
}
this->rayGenProgram["numLights"]->setInt((int)activeDirectLights.size());
this->missProgram["numLights"]->setInt((int)activeMissLights.size());
this->missPickProgram["numLights"]->setInt((int)activeMissLights.size());
}
return true;
}
void Renderer::LaunchAndDenoise(VisRTX::Impl::FrameBuffer* frameBuffer, int samplesPerPixel, bool useAIDenoiser, bool depthOfFieldEnabled, float focalDistance, float apertureRadius)
{
optix::Context context = OptiXContext::Get();
for (int i = 0; i < samplesPerPixel; ++i)
{
const bool lastSample = (i == samplesPerPixel - 1);
this->rayGenProgram["frameNumber"]->setInt(frameBuffer->frameNumber);
// Depth of field
if (depthOfFieldEnabled)
{
this->rayGenProgram["focalDistance"]->setFloat(focalDistance);
this->rayGenProgram["apertureRadius"]->setFloat(apertureRadius);
}
else
{
this->rayGenProgram["focalDistance"]->setFloat(-1.0f);
this->rayGenProgram["apertureRadius"]->setFloat(-1.0f);
}
// Write albedo
//int writeAlbedo = 0;
//if (useAIDenoiser && !frameBuffer->albedoWritten)
//{
// writeAlbedo = 1;
// frameBuffer->albedoWritten = true;
//}
//this->rayGenProgram["writeAlbedo"]->setInt(writeAlbedo);
// Validate only after all nodes have completed the prepass so all context subcomponents have been initialized
if (!this->contextValidated)
{
try
{
context->validate();
}
catch (optix::Exception& e)
{
throw VisRTX::Exception(Error::UNKNOWN_ERROR, e.getErrorString().c_str());
}
this->contextValidated = true;
}
// Render frame
#ifdef VISRTX_USE_DEBUG_EXCEPTIONS
try
{
#endif
if (lastSample && useAIDenoiser && frameBuffer->frameNumber < this->blendDelay + this->blendDuration)
{
float blend = 0.0f;
if (frameBuffer->frameNumber >= this->blendDelay)
blend = (float)(frameBuffer->frameNumber - this->blendDelay) / (float)this->blendDuration;
frameBuffer->denoiserBlend->setFloat(blend);
frameBuffer->denoiserCommandList->execute();
}
else
{
context->launch(RENDER_ENTRY_POINT, frameBuffer->width, frameBuffer->height);
}
#ifdef VISRTX_USE_DEBUG_EXCEPTIONS
}
catch (optix::Exception& e)
{
throw VisRTX::Exception(Error::UNKNOWN_ERROR, e.getErrorString().c_str());
}
#endif
// Increase frame number
frameBuffer->frameNumber++;
}
}
bool Renderer::Pick(const Vec2f& screenPos, PickResult& result)
{
if (!this->Init())
return false;
optix::Context context = OptiXContext::Get();
// Compute camera ray
VisRTX::Impl::Camera* camera = dynamic_cast<VisRTX::Impl::Camera*>(this->camera);
optix::float3 rayOrigin;
optix::float3 rayDirection;
const Vec2f pixel(2.0f * screenPos.x - 1.0f, 2.0f * (1.0f - screenPos.y) - 1.0f);
const optix::float3 W = optix::normalize(camera->direction);
const optix::float3 U = optix::normalize(optix::cross(camera->direction, camera->up));
const optix::float3 V = optix::normalize(optix::cross(U, W));
if (this->camera->GetType() == CameraType::PERSPECTIVE)
{
VisRTX::Impl::PerspectiveCamera* perspectiveCam = dynamic_cast<VisRTX::Impl::PerspectiveCamera*>(this->camera);
const float vlen = tanf(0.5f * perspectiveCam->fovy * M_PIf / 180.0f);
const float ulen = vlen * perspectiveCam->aspect;
rayOrigin = perspectiveCam->position;
rayDirection = optix::normalize(pixel.x * ulen * U + pixel.y * vlen * V + W);
}
else if (this->camera->GetType() == CameraType::ORTHOGRAPHIC)
{
VisRTX::Impl::OrthographicCamera* orthoCam = dynamic_cast<VisRTX::Impl::OrthographicCamera*>(this->camera);
rayOrigin = orthoCam->position + 0.5f * (pixel.x * orthoCam->height * orthoCam->aspect * U + pixel.y * orthoCam->height * V);
rayDirection = W;
}
this->rayGenPickProgram["rayOrigin"]->setFloat(rayOrigin);
this->rayGenPickProgram["rayDirection"]->setFloat(rayDirection);
context->launch(PICK_ENTRY_POINT, 1);
// Extract result
bool hit = false;
result.geometry = nullptr;
result.geometryHit = false;
result.light = nullptr;
result.lightHit = false;
result.primitiveIndex = 0;
result.position = Vec3f(0.0f, 0.0f, 0.0f);
PickStruct* pick = static_cast<PickStruct*>(this->pickBuffer->map(0, RT_BUFFER_MAP_READ));
if (pick->geometryId != 0)
{
result.geometry = dynamic_cast<VisRTX::Impl::Model*>(this->model)->pickGeometries[pick->geometryId];
result.geometryHit = true;
result.primitiveIndex = pick->primIndex;
hit = true;
}
if (pick->lightId != 0)
{
result.lightHit = true;
result.light = this->pickLights[pick->lightId];
hit = true;
}
if (hit)
{
optix::float3 pos = rayOrigin + pick->t * rayDirection;
result.position = Vec3f(pos.x, pos.y, pos.z);
}
this->pickBuffer->unmap();
return hit;
}
void Renderer::SetCamera(VisRTX::Camera* camera)
{
if (camera != this->camera)
{
if (this->camera)
this->camera->Release();
this->camera = camera;
if (this->camera)
{
this->camera->Retain();
// Mark this camera as dirty to enforce update
dynamic_cast<VisRTX::Impl::Camera*>(this->camera)->dirty = true;
}
}
}
void Renderer::SetModel(VisRTX::Model* model)
{
if (model != this->model)
{
// Remove lights from current model before losing it
if (this->model)
{
dynamic_cast<VisRTX::Impl::Model*>(this->model)->UpdateLightGeometries(nullptr);
this->model->Release();
}
this->model = model;
if (this->model)
{
this->model->Retain();
optix::Context context = OptiXContext::Get();
VisRTX::Impl::Model* m = dynamic_cast<VisRTX::Impl::Model*>(this->model);
this->rayGenProgram["topObject"]->set(m->superGroup);
this->rayGenPickProgram["topObject"]->set(m->superGroup);
}
}
}
void Renderer::AddLight(VisRTX::Light* light)
{
if (!light)
return;
auto it = this->lights.find(light);
if (it == this->lights.end())
{
this->lights.insert(light);
light->Retain();
}
}
void Renderer::RemoveLight(VisRTX::Light* light)
{
if (!light)
return;
auto it = this->lights.find(light);
if (it != this->lights.end())
{
this->lights.erase(it);
light->Release();
}
}
void Renderer::SetToneMapping(bool enabled, float gamma, const Vec3f& colorBalance, float whitePoint, float burnHighlights, float crushBlacks, float saturation, float brightness)
{
if (this->toneMappingFixed && !this->ignoreOverrides)
return;
this->toneMapping = enabled;
this->gamma = gamma;
this->colorBalance = colorBalance;
this->whitePoint = whitePoint;
this->burnHighlights = burnHighlights;
this->crushBlacks = crushBlacks;
this->saturation = saturation;
this->brightness = brightness;
}
void Renderer::SetDenoiser(DenoiserType denoiser)
{
if (this->denoiserFixed && !this->ignoreOverrides)
return;
this->denoiser = denoiser;
// TODO expose in API?
this->blendDelay = 20;
this->blendDuration = 1000;
}
void Renderer::SetSamplesPerPixel(uint32_t spp)
{
this->samplesPerPixel = spp;
}
void Renderer::SetEpsilon(float epsilon)
{
if (this->epsilonFixed && !this->ignoreOverrides)
return;
// Conservative epsilon...
this->epsilon = std::max(1e-3f, epsilon);
}
void Renderer::SetAlphaCutoff(float alphaCutoff)
{
this->alphaCutoff = alphaCutoff;
}
void Renderer::SetNumBounces(uint32_t minBounces, uint32_t maxBounces)
{
if (!this->minBouncesFixed || this->ignoreOverrides)
this->minBounces = minBounces;
if (!this->maxBouncesFixed || this->ignoreOverrides)
this->maxBounces = maxBounces;
}
void Renderer::SetWriteBackground(bool writeBackground)
{
this->writeBackground = writeBackground;
}
void Renderer::SetFireflyClamping(float direct, float indirect)
{
if (!this->clampDirectFixed || this->ignoreOverrides)
this->fireflyClampingDirect = direct;
if (!this->clampIndirectFixed || this->ignoreOverrides)
this->fireflyClampingIndirect = indirect;
}
void Renderer::SetSampleAllLights(bool sampleAllLights)
{
if (!this->sampleAllLightsFixed || this->ignoreOverrides)
this->sampleAllLights = sampleAllLights;
}
}
}
| 39.024204
| 189
| 0.544722
|
demarle
|
410ff5948c03bec8d364c8f5be18d89ba604faf4
| 1,812
|
cpp
|
C++
|
LinkedList/EvenAfterOddLL.cpp
|
tanmayagarwal06/CompetitiveProgramming
|
ce1df2dbe829a0babfb18e65beee8604eb80915c
|
[
"MIT"
] | null | null | null |
LinkedList/EvenAfterOddLL.cpp
|
tanmayagarwal06/CompetitiveProgramming
|
ce1df2dbe829a0babfb18e65beee8604eb80915c
|
[
"MIT"
] | null | null | null |
LinkedList/EvenAfterOddLL.cpp
|
tanmayagarwal06/CompetitiveProgramming
|
ce1df2dbe829a0babfb18e65beee8604eb80915c
|
[
"MIT"
] | 3
|
2020-10-06T02:57:41.000Z
|
2020-10-20T06:54:04.000Z
|
#include <iostream>
class node{
public:
int data;
node * next;
node(int data){
this->data=data;
this->next=NULL;
}
};
using namespace std;
node* takeinput(){
int data;
cin>>data;
node* head=NULL,*tail=NULL;
while(data!=-1){
node *newnode=new node(data);
if(head==NULL) {
head=newnode;
tail=newnode;
}
else{
tail->next=newnode;
tail=newnode;
}
cin>>data;
}
return head;
}
void print(node *head)
{
node*temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
node* arrange_LinkedList(node* head)
{
//write your code here
node *temp = head;
node *head1 = NULL;
node *temp1 = NULL;
node *head2 = NULL;
node *temp2 = NULL;
while(temp != NULL){
node *newnode=new node(temp->data);
if(temp->data % 2 == 0){
if(head1 == NULL){
head1 = newnode;
temp1 = head1;
} else {
temp1->next = newnode;
temp1 = temp1->next;
}
} else {
if(head2 == NULL){
head2 = newnode;
temp2 = head2;
} else {
temp2->next = newnode;
temp2 = temp2->next;
}
}
temp = temp->next;
}
if(head2 == NULL){
return head1;
}
temp2->next = head1;
return head2;
}
int main()
{
node*head=takeinput();
head=arrange_LinkedList(head);
print(head);
return 0;
}
| 19.483871
| 56
| 0.416115
|
tanmayagarwal06
|
411079d8cefad9aea41cca90f49bf5f2e14c4f77
| 7,766
|
cpp
|
C++
|
qcom-caf/display/composer/hwc_debugger.cpp
|
Jleeblanch/android_device_motorola_sm7250-common
|
735d0e7dce41e6fb381b10ece6e7e9616eee045c
|
[
"FTL"
] | 4
|
2020-12-17T13:39:05.000Z
|
2022-02-11T10:24:58.000Z
|
qcom-caf/display/composer/hwc_debugger.cpp
|
Jleeblanch/android_device_motorola_sm7250-common
|
735d0e7dce41e6fb381b10ece6e7e9616eee045c
|
[
"FTL"
] | null | null | null |
qcom-caf/display/composer/hwc_debugger.cpp
|
Jleeblanch/android_device_motorola_sm7250-common
|
735d0e7dce41e6fb381b10ece6e7e9616eee045c
|
[
"FTL"
] | 4
|
2021-01-07T12:31:21.000Z
|
2021-12-27T19:08:12.000Z
|
/*
* Copyright (c) 2014 - 2020, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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 <utils/constants.h>
#include <cutils/properties.h>
#include <display_properties.h>
#include "hwc_debugger.h"
namespace sdm {
HWCDebugHandler HWCDebugHandler::debug_handler_;
HWCDebugHandler::HWCDebugHandler() {
DebugHandler::Set(HWCDebugHandler::Get());
}
void HWCDebugHandler::DebugAll(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_ = 0x7FFFFFFF;
if (verbose_level) {
// Enable verbose scalar logs only when explicitly enabled
debug_handler_.log_mask_[kTagScalar] = 0;
}
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_ = 0x1; // kTagNone should always be printed.
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugResources(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagResources] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagResources] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugStrategy(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagStrategy] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagStrategy] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugCompManager(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagCompManager] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagCompManager] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugDriverConfig(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagDriverConfig] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagDriverConfig] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugRotator(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagRotator] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagRotator] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugScalar(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagScalar] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagScalar] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugQdcm(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagQDCM] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagQDCM] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugClient(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagClient] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagClient] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugDisplay(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagDisplay] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagDisplay] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::DebugQos(bool enable, int verbose_level) {
if (enable) {
debug_handler_.log_mask_[kTagQOSClient] = 1;
debug_handler_.log_mask_[kTagQOSImpl] = 1;
debug_handler_.verbose_level_ = verbose_level;
} else {
debug_handler_.log_mask_[kTagQOSClient] = 0;
debug_handler_.log_mask_[kTagQOSImpl] = 0;
debug_handler_.verbose_level_ = 0;
}
DebugHandler::SetLogMask(debug_handler_.log_mask_);
}
void HWCDebugHandler::Error(const char *fmt, ...) {
va_list list;
va_start(list, fmt);
__android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, fmt, list);
}
void HWCDebugHandler::Warning(const char *fmt, ...) {
va_list list;
va_start(list, fmt);
__android_log_vprint(ANDROID_LOG_WARN, LOG_TAG, fmt, list);
}
void HWCDebugHandler::Info(const char *fmt, ...) {
va_list list;
va_start(list, fmt);
__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, fmt, list);
}
void HWCDebugHandler::Debug(const char *fmt, ...) {
va_list list;
va_start(list, fmt);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, fmt, list);
}
void HWCDebugHandler::Verbose(const char *fmt, ...) {
if (debug_handler_.verbose_level_) {
va_list list;
va_start(list, fmt);
__android_log_vprint(ANDROID_LOG_VERBOSE, LOG_TAG, fmt, list);
}
}
void HWCDebugHandler::BeginTrace(const char *class_name, const char *function_name,
const char *custom_string) {
if (atrace_is_tag_enabled(ATRACE_TAG)) {
char name[PATH_MAX] = {0};
snprintf(name, sizeof(name), "%s::%s::%s", class_name, function_name, custom_string);
atrace_begin(ATRACE_TAG, name);
}
}
void HWCDebugHandler::EndTrace() {
atrace_end(ATRACE_TAG);
}
int HWCDebugHandler::GetIdleTimeoutMs() {
int value = IDLE_TIMEOUT_DEFAULT_MS;
debug_handler_.GetProperty(IDLE_TIME_PROP, &value);
return value;
}
int HWCDebugHandler::GetProperty(const char *property_name, int *value) {
char property[PROPERTY_VALUE_MAX];
if (property_get(property_name, property, NULL) > 0) {
*value = atoi(property);
return kErrorNone;
}
return kErrorNotSupported;
}
int HWCDebugHandler::GetProperty(const char *property_name, char *value) {
if (property_get(property_name, value, NULL) > 0) {
return kErrorNone;
}
return kErrorNotSupported;
}
} // namespace sdm
| 30.454902
| 89
| 0.738347
|
Jleeblanch
|
4110e68c6e1829114c8ac5891e51be787988da9b
| 847
|
cpp
|
C++
|
AtCoder/joisc2007/score/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
AtCoder/joisc2007/score/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | 1
|
2021-10-19T08:47:23.000Z
|
2022-03-07T05:23:56.000Z
|
AtCoder/joisc2007/score/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n; cin >> n;
vector<int> score(n, 0);
for (int i = 0; i < n; i++) cin >> score[i];
vector<int> score_sort = score;
sort(score_sort.begin(), score_sort.end());
reverse(score_sort.begin(), score_sort.end());
vector<int> score_sorted; score_sort.push_back(-100);
for (int i = 0; i < n; i++) if (score_sort[i] != score_sort[i + 1]) score_sorted.push_back(score_sort[i]);
int pos = 1, next = 1;
vector<int> ans(n, 0);
for (int i = 0; i < score_sorted.size(); i++) {
for (int j = 0; j < n; j++) {
if (score_sorted[i] == score[j]) {
ans[j] = pos, next++;
}
}
pos = next;
}
for (int i = 0; i < n; i++) cout << ans[i] << endl;
}
| 31.37037
| 110
| 0.532468
|
H-Tatsuhiro
|
411adc9b9bbe8bea9de20991ac6a6056d0d91bda
| 16,678
|
cpp
|
C++
|
game.cpp
|
NX1125/cg-tf
|
84a2e05908066efcbe797d35c6498f69a51ad917
|
[
"MIT"
] | null | null | null |
game.cpp
|
NX1125/cg-tf
|
84a2e05908066efcbe797d35c6498f69a51ad917
|
[
"MIT"
] | null | null | null |
game.cpp
|
NX1125/cg-tf
|
84a2e05908066efcbe797d35c6498f69a51ad917
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include "game.h"
#include "player.h"
#include "cube.h"
#include "textrendering.h"
#include "bomb.h"
#include "bullet.h"
#define FIXED_THIRD_PERSON_CAMERA
Game::Game(app_settings* settings) {
glClearColor(0, 0, 0, 0);
wf_object_loader_t loader;
// as stated in the spec, the height of the arena is 8 times the player's
// diameter. We have the radius, that's why 2 * 8
arena = new arena_t(settings->player->radius * 2 * 8, settings->arena->radius, loader);
simple_svg_line* airstrip = settings->airstrip;
float t = settings->player->radius * 0.5f;
point3f start(airstrip->x1, airstrip->y1, t);
point3f end(airstrip->x2, airstrip->y2, t);
takeoff_t* takeoff = new takeoff_t(start, end, arena->getHeight() / 5, 4000);
player = new player_t(takeoff, settings->player->radius);
addResetListener(player);
arena->setAirstrip(new airstrip_t(start, end, player->getRadius() * 2));
normalDistance = player->getRadius() * 8;
follower = new third_person_follower_t(/*point3f(0,0,0)*/
player->getPosition(), normalDistance);
follower->setAngle(M_PI, 20 * M_PI / 180.0);
loadModels(loader);
watch = new stopwatch_t();
player->setVelocityFactor(settings->vel);
player->setBulletVelocityFactor(settings->bulletVel);
player->setBombListener(this);
manager = new projectile_manager_t();
createBases(settings->groundEnemies);
createEnemies(settings->flyingEnemies, arena->getHeight() / 2, settings->eVel * takeoff->getFinalVelocity());
player->setManager(manager);
// A time of 2 seconds for the bomb to fall onto the ground.
// The time considers that the player is at the roof
// s(t) = at^2 / 2
// h = at^2 / 2
// 2h = at^2
// 2h / t^2 = a
const float timeToBombHitGround = 2;
float a = -2 * arena->getHeight() / 5 / (timeToBombHitGround * timeToBombHitGround);
printf("The bomb will fall with an acceleration of %f\n", a);
bomb_t::setGravityAcceleration(a);
timeToEnemyFire = (time_t) (1000.0f / settings->eBulletF);
miniMapAux = new circle_blueprint_t(16);
// point3f p = player->getPosition();
// player->setPosition(point3f(30, 30, 30));
// TODO Add reset listeners
glEnable(GL_NORMALIZE);
}
void Game::createBases(vector<simple_svg_circle*>& bases) {
for (simple_svg_circle* enemy : bases) {
enemy_base_t* b = new enemy_base_t(point3f(enemy->cx, enemy->cy, enemy->radius), enemy->radius);
manager->addObstacles(b, false);
b->setDeathListener(this);
this->bases.push_back(b);
}
}
void Game::createEnemies(vector<simple_svg_circle*>& enemies, float height, float velocity) {
for (simple_svg_circle* enemy : enemies) {
point3f p(enemy->cx, enemy->cy, height);
flying_enemy_t* e = new flying_enemy_t(p, enemy->radius);
manager->addObstacles(e, true);
e->setInitialVelocity(velocity);
this->enemies.push_back(e);
}
}
void Game::loadModels(wf_object_loader_t& loader) {
player_t::sInit(loader);
bullet_t::init(loader);
bomb_t::init(loader);
enemy_base_t::init(loader);
flying_enemy_t::init(loader);
cannon_t::init(loader);
propeller_t::init(loader);
loadCube(loader);
}
void Game::display() {
// TODO Put light and textures to meshes
glEnable(GL_CULL_FACE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, height - 500, 500, 500);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
switch (cameraView) {
case Camera::TAKEOFF_FUNCTION_VIEW:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, 1, 0, 1, 1, -1);
{
int n = 20;
glColor3f(1, 1, 0);
glBegin(GL_LINE_STRIP);
{
for (int i = 0; i <= n; i++) {
float x = i / (float) n;
float y = takeoff_t::getTakeoffFactor(x);
glVertex2d(x, y);
}
}
glEnd();
glColor3f(0, 1, 0);
glBegin(GL_LINE_STRIP);
{
for (int i = 0; i <= n; i++) {
float x = i / (float) n;
float y = takeoff_t::getTakeoffTangent(x);
glVertex2d(x, y);
}
}
glEnd();
glColor3f(1, 0, 0);
glBegin(GL_LINE_STRIP);
{
for (int i = 0; i <= n; i++) {
float x = i / (float) n;
float y = takeoff_t::getTakeoffTangent(x);
y = atanf(y);
glVertex2d(x, y);
}
}
glEnd();
}
glutSwapBuffers();
return;
case Camera::UP_VIEW:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(-arena->getRadius(), arena->getRadius(), -arena->getRadius(), arena->getRadius(), -arena->getHeight() * 2, arena->getHeight() * 2);
break;
case Camera::SIDE_VIEW:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(-arena->getRadius(), arena->getRadius(), -arena->getRadius(), arena->getRadius(), -arena->getHeight() * 2, arena->getHeight() * 2);
glRotated(-90, 1, 0, 0);
break;
case Camera::THIRD_PERSON_CAMERA:
gluPerspective(/* field of view in degree */ 40.0,
/* aspect ratio */ 1.0,
/* Z near */ 1.0, /* Z far */ 3 * arena->getRadius());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
{
point3f target = player->getPosition();
// point3f target(0, 0, 0);;
if (followerOrbitEnabled) {
target.z += player->getRadius() / 2;
follower->lookAt(target, player->getHorizontal(),
player->getVertical());
} else {
vector3f v = player->getDirection(0.2f * M_PI / 2) * follower->getNormalDistance();
gluLookAt(target.x - v.x, target.y - v.y, target.z - v.z,
target.x, target.y, target.z, 0, 0, 1);
}
}
break;
case Camera::CANNON_VIEW:
gluPerspective(/* field of view in degree */ 40.0,
/* aspect ratio */ 1.0,
/* Z near */ 1.0, /* Z far */ 3 * arena->getRadius());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
player->cannonView();
break;
case Camera::COCKPIT:
gluPerspective(/* field of view in degree */ 40.0,
/* aspect ratio */ 1.0,
/* Z near */ 1.0, /* Z far */ 3 * arena->getRadius());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
player->cockpitView();
break;
}
// glEnable(GL_LIGHTING);
// glShadeModel(GL_SMOOTH);
// point3f p = player->getPosition();
// GLfloat playerPosition[] = {0, 0, 1, 1};
// GLfloat white[] = {1, 1, 1, 1};
//
// glColor3f(0, 0, 0);
// glLightfv(GL_LIGHT0, GL_POSITION, playerPosition);
// glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
// glLightfv(GL_LIGHT0, GL_SPECULAR, white);
// glEnable(GL_LIGHT0);
arena->getAirstrip()->putLight();
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
drawWorld();
if (currentBomb != NULL) {
glViewport(0, 0, 200, 200);
gluPerspective(/* field of view in degree */ 40.0,
/* aspect ratio */ 1.0,
/* Z near */ 1.0, /* Z far */ 2 * arena->getRadius());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
point3f p = currentBomb->getPosition();
vector3f& v = currentBomb->getVelocity();
// Look at its shadow. Shadow of the Bomb
gluLookAt(p.x, p.y, p.z,
p.x, p.y, 0,
v.x, v.y, v.z);
drawWorld();
}
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
drawHUD();
drawMap();
glEnable(GL_DEPTH_TEST);
glutSwapBuffers();
}
void Game::drawWorld() {
// glPushMatrix();
// {
// glScalef(50, 50, 50);
// glRotatef(90, 1, 0, 0);
// drawAxis(1);
// bullet_t::draw0();
// }
// glPopMatrix();
GLfloat blue[] = {0, 0, 0.5f, 1.0f};
glMaterialfv(GL_FRONT, GL_AMBIENT, blue);
player->draw(true, true, true, true);
arena->draw();
for (enemy_base_t* base : bases) {
base->transformAndDraw();
}
for (flying_enemy_t* enemy : enemies) {
enemy->transformAndDraw();
}
manager->draw();
}
void Game::drawHUD() {
// Make the frame fit into NDC
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 500, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, height - 500, 500, 500);
glPushMatrix();
{
int w, h;
int w2, h2;
const float padding = 10.0f;
// text with white color:
glColor3f(1, 1, 1);
string missing("Faltam: ");
missing += std::to_string(bases.size() - score);
measureText(scoreText.c_str(), &w, &h);
measureText(missing.c_str(), &w2, &h2);
glTranslatef(500 - padding - max(w2, w), 0, 0);
glTranslatef(0, padding + h, 0);
drawText(scoreText.c_str());
glTranslatef(0, padding + h, 0);
drawText(missing.c_str());
}
glPopMatrix();
if (player->getBehaviour() == Behaviour::GAME_OVER) {
const char* text;
if (player->isDead()) {
// He lost!
// TODO Put a sercastic message for the player instead
text = "Perdeu... :(";
} else {
// He won!
text = "Ganhou! :D";
}
int w, h;
measureText(text, &w, &h);
// center it at screen:
glTranslatef((500 - w) / 2, (500 - h) / 2, 0);
// text with white color:
glColor3f(1, 1, 1);
drawText(text);
}
}
void Game::drawMap() {
// The minimap need to fit in 1/4 of the frame at the bottom-right position.
int w = 500 / 4;
int h = 500 / 4;
const float padding = 10;
glViewport(500 - w - padding, height - 500 + padding, w, h);
float r = arena->getRadius();
// Make the frame fit into NDC
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(r, -r, r, -r);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
arena->drawMapElement(miniMapAux);
// draw all of the ground enemies in orange (#FFA500)
glColor3f(0xFF / 255.0, 0xA5 / 255.0, 0x00 / 255.0);
for (enemy_base_t* e : bases) {
e->drawMapElement(miniMapAux);
}
// Flying enemies have a red color
glColor3f(1, 0, 0);
for (flying_enemy_t* e : enemies) {
e->drawMapElement(miniMapAux);
}
player->drawMapElement(miniMapAux);
}
void Game::mouseDragged(int x, int y) {
if (followerOrbitEnabled) {
follower->mouseDragged(x, y);
glutPostRedisplay();
}
}
void Game::mouseMoved(int x, int y) {
if (player->getBehaviour() == Behaviour::CONTROLLING) {
float k = y / (GLfloat) 500;
if (k > 1) {
k = 1;
}
player->setCannonAxis(x / (GLfloat) 500, k);
}
}
void Game::mouseButtonEvent(int button, int state, int x, int y) {
switch (state) {
case GLUT_DOWN:
mousePressed(button, x, y);
break;
case GLUT_UP:
mouseReleased(button, x, y);
break;
}
}
void Game::mousePressed(int button, int x, int y) {
if (button == GLUT_RIGHT_BUTTON &&
player->getBehaviour() == Behaviour::ON_GROUND) {
follower->setMousePressingPosition(x, y);
followerOrbitEnabled = true;
} else {
if (button == GLUT_RIGHT_BUTTON && followerOrbitEnabled) {
return;
}
player->mousePress(button);
}
}
void Game::mouseReleased(int button, int x, int y) {
followerOrbitEnabled = false;
}
void Game::reshape(int width, int height) {
this->width = width;
this->height = height;
printf("Reshape: (%d, %d)\n", width, height);
}
void Game::idle() {
watch->mark();
int time = watch->getMarkedElaspedTimeMillis();
if (time <= 10) {
return;
}
// printf("Time: %d ms\n", time);
arena->getAirstrip()->update(time);
player->update(time);
player->clipZ(arena->getHeight());
manager->update(time);
manager->removeOutsideOfArena(arena->getRadius(), arena->getHeight());
if (currentBomb != NULL && currentBomb->isDead()) {
currentBomb = NULL;
glutReshapeWindow(500, 700);
}
manager->collectGarbage();
for (flying_enemy_t* enemy : enemies) {
enemy->update(time);
enemy->clipZ(arena->getHeight());
}
timeSinceLastEnemyFire += time;
if (timeSinceLastEnemyFire > timeToEnemyFire) {
timeSinceLastEnemyFire = 0;
// All enemies are firing now!
for (flying_enemy_t* e : enemies) {
if (e->isAlive()) {
point3f p = e->getPosition() + e->getCannonExit();
vector3f v = e->getVelocity();
bullet_t* b = new bullet_t(p, v, true);
b->setRadius(e->getRadius() / 16);
manager->addProjectile(b);
}
}
}
if (player->canDie()) {
for (flying_enemy_t* enemy : enemies) {
if (!enemy->isDead() && enemy->overlaps(player)) {
printf("The player just hit an enemy while flying\n");
enemy->kill();
player->kill();
break;
}
}
}
for (flying_enemy_t* enemy : enemies) {
enemy->teleport(arena->getRadius());
}
if (player->canTeleport()) {
point3f p = player->getPosition();
if (player->teleport(arena->getRadius())) {
// follower->setCamera(follower->getCamera() + (player->getPosition() - p));
}
}
sAccumulatedTime += time;
if (sAccumulatedTime * 30 > 1000) {
glutPostRedisplay();
sAccumulatedTime = 0;
}
watch->setMarkAsOffset();
}
void Game::keyPressed(unsigned char key, int x, int y) {
switch (key) {
case ' ':
followerOrbitEnabled = true;
break;
case 'r':
reset();
return;
case '1':
printf("Changing to cockpit view\n");
cameraView = Camera::COCKPIT;
break;
case '2':
printf("Changing to cannon view\n");
cameraView = Camera::CANNON_VIEW;
break;
case '3':
printf("Changing to third person view\n");
cameraView = Camera::THIRD_PERSON_CAMERA;
break;
case '4':
printf("Changing to up view\n");
cameraView = Camera::UP_VIEW;
break;
case '5':
printf("Changing to takeoff function view\n");
cameraView = Camera::TAKEOFF_FUNCTION_VIEW;
break;
case '6':
printf("Changing to side view\n");
cameraView = Camera::SIDE_VIEW;
break;
default:
player->keyPress(key);
return;
}
glutPostRedisplay();
}
void Game::keyReleased(unsigned char key, int x, int y) {
player->keyRelease(key);
followerOrbitEnabled = false;
}
void Game::reset() {
for (flying_enemy_t* f : enemies) {
f->reset();
}
for (enemy_base_t* base : bases) {
base->reset();
}
manager->reset();
score = 0;
scoreText = "Score: 0";
this->cameraView = Camera::THIRD_PERSON_CAMERA;
follower->reset();
follower->setAngle(M_PI, 20 * M_PI / 180.0);
printf("Resetting game\n");
printf("Resetting listeners");
for (reset_listener_t* l : sResetListeners) {
l->reset();
}
}
void Game::addResetListener(reset_listener_t * l) {
sResetListeners.push_back(l);
}
void Game::onBaseDeath() {
score++;
scoreText = string("Score: ");
scoreText += std::to_string(score);
if (score >= bases.size()) {
player->won();
}
}
void Game::onBombThrow(bomb_t * b) {
currentBomb = b;
glutReshapeWindow(500, 700);
}
| 26.727564
| 151
| 0.54353
|
NX1125
|
411b62f216e68ade1a22793804d2cfb2eaef675b
| 30,349
|
cc
|
C++
|
support/strops.cc
|
gorlak/P4
|
fa25916ef69fa77887bb493800b6ce12be3f469e
|
[
"BSD-2-Clause"
] | null | null | null |
support/strops.cc
|
gorlak/P4
|
fa25916ef69fa77887bb493800b6ce12be3f469e
|
[
"BSD-2-Clause"
] | null | null | null |
support/strops.cc
|
gorlak/P4
|
fa25916ef69fa77887bb493800b6ce12be3f469e
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright 1995, 1996 Perforce Software. All rights reserved.
*
* This file is part of Perforce - the FAST SCM System.
*/
/*
* strings.cc - support for StrBuf, StrPtr
*/
# define CHARHASH(h, c) ( 293 * (h) + (c) );
# define NEED_QUOTE
# include <stdhdrs.h>
# include <charman.h>
# include <charset.h>
# include <debug.h>
# include <validate.h>
# include <error.h>
# include <regmatch.h>
# include "strbuf.h"
# include "strdict.h"
# include "strops.h"
/*
* StrOps::Words() - break a string apart at white space
*
* Quotes are handles as thus:
*
* "foo bar" -> (foo) (bar)
* foo" "bar -> (foo) (bar)
* "foo""bar" -> (foo"bar)
* foo""bar -> (foo"bar)
*
* Note that the only user of Words() that requires quote handling
* is RunCommand::RunChild() on UNIX, which is used for P4PORT=rsh:
*/
int
StrOps::Words( StrBuf &tmp, const char *buf, char *vec[], int maxVec )
{
// Ensure tmp clear and big enough to avoid realloc
tmp.Clear();
tmp.Alloc( strlen( buf ) + 1 );
tmp.Clear();
int count = 0;
while( count < maxVec )
{
// Skip blanks
while( isAspace( buf ) ) buf++;
if( !*buf ) break;
// First letter of new word
vec[ count++ ] = tmp.End();
// Eat word
int quote = 0;
for( ; *buf; ++buf )
{
if( buf[0] == '"' && buf[1] == '"' )
tmp.Extend( buf[0] ), ++buf;
else if( buf[0] == '"' )
quote = !quote;
else if( quote || !isAspace( buf ) )
tmp.Extend( buf[0] );
else break;
}
tmp.Extend( '\0' );
}
return count;
}
int
StrOps::Words( StrBuf &tmp, const char *buf, char *vec[], int maxVec, char s )
{
// Ensure tmp clear and big enough to avoid realloc
tmp.Clear();
tmp.Alloc( strlen( buf ) + 1 );
tmp.Clear();
int count = 0;
while( count < maxVec )
{
// Skip blanks
while( *buf == s ) buf++;
if( !*buf ) break;
// First letter of new word
vec[ count++ ] = tmp.End();
// Eat word
int quote = 0;
for( ; *buf; ++buf )
{
if( buf[0] == '"' && buf[1] == '"' )
tmp.Extend( buf[0] ), ++buf;
else if( buf[0] == '"' )
quote = !quote;
else if( quote || *buf != s )
tmp.Extend( buf[0] );
else break;
}
tmp.Extend( '\0' );
}
return count;
}
int
StrOps::WordsQ( StrBuf &tmp, StrRef cmd, char *words[], int maxVec, Error *e )
{
RegMatch m;
// a b -> (a) (b)
// 'a b' | "a b" -> (a b)
// 'a "b c" d' -> (a) (b c) (d)
// unescaped regex: "([^"]*)"|'([^']*)'|([^"' ]+)
m.compile( "\"([^\"]*)\"|'([^']*)'|([^\"' ]+)", e );
if( e->Test() )
return 0;
tmp.Clear();
tmp.Alloc( cmd.Length() + 1 );
tmp.Clear();
int count = 0;
char *p = cmd.Text();
words[ count ] = tmp.Text();
while( count < maxVec && p < cmd.Text() + cmd.Length() )
{
if( m.matches( p, e ) )
{
if( e->Test() )
return 0;
if( isBlank( *p ) )
{
p += 1;
continue;
}
if( *p == '\'' || *p == '"' )
tmp.Extend( p + 1, m.len() - 2 );
else
tmp.Extend( p, m.len() );
p += m.end() + 1;
tmp.Extend( '\0' );
words[ count + 1 ] = tmp.End();
count++;
}
else
break;
}
return count;
}
/*
* StrPtr::Lines() - break a string apart at line endings.
* Supports '\r', '\n', and '\r\n' termination.
*/
int
StrOps::Lines( StrBuf &o, char *vec[], int maxVec )
{
int count = 0;
int lastwas_cr = 0;
char *buf = o.Text();
while ( count < maxVec )
{
if ( *buf )
vec[ count++ ] = buf;
else
break;
while ( *buf )
{
if ( *buf == '\r' )
lastwas_cr =1;
else if ( *buf == '\n' && lastwas_cr )
{
*(buf-1) = '\0';
*buf = '\0';
buf++;
lastwas_cr = 0;
break;
}
else if ( *buf == '\n' )
{
*buf = '\0';
buf++;
break;
}
else if ( lastwas_cr )
{
// '\r' line termination only
*(buf-1) = '\0';
lastwas_cr = 0;
break;
}
buf++;
}
if ( lastwas_cr )
{
// Final \r of a \r line terminated buffer
*(buf-1) = '\0';
}
}
return count;
}
/*
* StrPtr::Dump() - print out a string for debugging purposes
*/
void
StrOps::Dump( const StrPtr &o )
{
unsigned char *s = o.UText();
unsigned char *e = o.UEnd();
for( ; s < e; s++ )
{
if( isprint( *s ) )
p4debug.printf( "%c", *s );
else
p4debug.printf( "<%02x>", *s );
}
p4debug.printf( "\n" );
}
/*
* StrPtr::Lower() - lowercase each character (in place) in a string
*/
void
StrOps::Lower( StrBuf &o )
{
char *p = o.Text();
int l = o.Length();
for( ; l--; p++ )
*p = tolowerq( *p );
}
/*
* StrPtr::Upper() - uppercase each character (in place) in a string
*/
void
StrOps::Upper( StrBuf &o )
{
char *p = o.Text();
int l = o.Length();
for( ; l--; p++ )
*p = toupperq( *p );
}
/*
* StrPtr::Caps() - uppercase first character (in place) in a string
*/
void
StrOps::Caps( StrBuf &o )
{
char *p = o.Text();
if( o.Length() && !isAhighchar( p ) && islower( *p ) )
*p = toAupper( p );
}
/*
* StrBuf::Ident() - copy in a string, indenting a tabstop
*/
void
StrOps::Indent( StrBuf &o, const StrPtr &buf )
{
const char *p = buf.Text();
const char *t;
while( *p )
{
o.Append( "\t", 1 );
if( t = strchr( p, '\n' ) )
{
o.Append( p, t - p + 1 );
p = t + 1;
}
else
{
// just in case - all lines end with \n
o.Append( p );
o.Append( "\n", 1 );
p += strlen( p );
}
}
}
/*
* StrBuf::Sub() - replace one character with another
*/
void
StrOps::Sub( StrPtr &string, char target, char replacement )
{
for ( char * temp = string.Text();
*temp != '\0';
temp++ )
{
if ( *temp == target )
*temp = replacement;
}
}
/*
* StrOps::Replace() - Replace substrings. Replaces all occurrences of
* string s in string i with string r and writes the results to o.
*/
void
StrOps::Replace( StrBuf &o, const StrPtr &i, const StrPtr &s, const StrPtr &r )
{
char *start, *end;
o.Clear();
start = i.Text();
while ( end = strstr( start, s.Text() ) )
{
o.Append( start, end - start );
o.Append( r.Text() );
start += end - start + s.Length();
}
if ( *start )
o.Append( start );
}
/*
* StrOps::ReplaceWild() - Replace '*' with '...' but sometimes
* %%1... if previous character is '.'
*/
void
StrOps::ReplaceWild( StrBuf &o, const StrPtr &i )
{
const char *n = "123456789";
char *start, *end;
int j = 0;
o.Clear();
start = i.Text();
while ( end = strstr( start, "*" ) )
{
o.Append( start, end - start );
if( end > start && *(end - 1) == '.' )
{
o.Append( "%%" );
o.Append( n + j, 1 );
if( ++j >= 9)
j = 0;
}
o.Append( "..." );
start += end - start + 1;
}
if ( *start )
o.Append( start );
}
/*
* StrBuf::Expand() - expand a string doing %var%, %x substitutions
*/
void
StrOps::Expand( StrBuf &o, const StrPtr &buf, StrDict &dict, StrDict *u )
{
StrPtr *val;
const char *p = buf.Text();
const char *q;
while( q = strchr( p, '%' ) )
{
// look for closing %
o.Append( p, q++ - p );
if( !( p = strchr( q, '%' ) ) )
{
// handle %junk
p = q;
break;
}
else if( p == q )
{
// handle %%
o.Extend( '%' );
}
else
{
// handle %var%
StrBuf var;
var.Extend( q, p - q );
var.Terminate();
if( val = dict.GetVar( var ) )
o.Append( val );
else
{
o << "%" << var << "%";
if( u )
u->SetVar( var.Text() );
}
}
++p;
}
o.Append( p );
}
/*
* StrOps::Expand2() - expand a string doing [%var%|opt] substitutions
*/
void
StrOps::Expand2( StrBuf &o, const StrPtr &buf, StrDict &dict )
{
StrPtr *val;
const char *p = buf.Text();
const char *q, *r, *s, *t;
// Handle sequences of
// text %var% ...
// text [ stuff1 %var% stuff2 ] ...
while( q = strchr( p, '%' ) )
{
if( q[1] == '\'' ) // %' stuff '%: include stuff, uninspected...
{
for( s = q + 2; *s; s++ )
if( s[0] == '\'' && s[1] == '%' )
break;
if( ! *s )
break; // %'junk
o.UAppend( p, q - p );
q += 2;
o.UAppend( q, s - q );
p = s + 2;
continue;
}
// variables: (p)text (r)[ stuff (q)%var(s)% stuff2 (t)]
if( !( s = strchr( q + 1, '%' ) ) )
{
// %junk
break;
}
else if( s == q + 1 )
{
// %% - [ %% ] not handled!
o.Append( p, s - p );
p = s + 1;
continue;
}
// Pick out var name and look up value
StrVarName var( q + 1, s - q - 1 );
val = dict.GetVar( var );
// Now handle %var% or [ %var% | alt ]
if( !( r = (char*)memchr( p, '[', q - p ) ) )
{
// %var%
o.Append( p, q - p );
if( val ) o.Append( val );
p = s + 1;
}
else if( !( t = strchr( s + 1, ']' ) ) )
{
// [ junk
break;
}
else
{
// [ stuff1 %var% stuff2 | alternate ]
o.Append( p, r - p );
// [ | alternate ]
const char *v = (char *)memchr( s, '|', t - s );
if( !v ) v = t;
if( val && val->Length() )
{
// stuff1, val, stuff2
o.Append( r + 1, q - r - 1 );
o.Append( val );
o.Append( s + 1, v - s - 1 );
}
else if( v < t )
{
// alternate
o.Append( v + 1, t - v - 1 );
}
p = t + 1;
}
}
o.Append( p );
}
/*
* StrOps::RmUniquote() - Remove %'text'% quote from a string
*/
void
StrOps::RmUniquote( StrBuf &o, const StrPtr &buf )
{
const char *p = buf.Text();
const char *q = p;
const char *r;
while( ( q = strchr( q, '%' ) ) )
{
r = strchr( ++q, '%' );
if( !r )
break;
if( q == r )
{
q++;
continue;
}
if( *q == '\'' )
{
o.UAppend( p, q++ - p - 1 );
o.UAppend( q, r - q - 1 );
q = p = r + 1;
}
else
q = r + 1;
}
o.UAppend( p );
}
/*
* StrBuf::OtoX() - turn an octet stream into hex
*/
void
StrOps::OtoX( const StrPtr &octet, StrBuf &hex )
{
OtoX( (const unsigned char *)octet.Text(), octet.Length(), hex );
}
void
StrOps::OtoX( const unsigned char *octet, p4size_t octetLen, StrBuf &hex )
{
char *b = hex.Alloc( 2 * octetLen );
for( int i = 0; i < octetLen; i++ )
{
*b++ = OtoX( ( octet[i] >> 4 ) & 0x0f );
*b++ = OtoX( ( octet[i] >> 0 ) & 0x0f );
}
hex.Terminate();
}
char
StrOps::OtoXlower( unsigned char o )
{
return o >= 10 ? o - 10 + 'a' : o + '0';
}
void
StrOps::OtoXlower( const StrPtr &octet, StrBuf &hex )
{
OtoXlower( (const unsigned char *)octet.Text(), octet.Length(), hex );
}
void
StrOps::OtoXlower( const unsigned char *octet, p4size_t octetLen, StrBuf &hex )
{
char *b = hex.Alloc( 2 * octetLen );
for( int i = 0; i < octetLen; i++ )
{
*b++ = OtoXlower( ( octet[i] >> 4 ) & 0x0f );
*b++ = OtoXlower( ( octet[i] >> 0 ) & 0x0f );
}
hex.Terminate();
}
/*
* StrOps::XtoO() - turn hex into an octet stream
*
* No error checking.
*/
void
StrOps::XtoO( const StrPtr &hex, StrBuf &octet )
{
int len = hex.Length() / 2;
XtoO( hex.Text(), (unsigned char *)octet.Alloc( len ), len );
octet.Terminate();
}
void
StrOps::XtoO( char *hex, unsigned char *octet, int octetLen )
{
for( ; octetLen--; hex += 2 )
{
*octet++
= ( XtoO( hex[0] ) << 4 )
| ( XtoO( hex[1] ) << 0 );
}
}
static const char valid[] = "0123456789abcdefABCDEF";
static int
IsX( char p )
{
for( int i = 0; i < sizeof valid; i++ )
if( valid[i] == p )
return 1;
return 0;
}
int
StrOps::IsDigest( const StrPtr &hex )
{
if( hex.Length() != 32 )
return 0;
for( int i = 0; i < 32; i++ )
if( !IsX( hex.Text()[i] ) )
return 0;
return 1;
}
int
StrOps::IsSha1( const StrPtr &hex )
{
if( hex.Length() < 6 || hex.Length() > 40 )
return 0;
for( int i = 0; i < hex.Length(); i++ )
if( !IsX( hex.Text()[i] ) )
return 0;
return 1;
}
static const char base64map[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int
StrOps::Base64Len( p4size_t len )
{
int v = ( ( len + 2 ) / 3 ) * 4;
switch( len % 3 )
{
case 1:
--v;
case 2:
--v;
}
return v;
}
void
StrOps::OtoBase64( const unsigned char *octet, p4size_t len, StrBuf &base )
{
char *p = base.Alloc( Base64Len( len ) );
while( len >= 3 )
{
unsigned int v = *octet++;
v <<= 8;
v |= *octet++;
v <<= 8;
v |= *octet++;
*p++ = base64map[ v >> 18 ];
v &= 0x3ffff;
*p++ = base64map[ v >> 12 ];
v &= 0xfff;
*p++ = base64map[ v >> 6 ];
*p++ = base64map[ v & 0x3f ];
len -= 3;
}
if( len == 2 )
{
unsigned int v = *octet++;
*p++ = base64map[ v >> 2 ];
v &= 3;
v <<= 8;
v |= *octet;
*p++ = base64map[ v >> 4 ];
*p = base64map[ ( v & 0xf ) << 2 ];
}
else if( len == 1 )
{
unsigned char v = *octet;
*p++ = base64map[ v >> 2 ];
*p = base64map[ ( v & 3 ) << 4 ];
}
base.Terminate();
}
inline static int BtoO( char b )
{
const char *p = strchr( base64map, b );
if( p )
return p - base64map;
return -1;
}
void
StrOps::Base64toO( const char *base, unsigned char *octet, int octLen )
{
while( octLen >= 3 )
{
// full block loop
unsigned int v;
v = BtoO( *base++ ) << 18;
v |= BtoO( *base++ ) << 12;
v |= BtoO( *base++ ) << 6;
v |= BtoO( *base++ );
*octet++ = v >> 16;
*octet++ = ( v >> 8 ) & 0xff;
*octet++ = v & 0xff;
octLen -= 3;
}
if( octLen == 2 )
{
unsigned int v;
v = BtoO( *base++ ) << 10;
v |= BtoO( *base++ ) << 4;
v |= BtoO( *base ) >> 2;
*octet++ = v >> 8;
*octet = v & 0xff;
}
else if( octLen == 1 )
{
unsigned char v;
v = BtoO( *base++ ) << 2;
v |= BtoO( *base ) >> 4;
*octet = v;
}
}
/*
* StrOps::WildToStr() - turn wildcards into %x escaped string
*
* No error checking.
*/
void
StrOps::WildToStr( const StrPtr &i, StrBuf &o )
{
// format special characters '@#*%'
WildToStr( i, o, "@#%*" );
}
void
StrOps::WildToStr( const StrPtr &i, StrBuf &o, const char *t )
{
o.Clear();
char *p = i.Text();
const char *f;
char *s;
while( *p )
{
s = p;
while( *p )
{
f = t;
while( *f && *f != *p )
++f;
if( *f )
break;
++p;
}
o.Append( s, p - s );
if( *p )
{
char buf[3];
buf[0] = '%';
buf[1] = OtoX( ( *p >> 4 ) & 0x0f );
buf[2] = OtoX( ( *p++ >> 0 ) & 0x0f );
o.Append( buf, 3 );
}
}
}
void
StrOps::MaskNonPrintable( const StrPtr &i, StrBuf &o )
{
o.Clear();
o.Alloc( i.Length() + 1 );
o.Clear();
unsigned char *s = i.UText();
unsigned char *e = i.UEnd();
for( ; s < e; s++ )
{
if( isAprint( s ) )
o.Extend( *s );
else
o.Extend( '_' );
}
o.Terminate();
}
/*
* StrOps::StrToWild() - turn %x escaped string into wildcards.
*
* No error checking.
*/
void
StrOps::StrToWild( const StrPtr &i, StrBuf &o )
{
// expand %x character back to '@#*%'
StrToWild( i, o, "@#%*" );
}
void
StrOps::StrToWild( const StrPtr &i, StrBuf &o, const char *t )
{
o.Clear();
char *p = i.Text();
char *s;
while( *p )
{
s = p;
while( *p )
{
if( p[0] == '%' && p[1] == '%' )
p += 2;
else if( p[0] != '%' )
p++;
else
break;
}
o.Append( s, p - s );
if( *p && ( p + 2 < i.End() ) )
{
char b[2];
b[0] = ( XtoO( p[1] ) << 4 ) | ( XtoO( p[2] ) << 0 );
// Only translate the wildcards in *t
if( strchr( t, b[0] ) )
o.Append( b, 1 );
else
o.Append( p, 3 );
if( *(p+2) == '\0')
break;
p += 3;
}
else if( *p )
{
o.Append( p++, 1 );
}
else
{
break;
}
}
}
/*
* StrOps::WildCompat() - turn %%d into %d for 'p4 where' compatability.
*
* No error checking.
*/
void
StrOps::WildCompat( const StrPtr &i, StrBuf &o )
{
// turn %%d into %d
o.Clear();
char *p = i.Text();
char *s;
while( *p )
{
s = p;
while( *p )
{
if( p[0] == '%' && p[1] == '%' && p[2] >= '0' && p[2] <= '9' )
break;
++p;
}
o.Append( s, p - s );
if( *p )
{
o.Append( ++p, 2 );
p += 2;
}
}
}
/*
* StrBuf::PackInt() - marshalling function
* StrBuf::PackChar() - marshalling function
* StrBuf::PackOctet() - marshalling function
* StrBuf::PackString() - marshalling function
* StrPtr::UnpackInt() - marshalling function
* StrPtr::UnpackChar() - marshalling function
* StrBuf::UnpackOctet() - marshalling function
* StrPtr::UnpackString() - marshalling function
*/
void
StrOps::PackInt( StrBuf &o, int v )
{
char *b = o.Alloc( 4 );
const unsigned int vv = (unsigned int)v;
b[0] = ( vv / 0x1 ) % 0x100;
b[1] = ( vv / 0x100 ) % 0x100;
b[2] = ( vv / 0x10000 ) % 0x100;
b[3] = ( vv / 0x1000000 ) % 0x100;
}
void
StrOps::PackInt64( StrBuf &o, P4INT64 v )
{
char *b = o.Alloc( 8 );
unsigned P4INT64 vv = (unsigned P4INT64)v;
b[0] = ( vv / 0x1 ) % 0x100;
b[1] = ( vv / 0x100 ) % 0x100;
b[2] = ( vv / 0x10000 ) % 0x100;
b[3] = ( vv / 0x1000000 ) % 0x100;
// On machines Without int64's, two >>16
// will avoid complaints and zero v.
vv >>= 16;
vv >>= 16;
b[4] = ( vv / 0x1 ) % 0x100;
b[5] = ( vv / 0x100 ) % 0x100;
b[6] = ( vv / 0x10000 ) % 0x100;
b[7] = ( vv / 0x1000000 ) % 0x100;
}
void
StrOps::PackIntA( StrBuf &o, int v )
{
o << v;
o.Extend(0);
}
void
StrOps::PackChar( StrBuf &o, const char *c, int length )
{
char *end;
// Append up to null, or whole thing if no null
if( end = (char *)memchr( c, 0, length ) )
length = end + 1 - c;
o.Append( c, length );
}
void
StrOps::PackOctet( StrBuf &o, const StrPtr &s )
{
o.Append( &s );
}
void
StrOps::PackString( StrBuf &o, const StrPtr &s )
{
PackInt( o, s.Length() );
o.Append( &s );
}
void
StrOps::PackStringA( StrBuf &o, const StrPtr &s )
{
PackIntA( o, s.Length() );
o.Append( &s );
}
int
StrOps::UnpackInt( StrRef &o )
{
if( o.Length() < 4 )
return 0;
const char *b = o.Text();
o += 4;
return
(unsigned char)b[0] * (unsigned int)0x1 +
(unsigned char)b[1] * (unsigned int)0x100 +
(unsigned char)b[2] * (unsigned int)0x10000 +
(unsigned char)b[3] * (unsigned int)0x1000000;
}
P4INT64
StrOps::UnpackInt64( StrRef &o )
{
if( o.Length() < 8 )
return 0;
const char *b = o.Text();
o += 8;
P4INT64 v =
(unsigned char)b[4] * (unsigned int)0x1 +
(unsigned char)b[5] * (unsigned int)0x100 +
(unsigned char)b[6] * (unsigned int)0x10000 +
(unsigned char)b[7] * (unsigned int)0x1000000;
// On machines without int64, this will just overflow
// and zero v, without complaint from the compiler.
v <<= 16; v <<= 16;
return v +
(unsigned char)b[0] * (unsigned int)0x1 +
(unsigned char)b[1] * (unsigned int)0x100 +
(unsigned char)b[2] * (unsigned int)0x10000 +
(unsigned char)b[3] * (unsigned int)0x1000000;
}
int
StrOps::UnpackIntA( StrRef &o )
{
char *buffer = o.Text();
int length = o.Length();
int v = 0;
int s = length && *buffer == '-';
if( s )
++buffer, --length;
while( length && *buffer )
{
v = v * 10 + *buffer - '0';
++buffer, --length;
}
if( length )
++buffer, --length;
o.Set( buffer, length );
return s ? -v : v;
}
void
StrOps::UnpackChar( StrRef &o, char *c, int l )
{
if( l > o.Length() )
l = o.Length();
char *end;
// Unpack whole thing
if( end = (char *)memccpy( c, o.Text(), 0, l ) )
l = end - c;
o += l;
}
void
StrOps::UnpackOctet( StrRef &o, const StrPtr &s )
{
int l = s.Length();
if( l > o.Length() )
l = o.Length();
memcpy( s.Text(), o.Text(), l );
o += l;
}
void
StrOps::UnpackString( StrRef &o, StrBuf &s )
{
int l = UnpackInt( o );
if( l > o.Length() )
l = o.Length();
s.Set( o.Text(), l );
o += l;
}
void
StrOps::UnpackStringA( StrRef &o, StrBuf &s )
{
int l = UnpackIntA( o );
if( l > o.Length() )
l = o.Length();
s.Set( o.Text(), l );
o += l;
}
void
StrOps::UnpackString( StrRef &o, StrRef &s )
{
int l = UnpackInt( o );
if( l > o.Length() )
l = o.Length();
s.Set( o.Text(), l );
o += l;
}
void
StrOps::UnpackStringA( StrRef &o, StrRef &s )
{
int l = UnpackIntA( o );
if( l > o.Length() )
l = o.Length();
s.Set( o.Text(), l );
o += l;
}
/*
* i18n
*/
int
StrOps::CharCnt( const StrPtr &s )
{
int cs = GlobalCharSet::Get();
if( !cs )
return s.Length();
CharStep *step = CharStep::Create( s.Text(), cs );
int ret = step->CountChars( s.End() );
delete step;
return ret;
}
void
StrOps::CharCopy( const StrPtr &s, StrBuf &t, int length )
{
int charSet;
if( s.Length() < length )
{
length = s.Length();
}
else if( s.Length() > length && ( charSet = GlobalCharSet::Get() ) )
{
// i18n -- copy 'length' characters (possibly many more bytes)
int i = 0;
CharStep *ss = CharStep::Create( s.Text(), charSet );
while( ss->Next() < s.End() && ++i < length )
;
length = ss->Ptr() - s.Text();
delete ss;
}
t.Set( s.Text(), length );
}
int
StrOps::SafeLen( const StrPtr &s )
{
int cs = GlobalCharSet::Get();
if( cs == 1 ) // utf8
{
CharSetUTF8Valid v;
const char *rp;
if( v.Valid( s.Text(), s.Length(), &rp ) != 1 )
return rp - s.Text();
}
return s.Length();
}
/*
* StrOps::ScrunchArgs() - try to display argv in a limited output buffer.
*
* This scrunches in two ways:
*
* 1. If any argument is too long (more than 1/4 the output if there
* are 4 or more args), the argument is clipped to be left...right.
*
* 2. If we run out of room even to display even clipped arguments,
* we just output (number-of-skipped-args) and then the last argument.
*/
void
StrOps::ScrunchArgs( StrBuf &out, int argc, StrPtr *argv, int targetLength,
int delim, const char *unsafeChars )
{
if( !argc )
return;
StrBuf dStr;
dStr.Extend( (char)delim );
dStr.Terminate();
// Each arg gets at most 1/4th the targetLength,
// unless there are fewer than 4 args.
int pieces = argc < 4 ? argc : 4;
int eachSpace = targetLength / pieces;
// Leave room for last argument -- we like to see it.
int endPost = CharCnt(out) + targetLength;
int lastargLen = CharCnt(argv[argc-1]);
endPost -= lastargLen < eachSpace ? lastargLen : eachSpace;
// For each arg
for( ; argc--; ++argv )
{
StrBuf argBuf, maskBuf;
StrPtr *theArg = argv;
if( unsafeChars )
{
WildToStr( *argv, maskBuf, unsafeChars );
EncodeNonPrintable( maskBuf, argBuf );
theArg = &argBuf;
}
int mySpace = CharCnt(*theArg);
int myLength = mySpace;
// If there are more args coming, we can take only our
// alloted eachSpace, and we may have to skip out on
// printing anything if we're already against the endPost.
if( argc )
{
// Back off to 1/4 targetLength max
if( mySpace > eachSpace )
mySpace = eachSpace;
// Will no more args fit?
// Just mention # of args skipped.
// We'll still dump the last arg.
if( mySpace + CharCnt(out) > endPost )
{
out << "(" << argc << ")" << dStr;
argv += argc - 1;
argc = 1;
continue;
}
}
// If this arg is bigger than our allocated space,
// dump out left...right of arg.
// Otherwise, dump whole arg.
if( myLength > mySpace )
{
int side = ( mySpace - 3 ) / 2;
int cs = GlobalCharSet::Get();
if( !cs )
{
out << StrRef( theArg->Text(), side );
out << "...";
out << StrRef( theArg->End() - side, side );
}
else
{
CharStep *step = CharStep::Create( theArg->Text(), cs );
out << StrRef( theArg->Text(),
step->Next( side ) - theArg->Text() );
out << "...";
step->Next( myLength - 2 * side );
out << StrRef( step->Ptr(), theArg->End() - step->Ptr() );
delete step;
}
}
else
{
out << *theArg;
}
// blank between args
if( argc )
out << dStr;
}
}
/*
* StrOps::GetDepotFileExtension() - Extracts the .xyz from a path, sans dot.
*/
void
StrOps::GetDepotFileExtension( const StrBuf &path, StrBuf &ext )
{
const char *dot = strrchr( path.Text(), '.' );
const char *sep = strrchr( path.Text(), '/' );
// file
// di.r/file
if( !dot || sep >= dot )
return;
// file..
if( ( path.Length() - ( dot - path.Text() ) ) > 0 )
// file.txt -> 'txt'
ext.Set( dot + 1 );
}
/*
* StrOps::GetDepotName() - extracts the depot name from a depot path
*/
void
StrOps::GetDepotName( const char *d, StrBuf &n )
{
const char *s = strstr( d, "//" );
const char *p = d + 2;
if( !s || s != d )
return;
s = strstr( p, "/" );
if( !s )
return;
n.Append( p, s - p );
}
/*
* StrOps::StreamNameInPath() - extract stream name from a depotFile & depth
*/
int
StrOps::StreamNameInPath( const char *dFile, int depth, StrBuf &name )
{
int slash = 0;
const char *t = ( dFile + 2 );
// string to depth+1 slashes then remove trailing slash
for( slash = 0; slash < depth + 1; slash++, t++ )
{
t = strchr( t, '/' );
if( !t ) return 0;
}
name.Append( dFile, --t - dFile );
return --slash;
}
/*
* StrOps::CommonPath() - Build a common file path given multiple depotpaths.
*
* Common path result is passed in as the first argument, the second
* argument maintains a state that will indicate that paths are from multiple
* directories (will need ...) appended. The third argument is the next
* depotfile for consideration.
*
* e.g.
* StrBuf root;
* int mdir = 0;
*
* StrOps::CommonPath( root, mdir, depotPath1 );
* StrOps::CommonPath( root, mdir, depotPath2 );
* StrOps::CommonPath( root, mdir, depotPath3 );
* StrOps::CommonPath( root, mdir, depotPath4 );
* StrOps::CommonPath( root, mdir, depotPath5 );
*
* if( mdir )
* root.Append( "..." );
* else
* root.Append( "*" );
*/
void
StrOps::CommonPath( StrBuf &o, int &mdir, const StrPtr &n )
{
if( o.Length() )
{
char *op = o.Text();
char *np = n.Text();
while( op < o.End() && StrPtr::SEqual( *op, *np ) )
++op, ++np;
// check to see if multiple directories
if( !mdir && ( strchr( op, '/' ) || strchr( np, '/' ) ) )
mdir = 1;
if( mdir && op[-1] == '.' )
o.SetEnd( op - 1 );
else
o.SetEnd( op );
}
else
{
o = n;
char *s = o.Text();
char *e = o.End();
while( e > s && *e != '/')
--e;
o.SetEnd( ++e );
}
}
/*
* StrOps::StripNewline() - strip \r\n from end of buffer
*/
void
StrOps::StripNewline( StrBuf &o )
{
if( o.Length() && o.End()[ -1 ] == '\n' )
o.SetEnd( o.End() -1 );
if( o.Length() && o.End()[ -1 ] == '\r' )
o.SetEnd( o.End() -1 );
o.Terminate();
}
void
StrOps::EncodeNonPrintable( const StrPtr &i, StrBuf &o, int maskp, int cmdSafe)
{
o.Clear();
char *p = i.Text();
char *s;
while( *p )
{
s = p;
while( *p )
{
if( !cmdSafe && !isAprint( p ) )
break;
else if( cmdSafe && ( isAhighchar( p ) || !isAalnum( p ) ) )
break;
else if( maskp && *p == '%' )
break;
++p;
}
o.Append( s, p - s );
if( *p )
{
char buf[3];
buf[0] = '%';
buf[1] = OtoX( ( *p >> 4 ) & 0x0f );
buf[2] = OtoX( ( *p++ >> 0 ) & 0x0f );
o.Append( buf, 3 );
}
}
}
void
StrOps::DecodeNonPrintable( const StrPtr &i, StrBuf &o )
{
o.Clear();
char *p = i.Text();
char *s;
while( *p )
{
s = p;
while( *p )
{
if( p[0] == '%' && p[1] == '%' )
p += 2;
else if( p[0] != '%' )
p++;
else
break;
}
o.Append( s, p - s );
if( *p )
{
char b[2];
b[0] = ( XtoO( p[1] ) << 4 ) | ( XtoO( p[2] ) << 0 );
o.Append( b, 1 );
p += 3;
}
}
}
void
StrOps::LFtoCRLF( const StrBuf *in, StrBuf *out )
{
out->Clear();
const char *s = in->Text(), *p = s;
while( ( p - s ) < in->Length() )
{
if( *p == '\n' )
out->Extend( '\r' );
out->Extend( *p );
p++;
}
out->Terminate();
}
unsigned int
StrOps::HashStringToBucket( const StrPtr &in, int buckets )
{
unsigned int tot = 0;
unsigned char *s = (unsigned char *)in.Text();
for( int i = 0; i<in.Length(); ++i )
tot = CHARHASH( tot, *s++ );
return( tot%buckets );
}
| 18.516779
| 80
| 0.469472
|
gorlak
|
411c1271c107c31bf0823b036b46fad178394606
| 2,833
|
cc
|
C++
|
spot/tests/core/tostring.cc
|
mcc-petrinets/formulas
|
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
|
[
"MIT"
] | 1
|
2018-03-02T14:29:57.000Z
|
2018-03-02T14:29:57.000Z
|
spot/tests/core/tostring.cc
|
mcc-petrinets/formulas
|
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
|
[
"MIT"
] | null | null | null |
spot/tests/core/tostring.cc
|
mcc-petrinets/formulas
|
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
|
[
"MIT"
] | 1
|
2015-06-05T12:42:07.000Z
|
2015-06-05T12:42:07.000Z
|
// -*- coding: utf-8 -*-
// Copyright (C) 2008, 2009, 2012, 2015, 2016 Laboratoire de Recherche
// et Développement de l'Epita (LRDE).
// Copyright (C) 2003 Laboratoire d'Informatique de Paris 6 (LIP6),
// département Systèmes Répartis Coopératifs (SRC), Université Pierre
// et Marie Curie.
//
// This file is part of Spot, a model checking library.
//
// Spot 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.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <iostream>
#include <cassert>
#include <spot/tl/parse.hh>
#include <spot/tl/print.hh>
const char* inputs[] =
{
"a",
"1",
"0",
"a => b",
"G a ",
"a U b",
"a & b",
"a & b & c",
"b & a & b",
"b & a & a",
"a & b & (c |(f U g)| e)",
"b & a & a & (c | e |(f U g)| e | c) & b",
"a <=> b",
"a & b & (c |(f U g)| e)",
"b & a & a & (c | e |(g U g)| e | c) & b",
"F\"F1\"&G\"G\"&X\"X\"",
"GFfalse",
"GFtrue",
"p=0Uq=1Ut=1",
"F\"FALSE\"",
"G\"TruE\"",
"FFALSE",
"GTruE",
"p=0UFXp=1",
"GF\"\\GF\"",
"GF\"foo bar\"",
"FFG__GFF",
"X\"U\"",
"X\"W\"",
"X\"M\"",
"X\"R\"",
"{a;b;{c && d*};**}|=>G{a*:b*}",
"GF!{{a || c} && b}",
"GF!{{a || c*} && b}<>->{{!a}*}",
"GF{{a || c*} & b[*]}[]->{d}",
"{a[*2..3]}",
"{a[*0..1]}",
"{a[*0..]}",
"{a[*..]}",
"{a[*1..]}",
"{a[+]}",
"{[+]}",
"{a[*2..3][*4..5]}",
"{a**}<>->1",
};
int main()
{
for (const char* input: inputs)
{
{
auto pf1 = spot::parse_infix_psl(input);
if (pf1.format_errors(std::cerr))
return 2;
auto f1 = pf1.f;
// The string generated from an abstract tree should be parsable
// again.
std::string f1s = spot::str_psl(f1);
std::cout << f1s << '\n';
auto pf2 = spot::parse_infix_psl(f1s);
if (pf2.format_errors(std::cerr))
return 2;
auto f2 = pf2.f;
// This second abstract tree should be equal to the first.
if (f1 != f2)
return 1;
// It should also map to the same string.
std::string f2s = spot::str_psl(f2);
if (f2s != f1s)
{
std::cerr << f1s << " != " << f2s << '\n';
return 1;
}
}
assert(spot::fnode::instances_check());
}
return 0;
}
| 24.213675
| 72
| 0.507589
|
mcc-petrinets
|
411e2d9b298c266088f96e61e5f657debeb92e81
| 3,121
|
cc
|
C++
|
CodeChef/WF/Medium Hard/LOTERY/A.cc
|
VastoLorde95/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | 170
|
2017-07-25T14:47:29.000Z
|
2022-01-26T19:16:31.000Z
|
CodeChef/WF/Medium Hard/LOTERY/A.cc
|
navodit15/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | null | null | null |
CodeChef/WF/Medium Hard/LOTERY/A.cc
|
navodit15/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | 55
|
2017-07-28T06:17:33.000Z
|
2021-10-31T03:06:22.000Z
|
#include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define foreach(it, v) for(auto it=(v).begin(); it != (v).end(); ++it)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define tr(...) cout<<__FUNCTION__<<' '<<__LINE__<<" = ";trace(#__VA_ARGS__, __VA_ARGS__)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
template<typename S, typename T>
ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;}
template<typename T>
ostream& operator<<(ostream& out,vector<T> const& v){
int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;}
template<typename T>
void trace(const char* name, T&& arg1){cout<<name<<" : "<<arg1<<endl;}
template<typename T, typename... Args>
void trace(const char* names, T&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma-names)<<" : "<<arg1<<" | ";trace(comma+1,args...);}
const int MOD = 1e9 + 7;
const int N = 100001;
inline int fast(int a, int b){
int ret = 1;
while(b){
if((b&1)) ret = (ll) ret * a %MOD;
a = (ll) a * a % MOD;
b >>= 1;
}
return ret;
}
int isprime[N];
int ppro[N];
int ippro[N];
int invp[N];
vector<int> primes;
void pre(int n){
isprime[2] = 1;
for(int i = 3; i <= n; i += 2) isprime[i] = 1;
for(int i = 3; i * i <= n; i += 2){
if(!isprime[i]) continue;
for(int j = i * i; j <= n; j += i) isprime[j] = 0;
}
ppro[0] = 1;
for(int i = 1; i <= n; i++){
if(isprime[i]){
ppro[i] = (ll) ppro[i-1] * i % MOD;
invp[i] = fast(i, MOD-2);
primes.pb(i);
}
else ppro[i] = ppro[i-1];
ippro[i] = fast(ppro[i], MOD-2);
}
}
int solve(int n, int k){
int rt = sqrt(n) + 1;
int ans = 1;
int num, mx;
for(int p : primes){
if(p >= rt) break;
num = p;
mx = 1;
while(num <= n){
if((n/num)*num >= n-k+1)
mx = num;
else break;
num *= p;
}
if(mx > 1) ans = (ll) ans * mx % MOD;
}
int L = max(n-k+1, rt), R = n;
ans = (ll) ans * ((ll) ppro[R] * ippro[L-1] % MOD) % MOD;
int low = L, high = R, x, y;
for(int i = 2; i <= rt; i++){
x = (L-1) / i + 1, y = R / i;
x = max(x, rt);
if(x > y) continue;
if(x >= low) continue;
high = min(low-1, y);
low = x;
ans = (ll) ans * ((ll) ppro[high] * ippro[low-1] % MOD) % MOD;
i = max(i+1, R / high) - 1;
}
return ans;
}
int c[N*10];
int d[N*10];
int main(){
int t;
sd(t);
int n, k;
scanf("%d%d", &n, &k);
int a, b, m;
scanf("%d%d%d", &a, &b, &m);
pre(m);
for(int i = 1; i < t; i++) scanf("%d", c+i);
for(int i = 1; i < t; i++) scanf("%d", d+i);
int ans = solve(n, k);
printf("%d\n", ans);
for(int i = 1; i < t; i++){
n = 1 + ((ll) a * ans + c[i]) % m;
k = 1 + ((ll) b * ans + d[i]) % n;
ans = solve(n, k);
printf("%d\n", ans);
}
return 0;
}
| 19.878981
| 118
| 0.521948
|
VastoLorde95
|
411fec6bb00572d72e8ddbbead952383ea18a1b5
| 5,456
|
cpp
|
C++
|
src/provider/local/src/movie/moviemetadatafetcher.cpp
|
jimmypoms/couch
|
2371ad236a04bf9623098da9b1fdec10997f1dd0
|
[
"Apache-2.0"
] | null | null | null |
src/provider/local/src/movie/moviemetadatafetcher.cpp
|
jimmypoms/couch
|
2371ad236a04bf9623098da9b1fdec10997f1dd0
|
[
"Apache-2.0"
] | null | null | null |
src/provider/local/src/movie/moviemetadatafetcher.cpp
|
jimmypoms/couch
|
2371ad236a04bf9623098da9b1fdec10997f1dd0
|
[
"Apache-2.0"
] | null | null | null |
/*
* movieinfofetcher.cpp
*
* Created on: 4 Nov 2015
* Author: jimmypoms
*/
#include "moviemetadatafetcher.h"
#include <qfile.h>
#include <qglobal.h>
#include <qiodevice.h>
#include <qstring.h>
#include <qurl.h>
#include <qxmlstream.h>
#include "couch/movie/moviemetadata.h"
#include "couch/source.h"
using namespace MediaInfoDLL;
MovieMetadataFetcher::MovieMetadataFetcher()
{
m_mediaInfoHandle.Option("Internet", "No");
}
bool MovieMetadataFetcher::fetchNfoMetadata(MovieMetadata &metadata, const QFileInfo &fileInfo)
{
QFile nfoFile(fileInfo.absolutePath() + "/" + fileInfo.completeBaseName() + ".nfo");
if (!nfoFile.exists()) {
return false;
}
if (!nfoFile.open(QIODevice::ReadOnly)) {
return false;
}
QXmlStreamReader xml(&nfoFile);
while (!xml.atEnd() && xml.readNextStartElement()) {
if (xml.name() == "movie") {
readMovieTag(xml, metadata);
} else {
xml.skipCurrentElement();
}
}
return true;
}
void MovieMetadataFetcher::readMovieTag(QXmlStreamReader &xml, MovieMetadata &metadata)
{
Q_ASSERT(xml.isStartElement() && xml.name() == "movie");
while (xml.readNextStartElement()) {
if (xml.name() == "actor") {
readActorTag(xml, metadata);
} else if (xml.name() == "fanart") {
readFanartTag(xml, metadata);
} else if (xml.name() == "title") {
metadata.setName(readStringTag(xml));
} else if (xml.name() == "tagline") {
metadata.setTagline(readStringTag(xml));
} else if (xml.name() == "year") {
metadata.setYear(readIntTag(xml));
} else if (xml.name() == "popularity") {
metadata.setPopularity(readIntTag(xml) / 100);
} else if (xml.name() == "rating") {
metadata.setRating(readDoubleTag(xml) / 10.0);
} else if (xml.name() == "runtime") {
metadata.setRuntime(readIntTag(xml));
} else if (xml.name() == "thumb") {
if (metadata.image().isEmpty()) {
metadata.setImage(QUrl(xml.attributes().value("preview").toString()));
} else {
xml.skipCurrentElement();
}
xml.readElementText(QXmlStreamReader::SkipChildElements);
} else if (xml.name() == "plot") {
metadata.setDescription(readStringTag(xml));
} else if (xml.name() == "genre") {
metadata.addGenre(readStringTag(xml));
} else if (xml.name() == "country") {
metadata.setCountry(readStringTag(xml));
} else if (xml.name() == "credits") {
metadata.addCredit(readStringTag(xml));
} else if (xml.name() == "director") {
metadata.addDirector(readStringTag(xml));
} else if (xml.name() == "studio") {
metadata.setStudio(readStringTag(xml));
} else if (xml.name() == "trailer") {
metadata.setTrailer(readTrailerTag(xml));
} else {
xml.skipCurrentElement();
}
}
}
void MovieMetadataFetcher::readActorTag(QXmlStreamReader &xml, MovieMetadata &metadata)
{
Q_ASSERT(xml.isStartElement() && xml.name() == "actor");
while (xml.readNextStartElement()) {
if (xml.name() == "name") {
metadata.addActor(readStringTag(xml));
} else {
xml.skipCurrentElement();
}
}
}
void MovieMetadataFetcher::readFanartTag(QXmlStreamReader &xml, MovieMetadata &metadata)
{
Q_ASSERT(xml.isStartElement() && xml.name() == "fanart");
while (xml.readNextStartElement()) {
if (metadata.poster().isEmpty() && xml.name() == "thumb") {
metadata.setPoster(readUrlTag(xml));
} else {
xml.skipCurrentElement();
}
}
}
QUrl MovieMetadataFetcher::readTrailerTag(QXmlStreamReader &xml)
{
QString trailer = xml.readElementText(QXmlStreamReader::SkipChildElements);
trailer.replace("plugin://plugin.video.youtube/?action=play_video&videoid=",
"https://www.youtube.com/watch?v=");
return QUrl(trailer);
}
QString MovieMetadataFetcher::readStringTag(QXmlStreamReader &xml)
{
return xml.readElementText(QXmlStreamReader::SkipChildElements);
}
int MovieMetadataFetcher::readIntTag(QXmlStreamReader &xml)
{
return xml.readElementText(QXmlStreamReader::SkipChildElements).toInt();
}
double MovieMetadataFetcher::readDoubleTag(QXmlStreamReader &xml)
{
return xml.readElementText(QXmlStreamReader::SkipChildElements).toDouble();
}
QUrl MovieMetadataFetcher::readUrlTag(QXmlStreamReader& xml)
{
return QUrl(xml.readElementText(QXmlStreamReader::SkipChildElements));
}
bool MovieMetadataFetcher::fetchFileMetadata(MovieMetadata &metadata, const QFileInfo &fileInfo)
{
return false;
}
void MovieMetadataFetcher::fetch(MovieMetadata &metadata, Source &source)
{
QFileInfo fileInfo(source.url().toLocalFile());
if (!fileInfo.exists()) {
return;
}
m_mediaInfoHandle.Open(source.url().toLocalFile().toStdString());
std::string width(m_mediaInfoHandle.Get(Stream_Video, 0, "Width"));
std::string height(m_mediaInfoHandle.Get(Stream_Video, 0, "Height"));
source.setSizeBytes(fileInfo.size());
source.setQuality(QString::fromStdString(width + " x " + height));
if (fetchNfoMetadata(metadata, fileInfo)) {
return;
}
if (fetchFileMetadata(metadata, fileInfo)) {
return;
}
}
| 31.537572
| 96
| 0.629216
|
jimmypoms
|
41204d277c876bfce0bd5ad03b90ccbf0eb34943
| 2,435
|
cpp
|
C++
|
test/test-views/chain-request.cpp
|
amukha/fostgres
|
d908e80d6ebeafc456bae086dd397c216d59b001
|
[
"BSL-1.0"
] | 17
|
2017-02-06T07:54:49.000Z
|
2019-07-20T03:55:15.000Z
|
test/test-views/chain-request.cpp
|
amukha/fostgres
|
d908e80d6ebeafc456bae086dd397c216d59b001
|
[
"BSL-1.0"
] | 17
|
2017-06-01T08:51:26.000Z
|
2019-09-02T13:46:23.000Z
|
test/test-views/chain-request.cpp
|
amukha/fostgres
|
d908e80d6ebeafc456bae086dd397c216d59b001
|
[
"BSL-1.0"
] | 6
|
2017-05-03T13:05:19.000Z
|
2019-08-06T11:34:41.000Z
|
/**
Copyright 2020 Red Anchor Trading Co. Ltd.
Distributed under the Boost Software License, Version 1.0.
See <http://www.boost.org/LICENSE_1_0.txt>
*/
#include <fost/http>
#include <fost/ua/exceptions.hpp>
#include <fost/urlhandler>
namespace {
const class chain_request : public fostlib::urlhandler::view {
public:
chain_request() : view("test.chain.request") {}
std::pair<boost::shared_ptr<fostlib::mime>, int> operator()(
const fostlib::json &config,
const fostlib::string &path,
fostlib::http::server::request &req,
const fostlib::host &host) const {
auto const body_str = fostlib::coerce<fostlib::string>(
fostlib::coerce<fostlib::utf8_string>(req.data()->data()));
auto const body = fostlib::json::parse(body_str);
fostlib::mime::mime_headers headers;
fostlib::string url = "http://127.0.0.1/test/"
+ fostlib::coerce<fostlib::string>(body["id"]);
boost::shared_ptr<fostlib::mime> response(new fostlib::text_body(
fostlib::json::unparse(fostlib::json{}, true), headers,
"application/json"));
fostlib::json result;
try {
if (fostlib::coerce<fostlib::string>(body["method"]) == "GET") {
result = fostlib::ua::get_json(fostlib::url{url}, headers);
} else {
result = fostlib::ua::post_json(
fostlib::url{url}, fostlib::json{}, headers);
}
} catch (fostlib::ua::unauthorized &e) {
return std::make_pair(response, 401);
} catch (fostlib::ua::forbidden &e) {
return std::make_pair(response, 403);
} catch (fostlib::ua::resource_not_found &e) {
return std::make_pair(response, 404);
} catch (fostlib::ua::http_error &e) {
auto status = fostlib::coerce<int>(e.data()["status-code"]);
return std::make_pair(response, status);
}
response = boost::shared_ptr<fostlib::mime>(new fostlib::text_body(
fostlib::json::unparse(result, true), headers,
"application/json"));
return std::make_pair(response, 200);
}
} c_chain_request;
}
| 36.893939
| 80
| 0.540041
|
amukha
|
41210be229bacb8ae73157fc015e68dbc23b0b33
| 450
|
hpp
|
C++
|
GUI/GUI-extc.hpp
|
erurami/huffman-encoder
|
94278ddcda8611dfe65638f7905a3f349bcd4064
|
[
"MIT"
] | null | null | null |
GUI/GUI-extc.hpp
|
erurami/huffman-encoder
|
94278ddcda8611dfe65638f7905a3f349bcd4064
|
[
"MIT"
] | null | null | null |
GUI/GUI-extc.hpp
|
erurami/huffman-encoder
|
94278ddcda8611dfe65638f7905a3f349bcd4064
|
[
"MIT"
] | null | null | null |
#ifndef _GUI_GUI_EXTC_HPP_
#define _GUI_GUI_EXTC_HPP_
#include <windows.h>
#define EXTCPROG_WINDOW_WIDTH 400
#define EXTCPROG_WINDOW_HEIGHT 220
HINSTANCE _G_GUI_GUI_Extc_hpp_H_Instance;
struct ExtractionInfos
{
LPTSTR strFrom;
LPTSTR strTo;
bool blKeepOriginal;
long* npProgress;
int * npExtractionStage;
};
bool StartExtractionWithGUI(ExtractionInfos* pExtcInfo, HWND hParentWindow);
#include "GUI-extc.ipp"
#endif
| 14.516129
| 76
| 0.775556
|
erurami
|
41216132d55a5bd9a68982563e0f3b00ab9036e9
| 1,843
|
cpp
|
C++
|
BZOJ/4635/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/4635/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/4635/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
#include<cstdio>
const int N=1001,M=7100,P=1000000007;
int T,type,t,n,m,l,r,i,j;
int f[N][N],s[N][N],G[N],V[M],NXT[M],mul[N],g[N],v[M],nxt[M],ed;
int p[N],a[10000001],b[N],ans;
inline void up(int&a,int b){a+=b;while(a>=P)a-=P;}
inline int pow(int a,int b){int t=1;for(;b;b>>=1,a=1LL*a*a%P)if(b&1)t=1LL*t*a%P;return t;}
inline void init(int x,int n){
int t=0,i,j;
for(i=2;i<=x;i=j+1)j=x/(x/i),up(t,1LL*(j-i+1)*a[x/i]%P);
a[x]=(pow(x,n)+P-t)%P;
}
void dfs(int x,int y,int z){
if(x==t){
if(z==1)return;
mul[y>0?y:-y]=z;
v[++ed]=y;nxt[ed]=g[i];g[i]=ed;
return;
}
dfs(x+1,y,z),dfs(x+1,-y*a[x],z*b[x]);
}
inline void cal(int x){
up(ans,p[m]);
for(int i=g[x];i;i=nxt[i]){
if(v[i]>0)up(ans,p[a[v[i]]]);
else up(ans,P-p[a[-v[i]]]);
}
}
int main(){
freopen("code.in","r",stdin);freopen("std.out","w",stdout);
scanf("%d%d",&T,&type);
if(type==1){
a[1]=1;
while(T--){
scanf("%d%d%d%d",&n,&m,&l,&r);ans=0;
for(i=1;i<=m;i=m/(m/i)+1)v[++t]=m/i;
while(t)init(v[t--],n);
for(i=l;i<=r;i=j+1){
j=m/(m/i);
if(j>r)j=r;
up(ans,1LL*(j-i+1)*a[m/i]%P);
}
printf("%d\n",ans);
}
}else{
for(i=0;i<N;i++)f[0][i]=f[i][0]=f[i][i]=i;
for(i=2;i<N;i++)for(j=1;j<i;j++)f[i][j]=f[j][i]=f[i-j][j];
for(i=1;i<N;i++)for(j=1;j<N;j++)s[i][j]=s[i][j-1]+(f[i][j]==1);
for(i=1;i<N;i++)for(j=i;j<N;j+=i)V[++ed]=i,NXT[ed]=G[j],G[j]=ed;
for(ed=0,i=2;i<N;i++){
for(n=i,t=0,j=2;j<=n;j++)if(n%j==0){
for(m=1;n%j==0;n/=j,m*=j);
a[t]=m,b[t++]=j;
}
dfs(0,1,1);
}
while(T--){
scanf("%d%d%d%d",&n,&m,&l,&r);ans=0;
for(i=1;i<=m;i++)p[i]=pow(i,n);
for(i=2;i<=m;i++)for(a[i]=0,j=G[i/mul[i]];j;j=NXT[j])a[i]+=s[i][m/V[j]];
while(l<=r)cal(l++);
printf("%d\n",ans);
}
}
return 0;
}
| 27.507463
| 90
| 0.45198
|
sjj118
|
412529ab284bbe64123f3e55276a236abadccb47
| 6,843
|
cpp
|
C++
|
event_handles/Sewing2dPatternEventHandle.cpp
|
dolphin-li/ClothDesigner
|
82b186d6db320b645ac67a4d32d7746cc9bdd391
|
[
"MIT"
] | 32
|
2016-12-13T05:49:12.000Z
|
2022-02-04T06:15:47.000Z
|
event_handles/Sewing2dPatternEventHandle.cpp
|
dolphin-li/ClothDesigner
|
82b186d6db320b645ac67a4d32d7746cc9bdd391
|
[
"MIT"
] | 2
|
2019-07-30T02:01:16.000Z
|
2020-03-12T15:06:51.000Z
|
event_handles/Sewing2dPatternEventHandle.cpp
|
dolphin-li/ClothDesigner
|
82b186d6db320b645ac67a4d32d7746cc9bdd391
|
[
"MIT"
] | 18
|
2017-11-16T13:37:06.000Z
|
2022-03-11T08:13:46.000Z
|
#include <QEvent>
#include <GL\glew.h>
#include "Viewer2d.h"
#include "Viewer3d.h"
#include "cloth\clothManager.h"
#include "cloth\clothPiece.h"
#include "Renderable\ObjMesh.h"
#include "cloth\graph\GraphsSewing.h"
#include "../clothdesigner.h"
#include "Sewing2dPatternEventHandle.h"
Sewing2dPatternEventHandle::Sewing2dPatternEventHandle(Viewer2d* v)
: Abstract2dEventHandle(v)
{
QString name = "icons/pattern_sewing.png";
QPixmap img(name);
img = img.scaledToWidth(32, Qt::TransformationMode::SmoothTransformation);
m_cursor = QCursor(img, 1, 1);
m_iconFile = name;
m_inactiveIconFile = name;
m_toolTips = "edit sewing";
}
Sewing2dPatternEventHandle::~Sewing2dPatternEventHandle()
{
}
void Sewing2dPatternEventHandle::handleEnter()
{
Abstract2dEventHandle::handleEnter();
m_viewer->setFocus();
m_viewer->beginSewingMode();
m_viewer->deleteCurrentUISew();
}
void Sewing2dPatternEventHandle::handleLeave()
{
m_viewer->deleteCurrentUISew();
m_viewer->endSewingMode();
m_viewer->clearFocus();
m_viewer->endDragBox();
Abstract2dEventHandle::handleLeave();
}
void Sewing2dPatternEventHandle::mousePressEvent(QMouseEvent *ev)
{
Abstract2dEventHandle::mousePressEvent(ev);
if (ev->buttons() == Qt::LeftButton)
{
pick(ev->pos());
if (pickInfo().renderId == 0)
m_viewer->beginDragBox(ev->pos());
} // end if left button
}
void Sewing2dPatternEventHandle::mouseReleaseEvent(QMouseEvent *ev)
{
auto manager = m_viewer->getManager();
if (manager == nullptr)
return;
if (m_viewer->buttons() == Qt::LeftButton)
{
auto op = ldp::AbstractGraphObject::SelectThis;
if (ev->modifiers() & Qt::SHIFT)
op = ldp::AbstractGraphObject::SelectUnion;
if (ev->modifiers() & Qt::CTRL)
op = ldp::AbstractGraphObject::SelectUnionInverse;
if (ev->pos() == m_mouse_press_pt)
{
bool changed = false;
for (size_t iSewing = 0; iSewing < manager->numGraphSewings(); iSewing++)
if (manager->graphSewing(iSewing)->select(pickInfo().renderId, op))
changed = true;
if (m_viewer->getMainUI() && changed)
{
m_viewer->getMainUI()->pushHistory(QString().sprintf("sew select: %d",
pickInfo().renderId), ldp::HistoryStack::TypePatternSelect);
m_viewer->getMainUI()->updateUiByParam();
}
auto obj = ldp::GraphsSewing::getObjByIdx(highLightInfo().renderId);
if (obj)
{
if (obj->isCurve())
m_viewer->makeSewUnit((ldp::AbstractGraphCurve*)obj, ev->pos());
}
}
else
{
const QImage& I = m_viewer->fboImage();
std::set<int> ids;
float x0 = std::max(0, std::min(m_mouse_press_pt.x(), ev->pos().x()));
float x1 = std::min(I.width() - 1, std::max(m_mouse_press_pt.x(), ev->pos().x()));
float y0 = std::max(0, std::min(m_mouse_press_pt.y(), ev->pos().y()));
float y1 = std::min(I.height() - 1, std::max(m_mouse_press_pt.y(), ev->pos().y()));
for (int y = y0; y <= y1; y++)
for (int x = x0; x <= x1; x++)
ids.insert(m_viewer->fboRenderedIndex(QPoint(x, y)));
bool changed = false;
for (size_t iSewing = 0; iSewing < manager->numGraphSewings(); iSewing++)
if (manager->graphSewing(iSewing)->select(ids, op))
changed = true;
if (m_viewer->getMainUI() && changed)
{
m_viewer->getMainUI()->pushHistory(QString().sprintf("sew select: %d",
pickInfo().renderId), ldp::HistoryStack::TypePatternSelect);
m_viewer->getMainUI()->updateUiByParam();
}
}
}
m_viewer->endDragBox();
Abstract2dEventHandle::mouseReleaseEvent(ev);
}
void Sewing2dPatternEventHandle::mouseDoubleClickEvent(QMouseEvent *ev)
{
Abstract2dEventHandle::mouseDoubleClickEvent(ev);
}
void Sewing2dPatternEventHandle::mouseMoveEvent(QMouseEvent *ev)
{
Abstract2dEventHandle::mouseMoveEvent(ev);
bool valid = false;
auto obj = ldp::GraphsSewing::getObjByIdx(highLightInfo().renderId);
if (obj)
{
if (obj->isCurve())
{
m_viewer->makeSewUnit((ldp::AbstractGraphCurve*)obj, ev->pos(), true);
valid = true;
}
}
if (!valid)
m_viewer->makeSewUnit(nullptr, ev->pos(), true);
}
void Sewing2dPatternEventHandle::wheelEvent(QWheelEvent *ev)
{
Abstract2dEventHandle::wheelEvent(ev);
}
void Sewing2dPatternEventHandle::keyPressEvent(QKeyEvent *ev)
{
Abstract2dEventHandle::keyPressEvent(ev);
auto manager = m_viewer->getManager();
if (!manager)
return;
ldp::AbstractGraphObject::SelectOp op = ldp::AbstractGraphObject::SelectEnd;
switch (ev->key())
{
default:
break;
case Qt::Key_Escape:
if (ev->modifiers() == Qt::NoModifier)
{
m_viewer->deleteCurrentUISew();
}
break;
case Qt::Key_A:
if (ev->modifiers() == Qt::CTRL)
op = ldp::AbstractGraphObject::SelectAll;
if (ev->modifiers() == Qt::NoModifier)
{
auto r = m_viewer->setNextSewAddingState();
if (m_viewer->getMainUI())
{
if (r == UiSewAddedToPanel)
{
m_viewer->getMainUI()->viewer3d()->updateGL();
m_viewer->getMainUI()->pushHistory("add a sew", ldp::HistoryStack::TypeGeneral);
}
if (r == UiSewUiTmpChanged)
{
m_viewer->getMainUI()->viewer3d()->updateGL();
m_viewer->getMainUI()->pushHistory("add a sew on ui", ldp::HistoryStack::TypeUiSewChanged);
}
}
}
break;
case Qt::Key_D:
if (ev->modifiers() == Qt::CTRL)
op = ldp::AbstractGraphObject::SelectNone;
break;
case Qt::Key_I:
if (ev->modifiers() == (Qt::CTRL | Qt::SHIFT))
op = ldp::AbstractGraphObject::SelectInverse;
break;
case Qt::Key_Delete:
if (ev->modifiers() == Qt::NoModifier)
{
bool change = manager->removeSelectedSewings();
if (m_viewer->getMainUI() && change)
{
m_viewer->getMainUI()->viewer3d()->updateGL();
m_viewer->getMainUI()->pushHistory(QString().sprintf("sewing removed",
op), ldp::HistoryStack::TypeGeneral);
}
}
break;
case Qt::Key_R:
if (ev->modifiers() == Qt::NoModifier)
{
bool change = manager->reverseSelectedSewings();
if (m_viewer->getMainUI() && change)
{
m_viewer->getMainUI()->viewer3d()->updateGL();
m_viewer->getMainUI()->pushHistory(QString().sprintf("sewing reversed",
op), ldp::HistoryStack::TypeGeneral);
}
}
break;
case Qt::Key_P:
if (ev->modifiers() == Qt::NoModifier)
{
bool change = manager->toggleSelectedSewingsType();
if (m_viewer->getMainUI() && change)
{
m_viewer->getMainUI()->viewer3d()->updateGL();
m_viewer->getMainUI()->pushHistory(QString().sprintf("sewing type changed",
op), ldp::HistoryStack::TypeGeneral);
}
}
break;
}
bool changed = false;
for (size_t iSewing = 0; iSewing < manager->numGraphSewings(); iSewing++)
if (manager->graphSewing(iSewing)->select(0, op))
changed = true;
if (m_viewer->getMainUI() && changed)
m_viewer->getMainUI()->pushHistory(QString().sprintf("sew select: all(%d)",
op), ldp::HistoryStack::TypePatternSelect);
}
void Sewing2dPatternEventHandle::keyReleaseEvent(QKeyEvent *ev)
{
Abstract2dEventHandle::keyReleaseEvent(ev);
}
| 28.160494
| 96
| 0.682595
|
dolphin-li
|
4127d200b32a30057857677b98275f949debbbc3
| 2,830
|
cpp
|
C++
|
QPandaSDK/QuantumCommandControl/QCloudCommandVector.cpp
|
ArrowYL/QPanda
|
cef733118cdf8c02676ad710851ad4169bd84b31
|
[
"Apache-2.0"
] | 58
|
2018-07-16T11:09:17.000Z
|
2022-03-01T07:35:52.000Z
|
QPandaSDK/QuantumCommandControl/QCloudCommandVector.cpp
|
ArrowYL/QPanda
|
cef733118cdf8c02676ad710851ad4169bd84b31
|
[
"Apache-2.0"
] | 1
|
2018-12-20T08:59:25.000Z
|
2018-12-20T08:59:25.000Z
|
QPandaSDK/QuantumCommandControl/QCloudCommandVector.cpp
|
ArrowYL/QPanda
|
cef733118cdf8c02676ad710851ad4169bd84b31
|
[
"Apache-2.0"
] | 15
|
2018-07-17T02:55:48.000Z
|
2020-04-22T00:16:09.000Z
|
/******************************************************************************
Copyright (c) 2017-2018 Origin Quantum Computing Co., Ltd.. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language
governing permissions and
limitations under the License.
Author: Dou Menghan
Date:2018-1-29
Description: quantum cloud command vector
************************************************************************/
#include "QCloudCommandVector.h"
#include <regex>
using namespace std;
QCloudCommandVector::QCloudCommandVector()
{
QCommand * pSubmit = dynamic_cast<QCommand *> (new QCommandSubmit);
QCommand * pTaskList = dynamic_cast<QCommand *>(new QCommandTaskList);
QCommand * pGetResult = dynamic_cast<QCommand *>(new QCommandGetResult);
mCommandMap.insert(QCPAIR("submit",pSubmit));
mCommandMap.insert(QCPAIR("tasklist",pTaskList));
mCommandMap.insert(QCPAIR("getresult",pGetResult));
mpVirQCHttp = nullptr;
}
QCloudCommandVector::~QCloudCommandVector()
{
for (auto aiter :mCommandMap)
{
delete(aiter.second);
}
}
/*****************************************************************************************************************
Name: commandAction
Description: command action
Argin: ssAction command name
Argout: None
return: true or false
*****************************************************************************************************************/
bool QCloudCommandVector::commandAction(std::stringstream & ssAction)
{
if (ssAction.str().empty())
{
return false;
}
string sAction(ssAction.str());
regex pattern("(\\w+( )|(\\w+)){1}");
smatch results;
string::const_iterator start = sAction.begin();
string::const_iterator end = sAction.end();
if (regex_search(start, end, results, pattern))
{
string sTemp(results[1].str());
sTemp.erase(sTemp.find_last_not_of(" ") + 1);
auto aiter = mCommandMap.find(sTemp);
if (aiter != mCommandMap.end())
{
return aiter->second->action(ssAction, this->mpVirQCHttp);
}
}
cout << "error command" << endl;
return false;
}
void QCloudCommandVector::commandDescription()
{
for (auto aiter : mCommandMap)
{
aiter.second->description();
}
}
| 30.76087
| 115
| 0.572438
|
ArrowYL
|
412be1a18b70adcc658e3482d4770405496559af
| 10,320
|
cpp
|
C++
|
src/modules/rw_uart/rw_uart.cpp
|
yihangHKU/PX4_Firmware_yh
|
c47884f7665dd500b606b9ca0372d3e2ee9d907d
|
[
"BSD-3-Clause"
] | 1
|
2019-12-25T07:07:34.000Z
|
2019-12-25T07:07:34.000Z
|
src/modules/rw_uart/rw_uart.cpp
|
yihangHKU/yihang
|
c47884f7665dd500b606b9ca0372d3e2ee9d907d
|
[
"BSD-3-Clause"
] | null | null | null |
src/modules/rw_uart/rw_uart.cpp
|
yihangHKU/yihang
|
c47884f7665dd500b606b9ca0372d3e2ee9d907d
|
[
"BSD-3-Clause"
] | 1
|
2022-01-26T16:01:22.000Z
|
2022-01-26T16:01:22.000Z
|
/*
* 串口读取函数
* rw_uart.c
*/
#include <px4_posix.h>
#include <px4_defines.h>
#include <px4_config.h>
#include <px4_tasks.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <stdbool.h>
#include <errno.h>
#include <drivers/drv_hrt.h>
#include <poll.h>
#include <string.h>
#include <systemlib/err.h>
//#include <systemlib/systemlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <uORB/uORB.h>
#include <uORB/topics/pm3901_with_tof.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_attitude.h>
#include <uORB/topics/debug_key_value.h>
#include <uORB/topics/debug_vect.h>
#include <systemlib/mavlink_log.h>
#include <lib/mathlib/math/filter/LowPassFilter2p.hpp>
#include <matrix/matrix/math.hpp>
#include <mathlib/math/EulerFromQuat.hpp>
// ORB_DEFINE(rw_uart_topic, struct rw_uart_topic_s);
extern "C" __EXPORT int rw_uart_main(int argc, char *argv[]);
#define SAMP_RATE (200.0f)
#define LOWP_RATE (20.0f)
static int uart_init(char * uart_name);
static int set_uart_baudrate(const int fd, unsigned int baud);
static orb_advert_t mavlink_log_pub = (void *) 0;
static float last_t = 0.0f;
static float last_pos = 0.0f;
static float last_vel = 0.0f;
static float filt_var[4] = {0.0f};
static int _sample_num = 0;
static float _sample_t = 0.0f;
math::LowPassFilter2p pos_filter(SAMP_RATE, LOWP_RATE);
math::LowPassFilter2p vel_filter(SAMP_RATE, LOWP_RATE);
matrix::EulerFromQuatf _euler;
int set_uart_baudrate(const int fd, unsigned int baud)
{
int speed;
switch (baud) {
case 9600: speed = B9600; break;
case 19200: speed = B19200; break;
case 38400: speed = B38400; break;
case 57600: speed = B57600; break;
case 115200: speed = B115200; break;
default:
warnx("ERR: baudrate: %d\n", baud);
return -EINVAL;
}
struct termios uart_config;
int termios_state;
/* 以新的配置填充结构体 */
/* 设置某个选项,那么就使用"|="运算,
* 如果关闭某个选项就使用"&="和"~"运算
* */
tcgetattr(fd, &uart_config); // 获取终端参数
/* clear ONLCR flag (which appends a CR for every LF) */
uart_config.c_oflag &= ~ONLCR;// 将NL转换成CR(回车)-NL后输出。
/* 无偶校验,一个停止位 */
uart_config.c_cflag &= ~(CSTOPB | PARENB);// CSTOPB 使用两个停止位,PARENB 表示偶校验
/* 设置波特率 */
if ((termios_state = cfsetispeed(&uart_config, speed)) < 0) {
warnx("ERR: %d (cfsetispeed)\n", termios_state);
return false;
}
if ((termios_state = cfsetospeed(&uart_config, speed)) < 0) {
warnx("ERR: %d (cfsetospeed)\n", termios_state);
return false;
}
// 设置与终端相关的参数,TCSANOW 立即改变参数
if ((termios_state = tcsetattr(fd, TCSANOW, &uart_config)) < 0) {
warnx("ERR: %d (tcsetattr)\n", termios_state);
return false;
}
return true;
}
int uart_init(char * uart_name)
{
int serial_fd = open(uart_name, O_RDWR | O_NOCTTY);
/*Linux中,万物皆文件,打开串口设备和打开普通文件一样,使用的是open()系统调用*/
// 选项 O_NOCTTY 表示不能把本串口当成控制终端,否则用户的键盘输入信息将影响程序的执行
if (serial_fd < 0) {
err(1, "failed to open port: %s", uart_name);
return false;
}
// printf("Open the %s\n",serial_fd);
return serial_fd;
}
float vel_estimate(float cur_pos)
{
float cur_t = (float)(hrt_absolute_time() * 1e-6);
float delt_t = cur_t - last_t;
float cur_vel_est = 0.0f;
float orig_vel = (cur_pos - last_pos) / delt_t;
if((orig_vel - last_vel) / delt_t > 10.0f)
{
cur_vel_est = last_vel;
}
else
{
/** filter **/
cur_vel_est = (filt_var[0] + filt_var[1] + filt_var[2] + filt_var[3] + orig_vel) / 5.0f;
filt_var[0] = filt_var[1];
filt_var[1] = filt_var[2];
filt_var[2] = filt_var[3];
filt_var[3] = orig_vel;
last_t = cur_t;
last_vel = cur_vel_est;
last_pos = cur_pos;
}
return cur_vel_est;
}
void get_att(int att_sub)
{
/* check if there is a new setpoint */
bool updated;
orb_check(att_sub, &updated);
vehicle_attitude_s v_att;
if (updated) {
orb_copy(ORB_ID(vehicle_attitude), att_sub, &v_att);
}
_euler = matrix::Quatf(v_att.q);
}
int rw_uart_main(int argc, char *argv[])
{
float cutoff_freq_pos = 20.0f;
float cutoff_freq_vel = 20.0f;
float sample_rate = SAMP_RATE;
// define and initialize data structure*/
struct pm3901_with_tof_s pm3901_tof_data;
memset(&pm3901_tof_data, 0, sizeof(pm3901_tof_data));
// initialize the orb topic
orb_advert_t pub_fd = orb_advertise(ORB_ID(pm3901_with_tof), &pm3901_tof_data);
struct pm3901_with_tof_s test;
int pm3901_and_tof_sub = orb_subscribe(ORB_ID(pm3901_with_tof));
int att_sub = orb_subscribe(ORB_ID(vehicle_attitude));
/* advertise debug vect */
struct debug_vect_s dbg_vect = {};
strncpy(dbg_vect.name, "tof3D", 10);
dbg_vect.x = 0.0f;
dbg_vect.y = 0.0f;
dbg_vect.z = 0.0f;
orb_advert_t pub_dbg_vect = orb_advertise(ORB_ID(debug_vect), &dbg_vect);
char data = '0';
char buffer[6] = "";
/*
GPS1:/dev/ttyS0
TEL1:/dev/ttyS1
TEL2:/dev/ttyS2
TEL4:/dev/ttyS3
*/
char *uart_name = (char*)"/dev/ttyS3";
int uart_read = uart_init(uart_name);
if(false == uart_read)
return -1;
if(false == set_uart_baudrate(uart_read,9600)){ //38400 for pm3901_and_tof
printf("[JXF]set_uart_baudrate is failed\n");
return -1;
}
mavlink_log_critical(&mavlink_log_pub, "pm3901_with_tof start successful");
//printf("[JXF]uart init is successful\n");
/* wakeup source */
px4_pollfd_struct_t fds[1];
/* Setup of loop */
fds[0].fd = att_sub;
fds[0].events = POLLIN;
int error_counter = 0;
while(true){
/* wait for sensor update of 1 file descriptor for 1000 ms (1 second) */
int poll_ret = px4_poll(&fds[0], (sizeof(fds) / sizeof(fds[0])), 10);
/* handle the poll result */
if (poll_ret == 0) {
orb_publish(ORB_ID(pm3901_with_tof), pub_fd, &pm3901_tof_data);
/* this means none of our providers is giving us data */
PX4_ERR("Got no data within a second");
} else if (poll_ret < 0) {
/* this is seriously bad - should be an emergency */
if (error_counter < 10 || error_counter % 50 == 0) {
/* use a counter to prevent flooding (and slowing us down) */
PX4_ERR("ERROR return value from poll(): %d", poll_ret);
}
error_counter++;
} else {
/** read uart data from sensor **/
read(uart_read, &data,1);
if(data == 0x5a) {//if(data == 0xaa) {
for(int j = 0; j < 6; j ++) {
read(uart_read, &data, 1);
buffer[j] = data;
data = '0';
}
}
if (fds[0].revents & POLLIN) {
/** initialize the filter **/
if(_sample_num == 0)
{
_sample_t = (float)(hrt_absolute_time() * 1e-6);
}
else if(_sample_num <= 100)
{
sample_rate = _sample_num / ((float)(hrt_absolute_time() * 1e-6) - _sample_t);
pos_filter.set_cutoff_frequency(sample_rate, cutoff_freq_pos);
vel_filter.set_cutoff_frequency(sample_rate, cutoff_freq_vel);
}
_sample_num ++;
if(_sample_num > 100)
{
/** decode the original data **/
#if 0
char xvel = buffer[1];
char yvel = - buffer[2];
char quality = buffer[3];
float height = (buffer[4] + (buffer[5]<<8))/1000.f;
#endif
char xvel = buffer[0];
char yvel = - buffer[1];
char quality = buffer[2];
float height = ((buffer[3] << 8) + buffer[4])/1000.f;
if(height < 4.0f)
{
pm3901_tof_data.xvel = xvel;
pm3901_tof_data.yvel = yvel;
pm3901_tof_data.quality = quality;
get_att(att_sub);
pm3901_tof_data.tof_pos = height;
pm3901_tof_data.tof_pos_calib = height * cosf(_euler.phi());//pos_filter.apply(height * cosf(_euler.phi()));
/** estimate the lineat velocity **/
pm3901_tof_data.tof_vel = vel_estimate(pm3901_tof_data.tof_pos_calib);
/** calibrate and filter the tof data **/
pm3901_tof_data.tof_vel_calib = pm3901_tof_data.tof_vel * (-1.0f);//vel_filter.apply(pm3901_tof_data.tof_vel * cosf(_euler.phi())) * (-1.0f);//positive: toward wall
dbg_vect.x = pm3901_tof_data.tof_pos;
dbg_vect.y = pm3901_tof_data.tof_pos_calib;
dbg_vect.z = pm3901_tof_data.tof_vel_calib;
dbg_vect.timestamp = hrt_absolute_time();
}
}
orb_publish(ORB_ID(debug_vect), pub_dbg_vect, &dbg_vect);
orb_publish(ORB_ID(pm3901_with_tof), pub_fd, &pm3901_tof_data);
// Display the original height data
static int count = 0; count ++;
if(count % 100 == 0)
{
printf("tof_sample_rate: %.6f, roll: %.6f\n", (double)(sample_rate), (double)(_euler.phi()));
printf("xvel: %d yvel: %d quality: %d height: %.6f\n", pm3901_tof_data.xvel, pm3901_tof_data.yvel, pm3901_tof_data.quality, (double)(pm3901_tof_data.tof_pos));
orb_copy(ORB_ID(pm3901_with_tof), pm3901_and_tof_sub, &test);
printf("check: xvel: %d yvel: %d quality: %d height: %.6f\n", test.xvel, test.yvel, test.quality, (double)(test.tof_pos));
}
}
}
}
PX4_INFO("exiting");
return 0;
}
| 32.149533
| 188
| 0.567733
|
yihangHKU
|
412c384ed1e2550d7af1b4696d2d61601be4d35d
| 8,549
|
cpp
|
C++
|
src/CourseUtil.cpp
|
turion64guy/PSPMania
|
ce837dca954c76fa7188552ade88becf243899bc
|
[
"Info-ZIP"
] | 9
|
2015-06-10T21:46:09.000Z
|
2021-04-22T20:47:31.000Z
|
src/CourseUtil.cpp
|
turion64guy/PSPMania
|
ce837dca954c76fa7188552ade88becf243899bc
|
[
"Info-ZIP"
] | null | null | null |
src/CourseUtil.cpp
|
turion64guy/PSPMania
|
ce837dca954c76fa7188552ade88becf243899bc
|
[
"Info-ZIP"
] | 5
|
2016-06-24T12:06:12.000Z
|
2021-08-14T17:33:28.000Z
|
#include "global.h"
#include "CourseUtil.h"
#include "Course.h"
#include "RageTimer.h"
#include "ProfileManager.h"
#include "SongManager.h"
#include "XmlFile.h"
#include "GameState.h"
#include "Style.h"
//
// Sorting stuff
//
static bool CompareCoursePointersByName(const Course* pCourse1, const Course* pCourse2)
{
// HACK: strcmp and other string comparators appear to eat whitespace.
// For example, the string "Players Best 13-16" is sorted between
// "Players Best 1-4" and "Players Best 5-8". Replace the string " "
// with " 0" for comparison only.
// XXX: That doesn't happen to me, and it shouldn't (strcmp is strictly
// a byte sort, though CompareNoCase doesn't use strcmp). Are you sure
// you didn't have only one space before? -glenn
CString sName1 = pCourse1->GetFullDisplayTitle();
CString sName2 = pCourse2->GetFullDisplayTitle();
sName1.Replace( " " , " 0" );
sName2.Replace( " " , " 0" );
return sName1.CompareNoCase( sName2 ) == -1;
}
static bool CompareCoursePointersByAutogen(const Course* pCourse1, const Course* pCourse2)
{
int b1 = pCourse1->m_bIsAutogen;
int b2 = pCourse2->m_bIsAutogen;
if( b1 < b2 )
return true;
else if( b1 > b2 )
return false;
else
return CompareCoursePointersByName(pCourse1,pCourse2);
}
static bool CompareCoursePointersByDifficulty(const Course* pCourse1, const Course* pCourse2)
{
int iNum1 = pCourse1->GetEstimatedNumStages();
int iNum2 = pCourse2->GetEstimatedNumStages();
if( iNum1 < iNum2 )
return true;
else if( iNum1 > iNum2 )
return false;
else // iNum1 == iNum2
return CompareCoursePointersByAutogen( pCourse1, pCourse2 );
}
static bool CompareCoursePointersByTotalDifficulty(const Course* pCourse1, const Course* pCourse2)
{
int iNum1 = pCourse1->m_SortOrder_TotalDifficulty;
int iNum2 = pCourse2->m_SortOrder_TotalDifficulty;
if( iNum1 == iNum2 )
return CompareCoursePointersByAutogen( pCourse1, pCourse2 );
return iNum1 < iNum2;
}
static bool MovePlayersBestToEnd( const Course* pCourse1, const Course* pCourse2 )
{
bool C1HasBest = pCourse1->CourseHasBestOrWorst();
bool C2HasBest = pCourse2->CourseHasBestOrWorst();
if( !C1HasBest && !C2HasBest )
return false;
if( C1HasBest && !C2HasBest )
return false;
if( !C1HasBest && C2HasBest )
return true;
return CompareCoursePointersByName( pCourse1, pCourse2 );
}
static bool CompareRandom( const Course* pCourse1, const Course* pCourse2 )
{
return ( pCourse1->IsFixed() && !pCourse2->IsFixed() );
}
static bool CompareCoursePointersByRanking(const Course* pCourse1, const Course* pCourse2)
{
int iNum1 = pCourse1->m_SortOrder_Ranking;
int iNum2 = pCourse2->m_SortOrder_Ranking;
if( iNum1 == iNum2 )
return CompareCoursePointersByAutogen( pCourse1, pCourse2 );
return iNum1 < iNum2;
}
void CourseUtil::SortCoursePointerArrayByDifficulty( vector<Course*> &apCourses )
{
sort( apCourses.begin(), apCourses.end(), CompareCoursePointersByDifficulty );
}
void CourseUtil::SortCoursePointerArrayByRanking( vector<Course*> &apCourses )
{
StepsType st = GAMESTATE->GetCurrentStyle()->m_StepsType;
for(unsigned i=0; i<apCourses.size(); i++)
apCourses[i]->UpdateCourseStats( st );
sort( apCourses.begin(), apCourses.end(), CompareCoursePointersByRanking );
}
void CourseUtil::SortCoursePointerArrayByTotalDifficulty( vector<Course*> &apCourses )
{
StepsType st = GAMESTATE->GetCurrentStyle()->m_StepsType;
for(unsigned i=0; i<apCourses.size(); i++)
apCourses[i]->UpdateCourseStats( st );
sort( apCourses.begin(), apCourses.end(), CompareCoursePointersByTotalDifficulty );
}
static bool CompareCoursePointersByType(const Course* pCourse1, const Course* pCourse2)
{
return pCourse1->GetPlayMode() < pCourse2->GetPlayMode();
}
void CourseUtil::SortCoursePointerArrayByType( vector<Course*> &apCourses )
{
stable_sort( apCourses.begin(), apCourses.end(), CompareCoursePointersByType );
}
void CourseUtil::MoveRandomToEnd( vector<Course*> &apCourses )
{
stable_sort( apCourses.begin(), apCourses.end(), CompareRandom );
}
static map<const Course*, float> course_sort_val;
bool CompareCoursePointersBySortValueAscending(const Course *pSong1, const Course *pSong2)
{
return course_sort_val[pSong1] < course_sort_val[pSong2];
}
bool CompareCoursePointersBySortValueDescending(const Course *pSong1, const Course *pSong2)
{
return course_sort_val[pSong1] > course_sort_val[pSong2];
}
bool CompareCoursePointersByTitle( const Course *pCourse1, const Course *pCourse2 )
{
return CompareCoursePointersByName( pCourse1, pCourse2 );
}
void CourseUtil::SortCoursePointerArrayByAvgDifficulty( vector<Course*> &apCourses )
{
// RageTimer foo;
course_sort_val.clear();
StepsType st = GAMESTATE->GetCurrentStyle()->m_StepsType;
for(unsigned i = 0; i < apCourses.size(); ++i)
{
const Trail* pTrail = apCourses[i]->GetTrail( st );
course_sort_val[apCourses[i]] = pTrail != NULL? (float) pTrail->GetMeter(): 0.0f;
}
sort( apCourses.begin(), apCourses.end(), CompareCoursePointersByTitle );
stable_sort( apCourses.begin(), apCourses.end(), CompareCoursePointersBySortValueAscending );
stable_sort( apCourses.begin(), apCourses.end(), MovePlayersBestToEnd );
}
void CourseUtil::SortCoursePointerArrayByNumPlays( vector<Course*> &arrayCoursePointers, ProfileSlot slot, bool bDescending )
{
Profile* pProfile = PROFILEMAN->GetProfile(slot);
if( pProfile == NULL )
return; // nothing to do since we don't have data
SortCoursePointerArrayByNumPlays( arrayCoursePointers, pProfile, bDescending );
}
void CourseUtil::SortCoursePointerArrayByNumPlays( vector<Course*> &arrayCoursePointers, const Profile* pProfile, bool bDescending )
{
ASSERT( pProfile );
for(unsigned i = 0; i < arrayCoursePointers.size(); ++i)
course_sort_val[arrayCoursePointers[i]] = (float) pProfile->GetCourseNumTimesPlayed(arrayCoursePointers[i]);
stable_sort( arrayCoursePointers.begin(), arrayCoursePointers.end(), bDescending ? CompareCoursePointersBySortValueDescending : CompareCoursePointersBySortValueAscending );
course_sort_val.clear();
}
void CourseID::FromCourse( const Course *p )
{
if( p )
{
if( p->m_bIsAutogen )
{
sPath = "";
sFullTitle = p->GetFullTranslitTitle();
}
else
{
sPath = p->m_sPath;
sFullTitle = "";
}
}
else
{
sPath = "";
sFullTitle = "";
}
}
Course *CourseID::ToCourse() const
{
if( !sPath.empty() )
{
Course *pCourse = SONGMAN->GetCourseFromPath( sPath );
if( pCourse )
return pCourse;
}
if( !sFullTitle.empty() )
{
Course *pCourse = SONGMAN->GetCourseFromName( sFullTitle );
if( pCourse )
return pCourse;
}
return NULL;
}
XNode* CourseID::CreateNode() const
{
XNode* pNode = new XNode;
pNode->name = "Course";
if( !sPath.empty() )
pNode->AppendAttr( "Path", sPath );
if( !sFullTitle.empty() )
pNode->AppendAttr( "FullTitle", sFullTitle );
return pNode;
}
void CourseID::LoadFromNode( const XNode* pNode )
{
ASSERT( pNode->name == "Course" );
pNode->GetAttrValue("Path", sPath);
pNode->GetAttrValue("FullTitle", sFullTitle);
}
CString CourseID::ToString() const
{
if( !sPath.empty() )
return sPath;
if( !sFullTitle.empty() )
return sFullTitle;
return "";
}
bool CourseID::IsValid() const
{
return !sPath.empty() || !sFullTitle.empty();
}
/*
* (c) 2001-2004 Chris Danford
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 30.423488
| 173
| 0.740554
|
turion64guy
|
4135be1ac2368d429c59ae065be880bfb9da5919
| 1,469
|
cpp
|
C++
|
HolographicJS/Console.cpp
|
lwansbrough/HolographicJS
|
8e71dd890e587929e46fba25c9dcaa72748ba73f
|
[
"Apache-2.0"
] | 120
|
2016-09-02T23:52:06.000Z
|
2020-02-27T05:25:53.000Z
|
HolographicJS/Console.cpp
|
lwansbrough/HolographicJS
|
8e71dd890e587929e46fba25c9dcaa72748ba73f
|
[
"Apache-2.0"
] | 3
|
2016-10-15T01:18:03.000Z
|
2017-02-20T21:28:16.000Z
|
HolographicJS/Console.cpp
|
lwansbrough/HolographicJS
|
8e71dd890e587929e46fba25c9dcaa72748ba73f
|
[
"Apache-2.0"
] | 7
|
2016-10-16T16:21:36.000Z
|
2019-09-26T07:51:44.000Z
|
#include "pch.h"
#include "Console.h"
#include "Binding.h"
#include <assert.h>
Console::Console()
{
}
JsValueRef Console::prototype;
JsValueRef CALLBACK Console::constructor(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
assert(isConstructCall);
JsValueRef output = JS_INVALID_REFERENCE;
Console* console = new Console();
JsCreateExternalObject(console, nullptr, &output);
JsSetPrototype(output, Console::prototype);
return output;
}
std::map<const wchar_t *, JsNativeFunction> Console::getMembers() {
std::map<const wchar_t *, JsNativeFunction> members;
members.insert({ L"log", log });
members.insert({ L"error", log });
members.insert({ L"info", log });
members.insert({ L"warn", log });
return members;
}
std::map<const wchar_t *, JsValueRef> Console::getProperties() {
std::map<const wchar_t *, JsValueRef> properties;
return properties;
}
JsValueRef CALLBACK Console::log(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) {
std::string entry;
for (int i = 1; i < argumentCount; i++) {
if (i > 1)
{
OutputDebugString(L" ");
}
JsValueRef stringValue;
JsConvertValueToString(arguments[i], &stringValue);
const wchar_t *string;
size_t length;
JsStringToPointer(stringValue, &string, &length);
OutputDebugString(string);
}
OutputDebugString(L"\r\n");
return JS_INVALID_REFERENCE;
}
| 25.77193
| 155
| 0.733152
|
lwansbrough
|
41397016e849101524e0069b27678cb78c6a0b83
| 816
|
hpp
|
C++
|
include/usagi/concepts/tuple/distinct.hpp
|
SachiSakurane/usagi
|
952a07d87ead0c7b5839648d0bde54213effde09
|
[
"BSL-1.0"
] | 1
|
2021-07-24T17:45:16.000Z
|
2021-07-24T17:45:16.000Z
|
include/usagi/concepts/tuple/distinct.hpp
|
SachiSakurane/usagi
|
952a07d87ead0c7b5839648d0bde54213effde09
|
[
"BSL-1.0"
] | 11
|
2021-11-09T06:38:47.000Z
|
2021-11-27T15:56:23.000Z
|
include/usagi/concepts/tuple/distinct.hpp
|
SachiSakurane/usagi
|
952a07d87ead0c7b5839648d0bde54213effde09
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <tuple>
#include <utility>
#include <usagi/tuple/erase.hpp>
#include <usagi/tuple/front.hpp>
#include <usagi/tuple/has.hpp>
namespace usagi::concepts::tuple {
namespace detail {
template <class TupleType, size_t Size = std::tuple_size_v<TupleType>>
class distinct_impl {
using target = usagi::tuple::front_t<TupleType>;
using sub_tuple = usagi::tuple::erase_front_t<TupleType>;
public:
static constexpr bool value =
!usagi::tuple::has<target, sub_tuple>::value && distinct_impl<sub_tuple>::value;
};
template <class TupleType>
struct distinct_impl<TupleType, 0> {
static constexpr bool value = true;
};
} // namespace detail
template <class TupleType>
concept distinct = detail::distinct_impl<TupleType>::value;
} // namespace usagi::concepts::tuple
| 26.322581
| 88
| 0.721814
|
SachiSakurane
|
413a23a5f2afa082e8d33c1c2c782771e470330f
| 1,148
|
cpp
|
C++
|
SiftEC/src/util/serializable_address_value_pair.cpp
|
zdx-alex/Sift
|
68647aebb1db23d879ca67e5e9cd54fda1f833d7
|
[
"Apache-2.0"
] | 3
|
2020-04-20T20:12:01.000Z
|
2021-12-07T03:39:09.000Z
|
SiftEC/src/util/serializable_address_value_pair.cpp
|
zdx-alex/Sift
|
68647aebb1db23d879ca67e5e9cd54fda1f833d7
|
[
"Apache-2.0"
] | null | null | null |
SiftEC/src/util/serializable_address_value_pair.cpp
|
zdx-alex/Sift
|
68647aebb1db23d879ca67e5e9cd54fda1f833d7
|
[
"Apache-2.0"
] | 3
|
2020-11-15T01:23:23.000Z
|
2021-03-01T06:51:55.000Z
|
#include "include/util/serializable_address_value_pair.h"
#include <cstring>
#include <assert.h>
SerializableAVPair::SerializableAVPair() {}
SerializableAVPair::~SerializableAVPair() {}
char* SerializableAVPair::serialize() {
char* frame = new char[sizeof(AVPair)];
memcpy(frame, &value, sizeof(AVPair)); // copy memory and not string
return frame;
}
void SerializableAVPair::deserialize(char *data) {
memcpy(&value, data, sizeof(AVPair));
}
uint64_t SerializableAVPair::getAddress() {
return value.address;
}
void SerializableAVPair::setAddress(uint64_t address) {
value.address = address;
}
char *SerializableAVPair::getValue() {
return value.value;
}
void SerializableAVPair::setValue(const char* new_value, size_t len) {
memcpy(value.value, new_value, RM_MEMORY_BLOCK_SIZE);
}
uint32_t SerializableAVPair::getLogIndex() {
return value.log_index;
}
void SerializableAVPair::setLogIndex(uint32_t log_index) {
value.log_index = log_index;
}
bool SerializableAVPair::equals(SerializableAVPair &sv) {
return value.address == sv.value.address
&& strcmp(value.value, sv.value.value);
}
| 24.956522
| 72
| 0.735192
|
zdx-alex
|
413bb842cc773ed2dff9dab9af6c8ebf39e092a5
| 11,031
|
cc
|
C++
|
src/bitcoin/BitcoinUtils.cc
|
vpashka/btcpool
|
dab18b2bc90b3db2fb30698fc04e7e21a06acd11
|
[
"MIT"
] | null | null | null |
src/bitcoin/BitcoinUtils.cc
|
vpashka/btcpool
|
dab18b2bc90b3db2fb30698fc04e7e21a06acd11
|
[
"MIT"
] | null | null | null |
src/bitcoin/BitcoinUtils.cc
|
vpashka/btcpool
|
dab18b2bc90b3db2fb30698fc04e7e21a06acd11
|
[
"MIT"
] | 1
|
2021-11-05T08:36:28.000Z
|
2021-11-05T08:36:28.000Z
|
/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.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 "BitcoinUtils.h"
#include "Utils.h"
#include "utilities_js.hpp"
#include <streams.h>
std::string EncodeHexBlock(const CBlock &block) {
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
return HexStr(ssBlock.begin(), ssBlock.end());
}
std::string EncodeHexBlockHeader(const CBlockHeader &blkHeader) {
CDataStream ssBlkHeader(SER_NETWORK, PROTOCOL_VERSION);
ssBlkHeader << blkHeader;
return HexStr(ssBlkHeader.begin(), ssBlkHeader.end());
}
#ifdef CHAIN_TYPE_BCH
/**
* This implements a constant-space merkle root/path calculator, limited to 2^32
* leaves.
*/
static void MerkleComputation(
const std::vector<uint256> &leaves,
uint256 *proot,
bool *pmutated,
uint32_t branchpos,
std::vector<uint256> *pbranch) {
if (pbranch)
pbranch->clear();
if (leaves.size() == 0) {
if (pmutated)
*pmutated = false;
if (proot)
*proot = uint256();
return;
}
bool mutated = false;
// count is the number of leaves processed so far.
uint32_t count = 0;
// inner is an array of eagerly computed subtree hashes, indexed by tree
// level (0 being the leaves).
// For example, when count is 25 (11001 in binary), inner[4] is the hash of
// the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to
// the last leaf. The other inner entries are undefined.
uint256 inner[32];
// Which position in inner is a hash that depends on the matching leaf.
int matchlevel = -1;
// First process all leaves into 'inner' values.
while (count < leaves.size()) {
uint256 h = leaves[count];
bool matchh = count == branchpos;
count++;
int level;
// For each of the lower bits in count that are 0, do 1 step. Each
// corresponds to an inner value that existed before processing the
// current leaf, and each needs a hash to combine it.
for (level = 0; !(count & (((uint32_t)1) << level)); level++) {
if (pbranch) {
if (matchh) {
pbranch->push_back(inner[level]);
} else if (matchlevel == level) {
pbranch->push_back(h);
matchh = true;
}
}
mutated |= (inner[level] == h);
CHash256()
.Write(inner[level].begin(), 32)
.Write(h.begin(), 32)
.Finalize(h.begin());
}
// Store the resulting hash at inner position level.
inner[level] = h;
if (matchh) {
matchlevel = level;
}
}
// Do a final 'sweep' over the rightmost branch of the tree to process
// odd levels, and reduce everything to a single top value.
// Level is the level (counted from the bottom) up to which we've sweeped.
int level = 0;
// As long as bit number level in count is zero, skip it. It means there
// is nothing left at this level.
while (!(count & (((uint32_t)1) << level))) {
level++;
}
uint256 h = inner[level];
bool matchh = matchlevel == level;
while (count != (((uint32_t)1) << level)) {
// If we reach this point, h is an inner value that is not the top.
// We combine it with itself (Bitcoin's special rule for odd levels in
// the tree) to produce a higher level one.
if (pbranch && matchh) {
pbranch->push_back(h);
}
CHash256().Write(h.begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
// Increment count to the value it would have if two entries at this
// level had existed.
count += (((uint32_t)1) << level);
level++;
// And propagate the result upwards accordingly.
while (!(count & (((uint32_t)1) << level))) {
if (pbranch) {
if (matchh) {
pbranch->push_back(inner[level]);
} else if (matchlevel == level) {
pbranch->push_back(h);
matchh = true;
}
}
CHash256()
.Write(inner[level].begin(), 32)
.Write(h.begin(), 32)
.Finalize(h.begin());
level++;
}
}
// Return result.
if (pmutated)
*pmutated = mutated;
if (proot)
*proot = h;
}
std::vector<uint256>
ComputeMerkleBranch(const std::vector<uint256> &leaves, uint32_t position) {
std::vector<uint256> ret;
MerkleComputation(leaves, nullptr, nullptr, position, &ret);
return ret;
}
std::vector<uint256> BlockMerkleBranch(const CBlock &block, uint32_t position) {
std::vector<uint256> leaves;
leaves.resize(block.vtx.size());
for (size_t s = 0; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetHash();
}
return ComputeMerkleBranch(leaves, position);
}
#endif
#ifndef CHAIN_TYPE_UBTC
/////////////////////// Block Reward of BTC, BCH, SBTC ///////////////////////
int64_t GetBlockReward(int nHeight, const Consensus::Params &consensusParams) {
int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
// Force block reward to zero when right shift is undefined.
if (halvings >= 64)
return 0;
int64_t nSubsidy = 50 * COIN_TO_SATOSHIS;
// Block reward is cut in half every 210,000 blocks which will occur
// approximately every 4 years.
nSubsidy >>=
halvings; // this line is secure, it copied from bitcoin's validation.cpp
return nSubsidy;
}
#else
/////////////////////// Block Reward of UBTC ///////////////////////
// copied from UnitedBitcoin-v1.1.0.0
int64_t GetBlockReward(int nHeight, const Consensus::Params &consensusParams) {
int halvings;
if (nHeight < Params().GetConsensus().ForkV1Height) {
halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
// Force block reward to zero when right shift is undefined.
if (halvings >= 64)
return 0;
int64_t nSubsidy = 50 * COIN_TO_SATOSHIS;
// Subsidy is cut in half every 210,000 blocks which will occur
// approximately every 4 years.
nSubsidy >>= halvings;
return nSubsidy;
} else {
int halfPeriodLeft = consensusParams.ForkV1Height - 1 -
consensusParams.nSubsidyHalvingInterval * 2;
int halfPeriodRight =
(consensusParams.nSubsidyHalvingInterval - halfPeriodLeft) * 10;
int PeriodEndHeight = consensusParams.ForkV1Height - 1 +
(consensusParams.nSubsidyHalvingInterval - halfPeriodLeft) * 10;
if (nHeight <= PeriodEndHeight)
halvings = 2;
else {
halvings = 3 +
(nHeight - PeriodEndHeight - 1) /
(consensusParams.nSubsidyHalvingInterval * 10);
}
// Force block reward to zero when right shift is undefined.
if (halvings >= 64)
return 0;
int64_t nSubsidy = 50 * COIN_TO_SATOSHIS;
// Subsidy is cut in half every 210,000 blocks which will occur
// approximately every 4 years.
nSubsidy >>= halvings;
nSubsidy = nSubsidy / 10 * 0.8;
return nSubsidy;
}
}
#endif
#ifdef CHAIN_TYPE_SBTC
namespace BitcoinUtils {
CTxDestination DecodeDestination(const std::string &str) {
CBitcoinAddress addr(str);
return addr.Get();
}
bool IsValidDestinationString(const std::string &str) {
CBitcoinAddress addr(str);
return addr.IsValid();
}
} // namespace BitcoinUtils
#endif // CHAIN_TYPE_SBTC
static bool checkBitcoinRPCGetNetworkInfo(
const string &rpcAddr, const string &rpcUserpass) {
string response;
string request =
"{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getnetworkinfo\","
"\"params\":[]}";
bool res = blockchainNodeRpcCall(
rpcAddr.c_str(), rpcUserpass.c_str(), request.c_str(), response);
if (!res) {
LOG(ERROR) << "rpc getnetworkinfo call failure";
return false;
}
LOG(INFO) << "getnetworkinfo: " << response;
JsonNode r;
if (!JsonNode::parse(
response.c_str(), response.c_str() + response.length(), r)) {
LOG(ERROR) << "decode getnetworkinfo failure";
return false;
}
// check fields & connections
if (r["result"].type() != Utilities::JS::type::Obj ||
r["result"]["connections"].type() != Utilities::JS::type::Int) {
LOG(ERROR) << "getnetworkinfo missing some fields";
return false;
}
if (r["result"]["connections"].int32() <= 0) {
LOG(ERROR) << "node connections is zero";
return false;
}
return true;
}
static bool
checkBitcoinRPCGetInfo(const string &rpcAddr, const string &rpcUserpass) {
string response;
string request =
"{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getinfo\",\"params\":[]}";
bool res = blockchainNodeRpcCall(
rpcAddr.c_str(), rpcUserpass.c_str(), request.c_str(), response);
if (!res) {
LOG(ERROR) << "rpc getinfo call failure";
return false;
}
LOG(INFO) << "getinfo: " << response;
JsonNode r;
if (!JsonNode::parse(
response.c_str(), response.c_str() + response.length(), r)) {
LOG(ERROR) << "decode getinfo failure";
return false;
}
// check fields & connections
if (r["result"].type() != Utilities::JS::type::Obj ||
r["result"]["connections"].type() != Utilities::JS::type::Int) {
LOG(ERROR) << "getinfo missing some fields";
return false;
}
if (r["result"]["connections"].int32() <= 0) {
LOG(ERROR) << "node connections is zero";
return false;
}
return true;
}
bool checkBitcoinRPC(const string &rpcAddr, const string &rpcUserpass) {
return checkBitcoinRPCGetNetworkInfo(rpcAddr, rpcUserpass) ||
checkBitcoinRPCGetInfo(rpcAddr, rpcUserpass);
}
int32_t getBlockHeightFromCoinbase(const string &coinbase1) {
// https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki
const string sizeStr = coinbase1.substr(84, 2);
auto size = (int32_t)strtol(sizeStr.c_str(), nullptr, 16);
// see CScript::push_int64 for the logic
if (size == OP_0)
return 0;
if (size >= OP_1 && size <= OP_1 + 16)
return size - (OP_1 - 1);
string heightHex;
for (int i = 0; i < size; ++i) {
heightHex = coinbase1.substr(86 + (i * 2), 2) + heightHex;
}
DLOG(INFO) << "getBlockHeightFromCoinbase coinbase: " << coinbase1;
DLOG(INFO) << "getBlockHeightFromCoinbase heightHex: " << heightHex;
return (int32_t)strtol(heightHex.c_str(), nullptr, 16);
}
| 31.60745
| 80
| 0.654519
|
vpashka
|
413eb05fc0d7d0e96a1b86e7b5bceb90e3b3f079
| 4,666
|
cpp
|
C++
|
modules/filters/src/smoothing/average.cpp
|
voxel-dot-at/toffy
|
e9f14b186cf57225ad9eae99f227f894f0e5f940
|
[
"Apache-2.0"
] | null | null | null |
modules/filters/src/smoothing/average.cpp
|
voxel-dot-at/toffy
|
e9f14b186cf57225ad9eae99f227f894f0e5f940
|
[
"Apache-2.0"
] | null | null | null |
modules/filters/src/smoothing/average.cpp
|
voxel-dot-at/toffy
|
e9f14b186cf57225ad9eae99f227f894f0e5f940
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2018 Simon Vogl <svogl@voxel.at>
Angel Merino-Sastre <amerino@voxel.at>
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 <iostream>
#include <boost/log/trivial.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include "toffy/smoothing/average.hpp"
using namespace toffy;
using namespace toffy::filters::smoothing;
using namespace cv;
using namespace std;
namespace logging = boost::log;
#ifdef CM_DEBUG
const bool dbg=true;
#else
const bool dbg=false;
#endif
std::size_t Average::_filter_counter = 1;
const std::string Average::id_name = "average";
Average::Average() :Filter(Average::id_name,_filter_counter),
_in_img("depth"),
_out_img("depth"),
_size(10)
{
_filter_counter++;
}
bool Average::filter(const Frame &in, Frame& out)
{
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << " " << id();
boost::shared_ptr<cv::Mat> img;
boost::shared_ptr<cv::Mat> new_img;
try {
img = boost::any_cast<boost::shared_ptr<cv::Mat> >(in.getData(_in_img));
} catch(const boost::bad_any_cast &) {
BOOST_LOG_TRIVIAL(warning) <<
"Could not cast input " << _in_img <<
", filter " << id() <<" not applied.";
return false;
}
try {
if (in.hasKey(_out_img))
new_img = boost::any_cast<boost::shared_ptr<cv::Mat> >(in.getData(_out_img));
else
new_img.reset(new Mat());
} catch(const boost::bad_any_cast &) {
BOOST_LOG_TRIVIAL(warning) <<
"Could not cast output " << _in_img <<
", filter " << id() <<" not applied.";
return false;
}
//bilateralFilter(*depth, *bi, d, sigmaColor, sigmaSpace, BORDER_REPLICATE);
boost::shared_ptr<cv::Mat> imgadd;
if (_queue.size() == _size) {
BOOST_LOG_TRIVIAL(debug) << "queue FULL";
imgadd = _queue.front();
_queue.pop_front();
img->copyTo(*imgadd);
_queue.push_back(imgadd);
} else {
BOOST_LOG_TRIVIAL(debug) << "Filling queue";
imgadd.reset( new Mat(img->clone()));
_queue.push_back(imgadd);
BOOST_LOG_TRIVIAL(debug) << _queue.size();
}
if (img->type() != _dst.type() || img->size() != _dst.size()) {
_dst.release();
_dst = Mat(img->size(), img->type());
}
if (img->size() != _cnt.size()) {
_cnt.release();
_cnt = Mat(img->size(), CV_32S);
}
_dst = Scalar::all(0.0);
_cnt = Scalar::all(0);
//int count[size];
//memset(count, 0, sizeof count);
float* src;
float* dst;
int* cnt;
for (size_t i=0; i < _queue.size(); i++) {
for(int row = 0; row < _queue[i]->rows; ++row) {
src = _queue[i]->ptr<float>(row);
dst = _dst.ptr<float>(row);
cnt = _cnt.ptr<int>(row);
for(int col = 0; col < _queue[i]->cols; ++col) {
if (src[col] > 0.0) {
dst [col] += src[col];
cnt[col]++;
}
}
}
}
for(int row = 0; row < _dst.rows; ++row) {
dst = _dst.ptr<float>(row);
cnt = _cnt.ptr<int>(row);
for(int col = 0; col < _dst.cols; ++col) {
if (cnt[col] != 0)
dst [col] /= cnt[col];
}
}
*new_img = _dst.clone();
/**new_img = _queue[0]->clone();
for (size_t i=1; i < _queue.size(); i++)
*new_img += *_queue[i];
BOOST_LOG_TRIVIAL(debug) << "averaging over: " <<_queue.size();
*new_img /= _queue.size();*/
out.addData(_out_img, new_img);
//cout << id() << " wrote to " << _out_img << endl;
return true;
}
/*
int Average::loadConfig(const boost::property_tree::ptree& pt)
{
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << " " << id();
//const boost::property_tree::ptree& average = pt.get_child(type());
updateConfig(pt.begin()->second );
return 1;
}
*/
boost::property_tree::ptree Average::getConfig() const
{
boost::property_tree::ptree pt;
pt = Filter::getConfig();
pt.put("options.size", _size);
pt.put("inputs.img", _in_img);
pt.put("outputs.img", _out_img);
return pt;
}
void Average::updateConfig(const boost::property_tree::ptree &pt) {
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << " " << id();
Filter::updateConfig(pt);
_size = pt.get("options.size", _size);
_queue.clear();
_in_img = pt.get("inputs.img", _in_img);
_out_img = pt.get("outputs.img", _out_img);
}
| 24.687831
| 82
| 0.623875
|
voxel-dot-at
|
413f3f27e5c9f76897708e6dc0809a96a106c978
| 696
|
cpp
|
C++
|
Src/EntityStorage.cpp
|
Condzi/Engine
|
10f6acdf33b24b8d0aab9efcec570821a73423a1
|
[
"MIT"
] | 1
|
2018-07-30T10:51:23.000Z
|
2018-07-30T10:51:23.000Z
|
Src/EntityStorage.cpp
|
Condzi/Engine
|
10f6acdf33b24b8d0aab9efcec570821a73423a1
|
[
"MIT"
] | null | null | null |
Src/EntityStorage.cpp
|
Condzi/Engine
|
10f6acdf33b24b8d0aab9efcec570821a73423a1
|
[
"MIT"
] | null | null | null |
/*
Conrad 'Condzi' Kubacki 2018
https://github.com/condzi
*/
#include "Engine/EnginePCH.hpp"
#include "Engine/EntityStorage.hpp"
#include <SFML/System/Clock.hpp>
namespace con::priv
{
void EntityStorage::update()
{
if ( cleanupClock.getElapsedTime() >= CLEANUP_INTERVAL ) {
cleanupClock.restart();
cleanup();
}
}
std::unique_ptr<Entity>& EntityStorage::getFreeSlot()
{
for ( auto& e : entities )
if ( !e )
return e;
print( LogPriority::Warning, "No free slots: has to realloc. (% items)", entities.size() );
return entities.emplace_back();
}
void EntityStorage::cleanup()
{
for ( auto& e : entities )
if ( e && e->getStatus() == Entity::Status::Dead )
e.reset();
}
}
| 17.846154
| 92
| 0.666667
|
Condzi
|
414109480f97f72793bb34a95ce9392a781c0ea8
| 801
|
cpp
|
C++
|
codeforces/cf616 div2/A.cpp
|
songhn233/ACM_Steps
|
6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe
|
[
"CC0-1.0"
] | 1
|
2020-08-10T21:40:21.000Z
|
2020-08-10T21:40:21.000Z
|
codeforces/cf616 div2/A.cpp
|
songhn233/Algorithm-Packages
|
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
|
[
"CC0-1.0"
] | null | null | null |
codeforces/cf616 div2/A.cpp
|
songhn233/Algorithm-Packages
|
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
|
[
"CC0-1.0"
] | null | null | null |
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#define ll long long
#define F(i,a,b) for(int i=(a);i<=(b);i++)
#define mst(a,b) memset((a),(b),sizeof(a))
#define PII pair<int,int>
using namespace std;
template<class T>inline void read(T &x) {
x=0; int ch=getchar(),f=0;
while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
if(f)x=-x;
}
const int inf=0x3f3f3f3f;
int T,n;
string s;
int main()
{
cin>>T;
while(T--)
{
cin>>n>>s;
int a[5],num=0;
for(int i=0;i<n;i++)
{
if((s[i]-'0')%2==1) a[++num]=s[i]-'0';
if(num==2) break;
}
if(num!=2) puts("-1");
else cout<<a[1]<<a[2]<<endl;
}
return 0;
}
| 19.071429
| 67
| 0.566792
|
songhn233
|
41432ebf6921c49b130331274b6bd1d5e211e863
| 8,991
|
cpp
|
C++
|
examples/mgard-x/CompressXgcData/TestXGCAbsoluteError.cpp
|
JieyangChen7/MGARD
|
acec8facae1e2767a3adff2bb3c30f3477e69bdb
|
[
"Apache-2.0"
] | null | null | null |
examples/mgard-x/CompressXgcData/TestXGCAbsoluteError.cpp
|
JieyangChen7/MGARD
|
acec8facae1e2767a3adff2bb3c30f3477e69bdb
|
[
"Apache-2.0"
] | null | null | null |
examples/mgard-x/CompressXgcData/TestXGCAbsoluteError.cpp
|
JieyangChen7/MGARD
|
acec8facae1e2767a3adff2bb3c30f3477e69bdb
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2021, Oak Ridge National Laboratory.
* MGARD-X: MultiGrid Adaptive Reduction of Data Portable across GPUs and CPUs
* Author: Jieyang Chen (chenj3@ornl.gov)
* Date: April 2, 2021
*/
#include <chrono>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <fstream>
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "adios2.h"
#include "mgard/mgard_api.h"
#define ANSI_RED "\x1b[31m"
#define ANSI_GREEN "\x1b[32m"
#define ANSI_RESET "\x1b[0m"
using namespace std::chrono;
void print_usage_message(char *argv[], FILE *fp) {
fprintf(fp,
"Usage: %s [input file] [num. of dimensions] [1st dim.] [2nd dim.] "
"[3rd. dim] ... [tolerance] [s]\n",
argv[0]);
}
int main(int argc, char *argv[]) {
MPI_Init(&argc, &argv);
int rank, np_size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np_size);
// np_size = 150;
/*
int deviceCount;
cudaGetDeviceCount(&deviceCount); // How many GPUs?
int device_id = rank % deviceCount;
cudaSetDevice(device_id);
std::cout << "total number of devices: " << deviceCount << ", rank " <<
rank << " used " << device_id << "\n";
*/
double compress_time = 0.0;
double decompress_time = 0.0;
double gpu_compress_time = 0.0;
double gpu_decompress_time = 0.0;
double in_time = 0.0;
double gpu_in_time = 0.0;
if (argc == 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) {
print_usage_message(argv, stdout);
return 0;
}
char *infile; //, *outfile;
double tol, s = 0;
int i = 1;
infile = argv[i++];
tol = atof(argv[i++]);
s = atof(argv[i++]);
double job_sz = atof(argv[i++]);
if (rank == 0) {
printf("Input data: %s ", infile);
printf("Abs. error bound: %.2e ", tol);
printf("S: %.2f\n", s);
}
adios2::ADIOS ad("", MPI_COMM_WORLD);
adios2::IO reader_io = ad.DeclareIO("XGC");
adios2::Engine reader = reader_io.Open(infile, adios2::Mode::Read);
adios2::IO bpIO = ad.DeclareIO("WriteBP_File");
adios2::Engine writer = bpIO.Open("xgc.mgard.bp", adios2::Mode::Write);
adios2::Variable<double> var_i_f_in;
var_i_f_in = reader_io.InquireVariable<double>("i_f");
if (!var_i_f_in) {
std::cout << "Didn't find i_f...exit\n";
exit(1);
}
size_t vx = var_i_f_in.Shape()[1];
size_t vy = var_i_f_in.Shape()[3];
size_t nnodes = var_i_f_in.Shape()[2];
size_t nphi = var_i_f_in.Shape()[0];
size_t gb_elements = nphi * vx * nnodes * vy;
size_t num_iter =
(size_t)(std::ceil)((double)gb_elements * sizeof(double) / 1024.0 /
1024.0 / 1024.0 / job_sz / np_size);
size_t div_nnodes = (size_t)(std::ceil)((double)nnodes / num_iter);
size_t iter_nnodes =
(size_t)(std::ceil)((double)div_nnodes / (double)np_size);
// size_t iter_elements = iter_nnodes * vx * vy * nphi;
size_t local_nnodes =
(rank == np_size - 1) ? (div_nnodes - rank * iter_nnodes) : iter_nnodes;
size_t local_elements = nphi * vx * local_nnodes * vy;
size_t lSize = sizeof(double) * gb_elements;
double *in_buff;
mgard_x::cudaMallocHostHelper((void **)&in_buff,
sizeof(double) * local_elements);
if (rank == 0) {
std::cout << "total data size: {" << nphi << ", " << vx << ", " << nnodes
<< ", " << vy << "}, number of iters: " << num_iter << "\n";
}
size_t out_size = 0;
for (size_t iter = 0; iter < num_iter; iter++) {
if (iter == num_iter - 1) {
iter_nnodes = (size_t)(std::ceil)(
((double)(nnodes - div_nnodes * iter)) /
(double)np_size); // local_nnodes - iter_nnodes*iter;
local_nnodes =
(rank == np_size - 1)
? (nnodes - div_nnodes * iter - iter_nnodes * (np_size - 1))
: iter_nnodes;
local_elements = local_nnodes * vx * vy * nphi;
}
std::vector<size_t> shape = {nphi, vx, local_nnodes, vy};
std::cout << "rank " << rank << " read from {0, 0, "
<< div_nnodes * iter + iter_nnodes * rank << ", 0} for {" << nphi
<< ", " << vx << ", " << local_nnodes << ", " << vy << "}\n";
var_i_f_in.SetSelection(adios2::Box<adios2::Dims>(
{0, 0, div_nnodes * iter + iter_nnodes * rank, 0},
{nphi, vx, local_nnodes, vy}));
reader.Get<double>(var_i_f_in, in_buff);
reader.PerformGets();
double maxv = 0;
for (size_t i = 0; i < local_elements; i++)
maxv = (maxv > in_buff[i]) ? maxv : in_buff[i];
std::cout << "max element: " << maxv << "\n";
MPI_Barrier(MPI_COMM_WORLD);
double *mgard_out_buff = NULL;
// printf("Start compressing and decompressing with GPU\n");
mgard_x::Array<4, double> in_array(shape);
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
in_time = -MPI_Wtime();
}
in_array.loadData(in_buff);
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
gpu_in_time += (in_time + MPI_Wtime());
}
// std::cout << "loadData: " << shape[0] << ", " << shape[1] << ", "
// << shape[2] << ", " << shape[3] << "\n";
mgard_x::Handle<4, double> handle(shape);
// std::cout << "before compression\n";
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
compress_time = -MPI_Wtime();
}
mgard_x::Array<1, unsigned char> compressed_array =
mgard_x::compress(handle, in_array, mgard_x::ABS, tol, s);
// std::cout << "after compression\n";
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
gpu_compress_time += (compress_time + MPI_Wtime());
}
out_size += compressed_array.getShape()[0];
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
decompress_time = -MPI_Wtime();
}
mgard_x::Array<4, double> out_array =
mgard_x::decompress(handle, compressed_array);
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
gpu_decompress_time += (decompress_time + MPI_Wtime());
}
mgard_out_buff = new double[local_elements];
memcpy(mgard_out_buff, out_array.getDataHost(),
local_elements * sizeof(double));
double error_L_inf_norm = 0;
for (int i = 0; i < local_elements; ++i) {
double temp = fabs(in_buff[i] - mgard_out_buff[i]);
if (temp > error_L_inf_norm)
error_L_inf_norm = temp;
}
double absolute_L_inf_error = error_L_inf_norm;
printf("Abs. L^infty error bound: %10.5E \n", tol);
printf("Abs. L^infty error: %10.5E \n", absolute_L_inf_error);
if (absolute_L_inf_error < tol) {
printf(ANSI_GREEN "SUCCESS: Error tolerance met!" ANSI_RESET "\n");
} else {
printf(ANSI_RED "FAILURE: Error tolerance NOT met!" ANSI_RESET "\n");
return -1;
}
char write_f[2048];
sprintf(write_f, "largeXGC/xgc.mgard.rank%i_%d.bin", rank, iter);
FILE *pFile = fopen(write_f, "wb");
fwrite(mgard_out_buff, sizeof(double), out_size, pFile);
fclose(pFile);
delete mgard_out_buff;
}
if (rank == 0) {
std::cout << " CPU to GPU time: " << gpu_in_time
<< ", compression time: " << gpu_compress_time
<< ", decompress time: " << gpu_decompress_time << "\n";
}
mgard_x::cudaFreeHostHelper(in_buff);
size_t gb_compressed;
MPI_Allreduce(&out_size, &gb_compressed, 1, MPI_UNSIGNED_LONG, MPI_SUM,
MPI_COMM_WORLD);
if (rank == 0) {
printf("In size: %10ld Out size: %10ld Compression ratio: %f \n", lSize,
gb_compressed, (double)lSize / gb_compressed);
}
reader.Close();
// size_t exscan;
// size_t *scan_counts = (size_t *)malloc(np_size * sizeof(size_t));
// MPI_Exscan(&out_size, &exscan, 1, MPI_UNSIGNED_LONG, MPI_SUM,
// MPI_COMM_WORLD); std::cout << "rank " << rank << " compressed size: " <<
// out_size << ", exscan: " << exscan << ", total compressed: " <<
// gb_compressed << "\n"; MPI_Gather(&exscan, 1, MPI_UNSIGNED_LONG,
// scan_counts, 1, MPI_UNSIGNED_LONG, 0, MPI_COMM_WORLD); if (rank == 0) {
// scan_counts[0] = 0;
// exscan = 0;
// std::cout << "scanned counts: ";
// for (int i=0; i<np_size; i ++)
// std::cout << scan_counts[i] << ", ";
// std::cout << "\n";
// }
// unsigned char *mgard_compress_buff = new unsigned char[out_size];
// memcpy(mgard_compress_buff, compressed_array.getDataHost(), out_size);
// adios2::Variable<unsigned char> bp_fdata = bpIO.DefineVariable<unsigned
// char>(
// "mgard_f", {gb_compressed}, {exscan}, {out_size},
// adios2::ConstantDims);
// writer.Put<unsigned char>(bp_fdata, mgard_compress_buff);
// if (rank==0) {
// adios2::Variable<size_t> bp_count = bpIO.DefineVariable<size_t>(
// "block_start", {(size_t)np_size}, {0}, {(size_t)np_size},
// adios2::ConstantDims); writer.Put<size_t>(bp_count, scan_counts);
// }
// writer.Close();
MPI_Finalize();
return 0;
}
| 35.121094
| 80
| 0.592926
|
JieyangChen7
|
41474d27de1e30b6ef540ccf2ffc3a345c748405
| 10,962
|
cpp
|
C++
|
KDIS/DataTypes/LinearSegmentParameter.cpp
|
cdit-ma/kdis
|
f722221cee0e5ea6869f9e923ad1cdb93d5d289f
|
[
"BSD-2-Clause"
] | null | null | null |
KDIS/DataTypes/LinearSegmentParameter.cpp
|
cdit-ma/kdis
|
f722221cee0e5ea6869f9e923ad1cdb93d5d289f
|
[
"BSD-2-Clause"
] | null | null | null |
KDIS/DataTypes/LinearSegmentParameter.cpp
|
cdit-ma/kdis
|
f722221cee0e5ea6869f9e923ad1cdb93d5d289f
|
[
"BSD-2-Clause"
] | null | null | null |
/*********************************************************************
Copyright 2013 Karl Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
For Further Information Please Contact me at
Karljj1@yahoo.com
http://p.sf.net/kdis/UserGuide
*********************************************************************/
#include "./LinearSegmentParameter.h"
using namespace KDIS;
using namespace DATA_TYPE;
using namespace UTILS;
//////////////////////////////////////////////////////////////////////////
// public:
//////////////////////////////////////////////////////////////////////////
LinearSegmentParameter::LinearSegmentParameter() :
m_ui8SegNum( 0 ),
m_ui16Length( 0 ),
m_ui16Width( 0 ),
m_ui16Height( 0 ),
m_ui16Depth( 0 ),
m_ui32Padding( 0 )
{
m_ModificationUnion.m_ui8Modifications = 0;
}
//////////////////////////////////////////////////////////////////////////
LinearSegmentParameter::LinearSegmentParameter( KDataStream & stream ) throw( KException )
{
Decode( stream );
}
//////////////////////////////////////////////////////////////////////////
LinearSegmentParameter::LinearSegmentParameter( KUINT8 SegNum, KUINT8 Mod, const LinearObjectAppearance & A,
const WorldCoordinates & Loc, const EulerAngles & Ori,
KUINT16 Length, KUINT16 Width, KUINT16 Height, KUINT16 Depth ) :
m_ui8SegNum( SegNum ),
m_ObjApr( A ),
m_Loc( Loc ),
m_Ori( Ori ),
m_ui16Length( Length ),
m_ui16Width( Width ),
m_ui16Height( Height ),
m_ui16Depth( Depth ),
m_ui32Padding( 0 )
{
m_ModificationUnion.m_ui8Modifications = Mod;
}
//////////////////////////////////////////////////////////////////////////
LinearSegmentParameter::~LinearSegmentParameter()
{
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetSegmentNumber( KUINT8 N )
{
m_ui8SegNum = N;
}
//////////////////////////////////////////////////////////////////////////
KUINT8 LinearSegmentParameter::GetSegmentNumber() const
{
return m_ui8SegNum;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetModification( KUINT8 M )
{
m_ModificationUnion.m_ui8Modifications = M;
}
//////////////////////////////////////////////////////////////////////////
KUINT8 LinearSegmentParameter::GetModification() const
{
return m_ModificationUnion.m_ui8Modifications;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetModificationLocation( KBOOL M /*= true*/ )
{
m_ModificationUnion.m_ui8LocBit = M;
}
//////////////////////////////////////////////////////////////////////////
KBOOL LinearSegmentParameter::IsModificationLocation() const
{
return m_ModificationUnion.m_ui8LocBit;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetModificationOrientation( KBOOL M /*= true*/ )
{
m_ModificationUnion.m_ui8OriBit = M;
}
//////////////////////////////////////////////////////////////////////////
KBOOL LinearSegmentParameter::IsModificationOrientation() const
{
return m_ModificationUnion.m_ui8OriBit;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetLinearObjectAppearance( const LinearObjectAppearance & L )
{
m_ObjApr = L;
}
//////////////////////////////////////////////////////////////////////////
const LinearObjectAppearance & LinearSegmentParameter::GetLinearObjectAppearance() const
{
return m_ObjApr;
}
//////////////////////////////////////////////////////////////////////////
LinearObjectAppearance & LinearSegmentParameter::GetLinearObjectAppearance()
{
return m_ObjApr;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetLocation( const WorldCoordinates & L )
{
m_Loc = L;
}
//////////////////////////////////////////////////////////////////////////
const WorldCoordinates & LinearSegmentParameter::GetLocation() const
{
return m_Loc;
}
//////////////////////////////////////////////////////////////////////////
WorldCoordinates & LinearSegmentParameter::GetLocation()
{
return m_Loc;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetOrientation( const EulerAngles & O )
{
m_Ori = O;
}
//////////////////////////////////////////////////////////////////////////
const EulerAngles & LinearSegmentParameter::GetOrientation() const
{
return m_Ori;
}
//////////////////////////////////////////////////////////////////////////
EulerAngles & LinearSegmentParameter::GetOrientation()
{
return m_Ori;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetLength( KUINT16 L )
{
m_ui16Length = L;
}
//////////////////////////////////////////////////////////////////////////
KUINT16 LinearSegmentParameter::GetLength() const
{
return m_ui16Length;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetWidth( KUINT16 W )
{
m_ui16Width = W;
}
//////////////////////////////////////////////////////////////////////////
KUINT16 LinearSegmentParameter::GetWidth() const
{
return m_ui16Width;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetHeight( KUINT16 H )
{
m_ui16Height = H;
}
//////////////////////////////////////////////////////////////////////////
KUINT16 LinearSegmentParameter::GetHeight() const
{
return m_ui16Height;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::SetDepth( KUINT16 D )
{
m_ui16Depth = D;
}
//////////////////////////////////////////////////////////////////////////
KUINT16 LinearSegmentParameter::GetDepth() const
{
return m_ui16Depth;
}
//////////////////////////////////////////////////////////////////////////
KString LinearSegmentParameter::GetAsString() const
{
KStringStream ss;
ss << "LinearSegmentParameter:\n"
<< "\tSegment Number: " << ( KUINT16 )m_ui8SegNum << "\n"
<< "\tModification:\n"
<< "\t\tLocation: " << ( KUINT16 )m_ModificationUnion.m_ui8LocBit << "\n"
<< "\t\tOrientation: " << ( KUINT16 )m_ModificationUnion.m_ui8OriBit << "\n"
<< IndentString( m_ObjApr.GetAsString(), 1 )
<< "\tLocation: " << m_Loc.GetAsString()
<< "\tOrientation: " << m_Ori.GetAsString()
<< "\tLength: " << m_ui16Length << "\n"
<< "\tWidth: " << m_ui16Width << "\n"
<< "\tHeight: " << m_ui16Height << "\n"
<< "\tDepth: " << m_ui16Depth << "\n";
return ss.str();
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::Decode( KDataStream & stream ) throw( KException )
{
if( stream.GetBufferSize() < LINEAR_SEGMENT_PARAMETER_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER );
stream >> m_ui8SegNum
>> m_ModificationUnion.m_ui8Modifications
>> KDIS_STREAM m_ObjApr
>> KDIS_STREAM m_Loc
>> KDIS_STREAM m_Ori
>> m_ui16Length
>> m_ui16Width
>> m_ui16Height
>> m_ui16Depth
>> m_ui32Padding;
}
//////////////////////////////////////////////////////////////////////////
KDataStream LinearSegmentParameter::Encode() const
{
KDataStream stream;
LinearSegmentParameter::Encode( stream );
return stream;
}
//////////////////////////////////////////////////////////////////////////
void LinearSegmentParameter::Encode( KDataStream & stream ) const
{
stream << m_ui8SegNum
<< m_ModificationUnion.m_ui8Modifications
<< KDIS_STREAM m_ObjApr
<< KDIS_STREAM m_Loc
<< KDIS_STREAM m_Ori
<< m_ui16Length
<< m_ui16Width
<< m_ui16Height
<< m_ui16Depth
<< m_ui32Padding;
}
//////////////////////////////////////////////////////////////////////////
KBOOL LinearSegmentParameter::operator == ( const LinearSegmentParameter & Value ) const
{
if( m_ui8SegNum != Value.m_ui8SegNum ) return false;
if( m_ModificationUnion.m_ui8Modifications != Value.m_ModificationUnion.m_ui8Modifications ) return false;
if( m_ObjApr != Value.m_ObjApr ) return false;
if( m_Loc != Value.m_Loc ) return false;
if( m_Ori != Value.m_Ori ) return false;
if( m_ui16Length != Value.m_ui16Length ) return false;
if( m_ui16Width != Value.m_ui16Width ) return false;
if( m_ui16Height != Value.m_ui16Height ) return false;
if( m_ui16Depth != Value.m_ui16Depth ) return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
KBOOL LinearSegmentParameter::operator != ( const LinearSegmentParameter & Value ) const
{
return !( *this == Value );
}
//////////////////////////////////////////////////////////////////////////
| 31.5
| 124
| 0.479201
|
cdit-ma
|
414862b9dbd90ee656c9fdfe2c2bffd6df2013b6
| 746
|
cpp
|
C++
|
16790.cpp
|
jnvshubham7/CPP_Programming
|
a17c4a42209556495302ca305b7c3026df064041
|
[
"Apache-2.0"
] | 1
|
2021-12-22T12:37:36.000Z
|
2021-12-22T12:37:36.000Z
|
16790.cpp
|
jnvshubham7/CPP_Programming
|
a17c4a42209556495302ca305b7c3026df064041
|
[
"Apache-2.0"
] | null | null | null |
16790.cpp
|
jnvshubham7/CPP_Programming
|
a17c4a42209556495302ca305b7c3026df064041
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
int t;
cin >> t;
while (t--) {
ll n;
cin >> n;
if (n % 4 == 0 && n % 6 == 0) {
cout << n / 6 << " " << n / 4 << endl;
}
else if (n < 6) {
if (n % 4 == 0) {
cout << "1"
<< " "
<< "1" << endl;
} else {
cout << "-1" << endl;
}
} else if (n % 4 == 0 && n % 6 != 0) {
if (n % 6 == 4) {
cout << (n / 6 + 1) << " " << (n / 4) << endl;
} else {
cout << "-1" << endl;
}
}
else if (n % 4 != 0 && n % 6 == 0) {
cout << "-1" << endl;
}
else {
cout << "-1" << endl;
}
}
return 0;
}
| 13.814815
| 54
| 0.290885
|
jnvshubham7
|
414b75f8c43cce60e5ea63b0cd22d03b196f1fa0
| 1,778
|
cpp
|
C++
|
2016/Day12/JSONAnalysis.cpp
|
marcuskrahl/AdventOfCode
|
0148d9a01a565aac1a6104a6001478fab3b6d4f8
|
[
"MIT"
] | null | null | null |
2016/Day12/JSONAnalysis.cpp
|
marcuskrahl/AdventOfCode
|
0148d9a01a565aac1a6104a6001478fab3b6d4f8
|
[
"MIT"
] | null | null | null |
2016/Day12/JSONAnalysis.cpp
|
marcuskrahl/AdventOfCode
|
0148d9a01a565aac1a6104a6001478fab3b6d4f8
|
[
"MIT"
] | null | null | null |
#include "JSONAnalysis.hpp"
#include <regex>
std::regex number_regex("-?\\d+");
int get_sum_of_numbers(const std::string& input) {
std::smatch match;
int sum = 0;
std::string reduced_input = input;
while (std::regex_search(reduced_input, match, number_regex)) {
int extracted_number = std::stoi(match[0]);
sum += extracted_number;
reduced_input = match.suffix().str();
}
return sum;
}
std::string::iterator get_position_of_open_brace(std::string& input, size_t pos) {
auto it = input.begin() + pos;
int level = 0;
do {
it--;
if (*it == '}') {
level++;
} else if (*it == '{') {
if (level == 0) {
break;
} else {
level--;
}
}
} while (it != input.begin());
return it;
}
std::string::iterator get_position_of_close_brace(std::string& input, size_t pos) {
auto it = input.begin() + pos;
int level = 0;
while (it != input.end()) {
if (*it == '{') {
level++;
} else if (*it == '}') {
if (level == 0) {
break;
} else {
level--;
}
}
it++;
}
return it;
}
std::string remove_red_objects(std::string input) {
size_t pos;
while ((pos = input.find(":\"red\"")) != std::string::npos) {
auto pos_open = get_position_of_open_brace(input, pos);
auto pos_close = get_position_of_close_brace(input, pos);
input.erase(pos_open,pos_close+1);
}
return input;
}
int get_sum_of_numbers_without_red(const std::string& input) {
std::string input_without_red = remove_red_objects(input);
return get_sum_of_numbers(input_without_red);
}
| 25.4
| 83
| 0.53937
|
marcuskrahl
|
414eab0e3202fa44efd2dbb1e20082a48190f367
| 589
|
cpp
|
C++
|
system/StageTwo.cpp
|
arulagrawal/cos214_project
|
1ea65ac7e46b97107c0ec2a75359514bc6c98c15
|
[
"BSD-2-Clause"
] | null | null | null |
system/StageTwo.cpp
|
arulagrawal/cos214_project
|
1ea65ac7e46b97107c0ec2a75359514bc6c98c15
|
[
"BSD-2-Clause"
] | null | null | null |
system/StageTwo.cpp
|
arulagrawal/cos214_project
|
1ea65ac7e46b97107c0ec2a75359514bc6c98c15
|
[
"BSD-2-Clause"
] | null | null | null |
#include "StageTwo.h"
///runs all the functions of stage according to stageTwo parameters and requirements.
StageTwo::StageTwo(Falcon* f) : Stage(f){
}
bool StageTwo::staticFire(){
return falcon->getEngine()->test();
}
void StageTwo::on(){
falcon->getEngine()->on();
}
void StageTwo::off(){
falcon->getEngine()->off();
}
double StageTwo::boost(double weight, double alt){
//cout<<"HERE"<<endl;
return falcon->getEngine()->boost(weight, alt);
}
int StageTwo::getStage(){
return 2;
}
void StageTwo::next(){
cout << "Final stage reached already." << endl;
}
| 19.633333
| 85
| 0.657046
|
arulagrawal
|
a990b55a32bca41668116e24767449113cd671c5
| 601
|
hxx
|
C++
|
is_scalar.hxx
|
mojo-runtime/lib-std
|
35178964db5b51184f35447f33c379de9768b534
|
[
"MIT"
] | null | null | null |
is_scalar.hxx
|
mojo-runtime/lib-std
|
35178964db5b51184f35447f33c379de9768b534
|
[
"MIT"
] | null | null | null |
is_scalar.hxx
|
mojo-runtime/lib-std
|
35178964db5b51184f35447f33c379de9768b534
|
[
"MIT"
] | null | null | null |
#pragma once
#include "is_arithmetic.hxx"
#include "is_enum.hxx"
#include "is_member_pointer.hxx"
#include "is_null_pointer.hxx"
#include "is_pointer.hxx"
#include "is_same.hxx"
namespace std {
template <typename T>
struct is_scalar : integral_constant<bool,
std::is_arithmetic<T>() ||
std::is_enum<T>() ||
std::is_member_pointer<T>() ||
std::is_null_pointer<T>() ||
std::is_pointer<T>()>
{
};
}
| 26.130435
| 67
| 0.475874
|
mojo-runtime
|
a99405149444514516d370fec6285fa324b8c334
| 2,363
|
cc
|
C++
|
coding/Reactor/v3/TCPConnection.cc
|
snow-tyan/learn-cpp
|
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
|
[
"MulanPSL-1.0"
] | null | null | null |
coding/Reactor/v3/TCPConnection.cc
|
snow-tyan/learn-cpp
|
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
|
[
"MulanPSL-1.0"
] | null | null | null |
coding/Reactor/v3/TCPConnection.cc
|
snow-tyan/learn-cpp
|
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
|
[
"MulanPSL-1.0"
] | null | null | null |
#include "TCPConnection.hh"
#include "EventLoop.hh"
#include <sstream>
using std::ostringstream;
namespace wd
{
TCPConnection::TCPConnection(int fd, EventLoop *event)
: _sock(Socket(fd)),
_sockio(SocketIO(fd)),
_localAddr(getLocalAddr(fd)),
_peerAddr(getPeerAddr(fd)),
_isShutdownWrite(false),
_event(event) {}
TCPConnection::~TCPConnection()
{
if (!_isShutdownWrite) {
shutdown();
}
}
void TCPConnection::shutdown()
{
if (!_isShutdownWrite) {
_isShutdownWrite = true;
_sock.shutdownWrite();
}
}
string TCPConnection::toString() const
{
ostringstream oss;
oss << _localAddr.ip() << ":" << _localAddr.port()
<< "-->" << _peerAddr.ip() << ":" << _peerAddr.port();
return oss.str();
}
string TCPConnection::recv()
{
char buff[65536] = {0};
_sockio.readLine(buff, sizeof(buff));
// _sockio.readn(buff, sizeof buff);
return string(buff);
}
void TCPConnection::sendInLoop(const string &msg)
{
if (_event) {
_event->runInLoop(std::bind(&TCPConnection::send, this, msg));
}
}
void TCPConnection::send(const string &msg)
{
_sockio.writen(msg.c_str(), msg.size());
}
InetAddress TCPConnection::getLocalAddr(int fd)
{
struct sockaddr_in addr;
socklen_t len = sizeof(struct sockaddr);
if (-1 == getsockname(_sock.fd(), (struct sockaddr *)&addr, &len)) {
perror("getsockname");
}
return InetAddress(addr);
}
InetAddress TCPConnection::getPeerAddr(int fd)
{
struct sockaddr_in addr;
socklen_t len = sizeof(struct sockaddr);
if (-1 == getpeername(_sock.fd(), (struct sockaddr *)&addr, &len)) {
perror("getpeername");
}
return InetAddress(addr);
}
void TCPConnection::setConnectionCallback(const TCPCallback &cb)
{
_onConnection = cb;
}
void TCPConnection::setMessageCallback(const TCPCallback &cb)
{
_onMessage = cb;
}
void TCPConnection::setCloseCallback(const TCPCallback &cb)
{
_onClose = cb;
}
void TCPConnection::handleConnectionCallback()
{
if (_onConnection) {
_onConnection(shared_from_this());
}
}
void TCPConnection::handleMessageCallback()
{
if (_onMessage) {
_onMessage(shared_from_this());
}
}
void TCPConnection::handleCloseCallback()
{
if (_onClose) {
_onClose(shared_from_this());
}
}
} // end of namespace wd
| 22.292453
| 72
| 0.65256
|
snow-tyan
|
a997e3e1615ebe70661c294f3cc8e2239b83a4dd
| 18,695
|
cpp
|
C++
|
Calc/src/device_vkw.cpp
|
generalistr6/Radeon_Rays
|
d9e0a89d8e770c7fbd1e8c20761432b8ce93ecf7
|
[
"MIT"
] | null | null | null |
Calc/src/device_vkw.cpp
|
generalistr6/Radeon_Rays
|
d9e0a89d8e770c7fbd1e8c20761432b8ce93ecf7
|
[
"MIT"
] | null | null | null |
Calc/src/device_vkw.cpp
|
generalistr6/Radeon_Rays
|
d9e0a89d8e770c7fbd1e8c20761432b8ce93ecf7
|
[
"MIT"
] | null | null | null |
#include "except_vk.h"
#if defined(USE_VULKAN)
#include <cassert>
#include "misc/debug.h"
#include "wrappers/device.h"
#include "wrappers/shader_module.h"
#include "wrappers/buffer.h"
#include "wrappers/descriptor_set_group.h"
#include "wrappers/command_pool.h"
#include "wrappers/compute_pipeline_manager.h"
#include "wrappers/command_buffer.h"
#include "wrappers/fence.h"
#include "wrappers/queue.h"
#include "wrappers/pipeline_layout.h"
#include "wrappers/physical_device.h"
#include "misc/glsl_to_spirv.h"
#include "calc_common.h"
#include "buffer.h"
#include "event.h"
#include "executable.h"
#include "common_vk.h"
#include "buffer_vk.h"
#include "event_vk.h"
#include "executable_vk.h"
#include "function_vk.h"
#include "device_vk.h"
namespace Calc
{
void LogError( const char* in_assertion_text,
const char* in_condition,
const char* in_file_name,
int in_line,
const char* in_comment )
{
printf( in_assertion_text, in_condition, in_file_name, in_line, in_comment );
int to_set_breakpoint_here = 0;
}
void Abort()
{
int to_set_breakpoint_here = 0;
abort();
}
// ctor
DeviceVulkanw::DeviceVulkanw( Anvil::Device* in_new_device, bool in_use_compute_pipe ) :
DeviceVulkan()
, m_anvil_device( in_new_device )
, m_is_command_buffer_recording( false )
, m_use_compute_pipe( in_use_compute_pipe )
, m_cpu_fence_id( 0 )
, m_gpu_known_fence_id( 1 )
{
m_anvil_device->retain();
for( auto& fence : m_anvil_fences )
{
fence.reset( new Anvil::Fence(m_anvil_device, true) );
}
}
// dtor
DeviceVulkanw::~DeviceVulkanw()
{
m_command_buffer.reset();
for (auto& fence : m_anvil_fences) { fence.reset(); }
m_anvil_device->release();
}
// Allocate CommandBuffer used to record compute commands
bool DeviceVulkanw::InitializeVulkanResources()
{
const Anvil::QueueFamilyType familyType = m_use_compute_pipe ? Anvil::QUEUE_FAMILY_TYPE_COMPUTE : Anvil::QUEUE_FAMILY_TYPE_UNIVERSAL;
auto cmd_pool = m_anvil_device->get_command_pool( familyType );
// if device doesn't have the type of pool asked for, bail
if(cmd_pool == nullptr) {
return false;
}
m_command_buffer.reset( cmd_pool->alloc_primary_level_command_buffer() );
return nullptr != m_command_buffer;
}
bool DeviceVulkanw::InitializeVulkanCommandBuffer(Anvil::CommandPool* cmd_pool)
{
m_command_buffer.reset(cmd_pool->alloc_primary_level_command_buffer());
return nullptr != m_command_buffer;
}
// Return specification of the device
void DeviceVulkanw::GetSpec( DeviceSpec& spec )
{
const Anvil::PhysicalDevice* device = m_anvil_device->get_physical_device();
spec.name = device->get_device_properties().deviceName;
spec.vendor = device->get_device_properties().deviceName;
spec.type = DeviceType::kGpu;
spec.sourceTypes = SourceType::kGLSL;
uint64_t localMemory = 0;
uint64_t hostMemory = 0;
for (uint32_t i = 0; i < device->get_memory_properties().types.size(); ++i)
{
const Anvil::MemoryType& memoryType = device->get_memory_properties().types[i];
if (memoryType.flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
{
localMemory += memoryType.heap_ptr->size;
}
else if (memoryType.flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT)
{
hostMemory += memoryType.heap_ptr->size;
}
}
spec.global_mem_size = static_cast< std::size_t >(hostMemory);
spec.local_mem_size = static_cast< std::size_t >(localMemory);
spec.min_alignment = static_cast< std::uint32_t >(device->get_device_properties().limits.minMemoryMapAlignment);
spec.max_alloc_size = static_cast< std::size_t >(hostMemory);
spec.max_local_size = static_cast< std::size_t >(localMemory);
}
// Buffer creation and deletion
Buffer* DeviceVulkanw::CreateBuffer( std::size_t size, std::uint32_t flags )
{
return CreateBuffer( size, flags, nullptr );
}
Buffer* DeviceVulkanw::CreateBuffer( std::size_t size, std::uint32_t flags, void* initdata )
{
if(size == 0 )
{
throw ExceptionVk("Buffer size of 0 isn't valid" );
return nullptr;
}
const Anvil::QueueFamilyBits queueToUse = (true == m_use_compute_pipe) ?
Anvil::QUEUE_FAMILY_COMPUTE_BIT :
Anvil::QUEUE_FAMILY_GRAPHICS_BIT;
Anvil::Buffer* newBuffer = new Anvil::Buffer( m_anvil_device
, size
, queueToUse
, VK_SHARING_MODE_EXCLUSIVE
, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT
, true
, false
, initdata );
return new BufferVulkan( newBuffer, false );
}
void DeviceVulkanw::DeleteBuffer( Buffer* buffer )
{
if ( nullptr != buffer )
{
delete buffer;
}
}
// Data movement
void DeviceVulkanw::ReadBuffer( Buffer const* buffer, std::uint32_t queue, std::size_t offset, std::size_t size, void* dst, Event** e ) const
{
if (nullptr != e) {
*e = new EventVulkan(this);
}
BufferVulkan* vulkanBuffer = ConstCast<BufferVulkan>( buffer );
// make sure GPU has stopped using this buffer
WaitForFence(vulkanBuffer->m_fence_id);
Anvil::Buffer* anvilBuffer = vulkanBuffer->GetAnvilBuffer();
anvilBuffer->read( offset, size, dst );
}
void DeviceVulkanw::WriteBuffer( Buffer const* buffer, std::uint32_t queue, std::size_t offset, std::size_t size, void* src, Event** e )
{
if (nullptr != e) {
*e = new EventVulkan(this);
}
BufferVulkan* vulkanBuffer = ConstCast<BufferVulkan>( buffer );
// make sure GPU has stopped using this buffer
WaitForFence(vulkanBuffer->m_fence_id);
Anvil::Buffer* anvilBuffer = vulkanBuffer->GetAnvilBuffer();
anvilBuffer->write( offset, size, src );
}
// Buffer mapping
void DeviceVulkanw::MapBuffer( Buffer const* buffer,
std::uint32_t queue,
std::size_t offset,
std::size_t size,
std::uint32_t map_type,
void** mapdata,
Event** e )
{
BufferVulkan* vulkanBuffer = ConstCast<BufferVulkan>( buffer );
// make sure GPU has stopped using this buffer
WaitForFence(vulkanBuffer->m_fence_id);
if( nullptr != e ) {
*e = new EventVulkan(this);
}
// allocated a proxy buffer
uint8_t* mappedMemory = new uint8_t[ size ];
(*mapdata) = mappedMemory;
if ( MapType::kMapRead == map_type )
{
// read the Vulkan buffer
ReadBuffer( buffer, queue, offset, size, mappedMemory, e );
}
else if ( MapType::kMapWrite != map_type )
{
VK_EMPTY_IMPLEMENTATION;
}
vulkanBuffer->SetMappedMemory( mappedMemory, map_type, offset, size );
}
void DeviceVulkanw::UnmapBuffer( Buffer const* buffer, std::uint32_t queue, void* mapdata, Event** e )
{
// get the allocated proxy buffer
BufferVulkan* vulkanBuffer = ConstCast<BufferVulkan>( buffer );
if( nullptr != e ) {
*e = new EventVulkan(this);
}
const MappedMemory& mappedMemory = vulkanBuffer->GetMappedMemory();
Assert( mappedMemory.data == mapdata );
if ( MapType::kMapWrite == mappedMemory.type )
{
// write the proxy buffer data to the Vulkan buffer
WriteBuffer( buffer, queue, mappedMemory.offset, mappedMemory.size, mapdata, e );
}
delete[] mappedMemory.data;
vulkanBuffer->SetMappedMemory( nullptr, 0, 0, 0 );
}
// Kernel compilation
Executable* DeviceVulkanw::CompileExecutable( char const* source_code, std::size_t size, char const* options )
{
return new ExecutableVulkan( m_anvil_device, source_code, size, m_use_compute_pipe );
}
Executable* DeviceVulkanw::CompileExecutable( std::uint8_t const* binary_code, std::size_t size, char const* options )
{
VK_EMPTY_IMPLEMENTATION;
return nullptr;
}
Executable* DeviceVulkanw::CompileExecutable( char const* inFilename, char const** inHeaderNames, int inHeadersNum, char const* options)
{
return new ExecutableVulkan( m_anvil_device, inFilename, m_use_compute_pipe );
}
void DeviceVulkanw::DeleteExecutable( Executable* executable )
{
delete executable;
}
// Executable management
size_t DeviceVulkanw::GetExecutableBinarySize( Executable const* executable ) const
{
VK_EMPTY_IMPLEMENTATION;
return 0;
}
void DeviceVulkanw::GetExecutableBinary( Executable const* executable, std::uint8_t* binary ) const
{
VK_EMPTY_IMPLEMENTATION;
}
// Get queue, the execution of vulkan shaders can be done through the compute queue or the graphic queue
Anvil::Queue* DeviceVulkanw::GetQueue() const
{
Anvil::Queue* toReturn = (true == m_use_compute_pipe) ?
m_anvil_device->get_compute_queue( 0 ) :
m_anvil_device->get_universal_queue( 0 );
return toReturn;
}
// To start recording Vulkan commands to the CommandBuffer
void DeviceVulkanw::StartRecording()
{
Assert( false == m_is_command_buffer_recording );
AllocNextFenceId();
const auto fence = GetFence( m_cpu_fence_id );
fence->reset();
m_is_command_buffer_recording = true;
m_command_buffer->reset( false );
m_command_buffer->start_recording( true, false );
}
// Finish recording
void DeviceVulkanw::EndRecording( bool in_wait_till_completed, Event** out_event )
{
// execute CommandBuffer if either wait_till_completed
// TODO buffer n exec's per commit
CommitCommandBuffer( in_wait_till_completed );
if ( nullptr != out_event )
{
*out_event = new EventVulkan( this );
}
}
// Execute CommandBuffer
void DeviceVulkanw::CommitCommandBuffer( bool in_wait_till_completed )
{
const auto fence = GetFence( m_cpu_fence_id );
m_is_command_buffer_recording = false;
m_command_buffer->stop_recording();
GetQueue()->submit_command_buffer( m_command_buffer.get(), in_wait_till_completed, fence );
}
// Execution Not thread safe
void DeviceVulkanw::Execute( Function const* func, std::uint32_t queue, size_t global_size, size_t local_size, Event** e )
{
FunctionVulkan* vulkan_function = ConstCast<FunctionVulkan>( func );
uint32_t number_of_parameters = (uint32_t)( vulkan_function->GetParameters().size() );
// get the Function's descriptor set group
Anvil::DescriptorSetGroup* new_descriptor_set = vulkan_function->GetDescriptorSetGroup();
// if it's empty, this is 1st run of the Function so we have to create it
if ( nullptr == new_descriptor_set )
{
// allocate it through Anvil
new_descriptor_set = new Anvil::DescriptorSetGroup( m_anvil_device, false, 1 );
// add bindings and items (Buffers) to the new DSG
for ( uint32_t i = 0; i < number_of_parameters; ++i )
{
const Buffer* parameter = vulkan_function->GetParameters()[ i ];
BufferVulkan* buffer = ConstCast<BufferVulkan>( parameter );
new_descriptor_set->add_binding( 0, i, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT );
}
// set it to the Function to be reused during any subsequent run
vulkan_function->SetDescriptorSetGroup( new_descriptor_set );
}
// bind new items (Buffers), releasing the old ones
for ( uint32_t i = 0; i < number_of_parameters; ++i )
{
const Buffer* parameter = vulkan_function->GetParameters()[ i ];
BufferVulkan* buffer = ConstCast<BufferVulkan>( parameter );
new_descriptor_set->set_binding_item( 0, i, buffer->GetAnvilBuffer() );
}
// get the Function's pipeline
Anvil::ComputePipelineID pipeline_id = vulkan_function->GetPipelineID();
// if it is invalid, this is 1st run of the Function so we have to create it
if ( ~0u == pipeline_id )
{
// create the pipeline through Anvil with the shader module as a parameter
m_anvil_device->get_compute_pipeline_manager()->add_regular_pipeline( false, false, vulkan_function->GetFunctionEntryPoint(), &pipeline_id );
// attach the DSG to it
m_anvil_device->get_compute_pipeline_manager()->attach_dsg_to_pipeline( pipeline_id, new_descriptor_set );
// remember the pipeline for any seubsequent run
vulkan_function->SetPipelineID( pipeline_id );
}
// indicate we'll be recording Vulkan commands to the CommandBuffer from now on
StartRecording();
// attach pipeline
m_command_buffer->record_bind_pipeline( VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_id );
Anvil::PipelineLayout* pipeline_layout = m_anvil_device->get_compute_pipeline_manager()->get_compute_pipeline_layout( pipeline_id );
Anvil::DescriptorSet* descriptor_set = new_descriptor_set->get_descriptor_set( 0 );
// attach layout and 0 descriptor set (we don't use any other set currently)
m_command_buffer->record_bind_descriptor_sets( VK_PIPELINE_BIND_POINT_COMPUTE,
pipeline_layout,
0,
1,
&descriptor_set,
0,
nullptr );
// set memory barriers
for ( uint32_t i = 0; i < number_of_parameters; ++i )
{
const Buffer* parameter = vulkan_function->GetParameters()[ i ];
BufferVulkan* buffer = ConstCast<BufferVulkan>( parameter );
Anvil::BufferBarrier bufferBarrier( VK_ACCESS_HOST_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
GetQueue()->get_queue_family_index(),
GetQueue()->get_queue_family_index(),
buffer->GetAnvilBuffer(),
0,
buffer->GetSize() );
m_command_buffer->record_pipeline_barrier( VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_FALSE,
0, nullptr,
1, &bufferBarrier,
0, nullptr );
// tell buffer that we are used by this submit
buffer->SetFenceId( GetFenceId() );
}
// dispatch the Function's shader module
m_command_buffer->record_dispatch( (uint32_t)global_size, 1, 1 );
// end recording
EndRecording( false, e );
// remove references to buffers. they were already referenced by the CommandBuffer.
vulkan_function->UnreferenceParametersBuffers();
}
// Events handling
void DeviceVulkanw::WaitForEvent( Event* e )
{
e->Wait();
}
void DeviceVulkanw::WaitForMultipleEvents( Event** e, std::size_t num_events )
{
if(nullptr == e)
return;
// TODO optimize
for (size_t i = 0; i < num_events; ++i)
{
(*e)[i].Wait();
}
}
void DeviceVulkanw::DeleteEvent( Event* e )
{
if ( nullptr != e )
{
delete e;
}
}
// Queue management functions
void DeviceVulkanw::Flush( std::uint32_t queue )
{
if(false == m_is_command_buffer_recording)
{
StartRecording();
}
EndRecording(true, nullptr);
}
void DeviceVulkanw::Finish( std::uint32_t queue )
{
// TODO work out semantics of these two
Flush(queue);
}
bool DeviceVulkanw::HasBuiltinPrimitives() const
{
VK_EMPTY_IMPLEMENTATION;
return false;
}
Primitives* DeviceVulkanw::CreatePrimitives() const
{
VK_EMPTY_IMPLEMENTATION;
return nullptr;
}
void DeviceVulkanw::DeletePrimitives( Primitives* prims )
{
VK_EMPTY_IMPLEMENTATION;
}
uint64_t DeviceVulkanw::AllocNextFenceId() {
// stall if we have run out of fences to use
while( m_cpu_fence_id >= m_gpu_known_fence_id + NUM_FENCE_TRACKERS)
{
WaitForFence(m_gpu_known_fence_id+1);
}
return m_cpu_fence_id.fetch_add(1);
}
void DeviceVulkanw::WaitForFence( uint64_t id ) const
{
AssertEx( id < m_gpu_known_fence_id + NUM_FENCE_TRACKERS,
"CPU too far ahead of GPU" );
while(HasFenceBeenPassed(id) == false ) {
vkWaitForFences(m_anvil_device->get_device_vk(), 1,
GetFence(m_gpu_known_fence_id)->get_fence_ptr(),
VK_TRUE,
UINT64_MAX);
// don't known id update until wait has finished
m_gpu_known_fence_id++;
}
}
}
#endif // USE_VULKAN
| 34.429098
| 153
| 0.58406
|
generalistr6
|
a99ad348afbb52eae1bad522a78bb3bc5a926217
| 788
|
cpp
|
C++
|
third_party/common/src/RE/NiAVObject.cpp
|
qis/alchemy
|
fe6897fa8c065eccc49b61c8c82eda223d865d51
|
[
"0BSD"
] | 3
|
2018-04-05T04:04:17.000Z
|
2021-02-01T17:50:01.000Z
|
third_party/common/src/RE/NiAVObject.cpp
|
qis/alchemy
|
fe6897fa8c065eccc49b61c8c82eda223d865d51
|
[
"0BSD"
] | null | null | null |
third_party/common/src/RE/NiAVObject.cpp
|
qis/alchemy
|
fe6897fa8c065eccc49b61c8c82eda223d865d51
|
[
"0BSD"
] | 1
|
2021-02-01T17:50:03.000Z
|
2021-02-01T17:50:03.000Z
|
#include "RE/NiAVObject.h"
#include "RE/Offsets.h"
#include "REL/Relocation.h"
namespace RE
{
void NiAVObject::UpdateModelHair(NiColorA** a_color)
{
using func_t = function_type_t<decltype(&NiAVObject::UpdateModelHair)>;
REL::Offset<func_t*> func(Offset::NiAVObject::UpdateModelHair);
return func(this, a_color);
}
void NiAVObject::UpdateModelSkin(NiColorA** a_color)
{
using func_t = function_type_t<decltype(&NiAVObject::UpdateModelSkin)>;
REL::Offset<func_t*> func(Offset::NiAVObject::UpdateModelSkin);
return func(this, a_color);
}
void NiAVObject::UpdateNode(ControllerUpdateContext* a_ctx)
{
using func_t = function_type_t<decltype(&NiAVObject::UpdateNode)>;
REL::Offset<func_t*> func(Offset::NiAVObject::UpdateNode);
return func(this, a_ctx);
}
}
| 24.625
| 73
| 0.744924
|
qis
|
a99bfc42e52ec1502a3586f60e38578f54f0fd19
| 451
|
cpp
|
C++
|
ref/SerialTool-master/SerialTool/src/views/terminal/qvterminal/qvtchar.cpp
|
Azjhong/qt
|
98f26b097289e3a11b4ae606c880461b876eebb2
|
[
"MIT"
] | null | null | null |
ref/SerialTool-master/SerialTool/src/views/terminal/qvterminal/qvtchar.cpp
|
Azjhong/qt
|
98f26b097289e3a11b4ae606c880461b876eebb2
|
[
"MIT"
] | null | null | null |
ref/SerialTool-master/SerialTool/src/views/terminal/qvterminal/qvtchar.cpp
|
Azjhong/qt
|
98f26b097289e3a11b4ae606c880461b876eebb2
|
[
"MIT"
] | null | null | null |
#include "qvtchar.h"
QVTChar::QVTChar()
{
m_char = QChar();
}
QVTChar::QVTChar(QChar c, const QVTCharFormat &format)
{
m_char = c;
m_background = format.background();
m_foreground = format.foreground();
}
QChar QVTChar::c() const
{
return m_char;
}
void QVTChar::setC(QChar c)
{
m_char = c;
}
QColor QVTChar::background() const
{
return m_background;
}
QColor QVTChar::foreground() const
{
return m_foreground;
}
| 13.264706
| 54
| 0.658537
|
Azjhong
|
a99d63a5cdc85bd5904e86268ce69ef64e31b706
| 794
|
cpp
|
C++
|
src/EExceptionMonitor.cpp
|
developkits/CxxMina
|
705734fccc5ef87c7faa385b77cd1e67c46c5c75
|
[
"Apache-2.0"
] | 7
|
2016-08-25T14:22:36.000Z
|
2020-05-25T17:27:51.000Z
|
src/EExceptionMonitor.cpp
|
developkits/CxxMina
|
705734fccc5ef87c7faa385b77cd1e67c46c5c75
|
[
"Apache-2.0"
] | 1
|
2018-07-11T12:37:55.000Z
|
2018-07-12T00:05:33.000Z
|
src/EExceptionMonitor.cpp
|
developkits/CxxMina
|
705734fccc5ef87c7faa385b77cd1e67c46c5c75
|
[
"Apache-2.0"
] | 2
|
2017-06-09T01:22:36.000Z
|
2021-09-29T16:27:58.000Z
|
/*
* EExceptionMonitor.cpp
*
* Created on: 2015-12-28
* Author: cxxjava@163.com
*/
#include "../inc/EExceptionMonitor.hh"
#include "../inc/EDefaultExceptionMonitor.hh"
namespace efc {
namespace eio {
EExceptionMonitor* EExceptionMonitor::instance = null;
DEFINE_STATIC_INITZZ_BEGIN(EExceptionMonitor)
ESystem::_initzz_();
instance = new EDefaultExceptionMonitor();
DEFINE_STATIC_INITZZ_END
EExceptionMonitor::~EExceptionMonitor() {
}
EExceptionMonitor* EExceptionMonitor::getInstance() {
return instance;
}
void EExceptionMonitor::setInstance(EExceptionMonitor* monitor) {
if (monitor == null) {
monitor = new EDefaultExceptionMonitor();
}
delete instance;
instance = monitor;
}
EExceptionMonitor::EExceptionMonitor() {
}
} /* namespace eio */
} /* namespace efc */
| 18.904762
| 65
| 0.744332
|
developkits
|
a99fa9d2dbedeef58d0aafbc070a00004912be4c
| 237
|
cpp
|
C++
|
test/test_config.cpp
|
yangfly/FaceApi
|
a7c217d8bc05224a79593d8c5c664bab4adc821c
|
[
"MIT"
] | null | null | null |
test/test_config.cpp
|
yangfly/FaceApi
|
a7c217d8bc05224a79593d8c5c664bab4adc821c
|
[
"MIT"
] | null | null | null |
test/test_config.cpp
|
yangfly/FaceApi
|
a7c217d8bc05224a79593d8c5c664bab4adc821c
|
[
"MIT"
] | null | null | null |
#include "config.hpp"
using namespace std;
using namespace ocean_ai;
int main() {
try {
Config config("config.json");
int a = 5;
}
catch (const std::invalid_argument& ex) {
cout << "exception: " << ex.what();
}
return 0;
}
| 14.8125
| 42
| 0.628692
|
yangfly
|
a9a3a58302bc727d64e0c96f63bdaced213d6497
| 1,571
|
cc
|
C++
|
libs/time/legacy-test-date-stamp.cc
|
sandtreader/obtools
|
2382e2d90bb62c9665433d6d01bbd31b8ad66641
|
[
"MIT"
] | null | null | null |
libs/time/legacy-test-date-stamp.cc
|
sandtreader/obtools
|
2382e2d90bb62c9665433d6d01bbd31b8ad66641
|
[
"MIT"
] | null | null | null |
libs/time/legacy-test-date-stamp.cc
|
sandtreader/obtools
|
2382e2d90bb62c9665433d6d01bbd31b8ad66641
|
[
"MIT"
] | null | null | null |
//==========================================================================
// ObTools::Time: test-stamp.cc
//
// Test harness for time library - reading and converting durations
//
// Copyright (c) 2005 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-time.h"
#include <iostream>
using namespace std;
using namespace ObTools;
const char *days[] = { "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
//--------------------------------------------------------------------------
// Main
int main()
{
Time::DateStamp now = Time::Stamp::now();
time_t t = now.time();
cout << "now -> " << asctime(gmtime(&t))
<< " -> " << now.iso() << " (" << days[now.weekday()-1] << ")"
<< endl;
// Read a line at a time, and convert to stamp
while (!cin.eof())
{
string line;
getline(cin, line);
Time::DateStamp s(line);
time_t t = s.time();
cout << "--------------------" << endl;
cout << " Input: " << line << endl;
cout << " ISO date: " << s.iso() << endl;
cout << " check time: " << asctime(gmtime(&t));
cout << " weekday: " << days[s.weekday()-1] << endl;
Time::DateStamp local = s.localise();
cout << " localised: " << local.iso() << endl;
cout << " globalised: " << local.globalise().iso() << endl;
cout << " locale date: " << s.locale_date() << endl;
}
return 0;
}
| 29.092593
| 76
| 0.460216
|
sandtreader
|
a9a3aee61896fbd27bfe3e26f9043970a1ce5ae3
| 1,806
|
cpp
|
C++
|
libs/oef-base/src/comms/Listener.cpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 1
|
2019-09-30T12:22:46.000Z
|
2019-09-30T12:22:46.000Z
|
libs/oef-base/src/comms/Listener.cpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | null | null | null |
libs/oef-base/src/comms/Listener.cpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 1
|
2019-12-06T10:02:35.000Z
|
2019-12-06T10:02:35.000Z
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// 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 <functional>
#include <iostream>
#include "oef-base/comms/Core.hpp"
#include "oef-base/comms/Listener.hpp"
#include "oef-base/monitoring/Counter.hpp"
static Counter accepting("mt-core.network.accept");
static Counter errored("mt-core.network.accepterror");
static Counter accepted("mt-core.network.accepted");
Listener::Listener(Core &thecore, unsigned short int port)
: core(thecore)
{
acceptor = thecore.makeAcceptor(port);
}
void Listener::start_accept()
{
auto new_connection = creator(core);
accepting++;
acceptor->async_accept(
new_connection->socket(),
std::bind(&Listener::handle_accept, this, new_connection, std::placeholders::_1));
}
void Listener::handle_accept(std::shared_ptr<ISocketOwner> const &new_connection,
std::error_code const & error)
{
accepted++;
if (!error)
{
new_connection->go();
start_accept();
}
else
{
errored++;
std::cout << "Listener::handle_accept " << error << std::endl;
}
}
| 30.1
| 88
| 0.629014
|
chr15murray
|
a9a6531c61c9b4b0b7a146cda2efe541ccda6cd6
| 1,286
|
cpp
|
C++
|
src/kenobet.cpp
|
iurylamonie/keno
|
b6dd28a7a36037ac5ea606d1ba77abd0d400ad6c
|
[
"MIT"
] | null | null | null |
src/kenobet.cpp
|
iurylamonie/keno
|
b6dd28a7a36037ac5ea606d1ba77abd0d400ad6c
|
[
"MIT"
] | null | null | null |
src/kenobet.cpp
|
iurylamonie/keno
|
b6dd28a7a36037ac5ea606d1ba77abd0d400ad6c
|
[
"MIT"
] | null | null | null |
#include "kenobet.h"
bool KenoBet::add_number( number_type spot_ )
{
if( spot_ >= 1 and spot_ <= 80)
{
if( m_spots.size() ) ///< Verifica se já foi salvo algum spot do jogador.
{
auto rbsearch = std::binary_search( m_spots.begin(), m_spots.end(), spot_ );
if( !rbsearch ) ///< Caso o spot não exista em m_spots, ele é inserido.
{
m_spots.push_back( spot_ );
std::sort( m_spots.begin(), m_spots.end() );
return true;
}
}
else { m_spots.push_back( spot_ ); return true; } ///< Caso nenhum spot tenha sido salvo ainda
}
return false;
}
bool KenoBet::set_wage( cash_type wage_ )
{
if( wage_ > 0 )
{
m_wage = wage_;
return true;
}
return false;
}
void KenoBet::reset( void )
{
m_wage = 0;
m_spots.clear();
}
cash_type KenoBet::get_wage( void ) const { return m_wage; }
size_t KenoBet::size ( void ) const { return m_spots.size(); }
set_of_numbers_type KenoBet::get_hits( const set_of_numbers_type & hits_ ) const
{
set_of_numbers_type rhits;///< Armazena em ordem crescente os acertos do jogador
for( auto i : hits_ )
{
auto rbsearch = std::binary_search( m_spots.begin(), m_spots.end(), i);
if( rbsearch ) rhits.push_back( i );
}
return rhits;
}
set_of_numbers_type KenoBet::get_spots( void ) const { return m_spots; }
| 22.561404
| 96
| 0.664852
|
iurylamonie
|
a9a9138a72b45826f20291e2c911ae60c60f41f8
| 4,579
|
cpp
|
C++
|
src/sa-bsn/target_system/components/component/src/Sensor.cpp
|
gabrielevi10/bsn
|
2d42aa006933caf75365bb327fd7d79ae30c88b7
|
[
"MIT"
] | 8
|
2020-01-26T15:26:27.000Z
|
2022-01-05T15:38:07.000Z
|
src/sa-bsn/target_system/components/component/src/Sensor.cpp
|
gabrielevi10/bsn
|
2d42aa006933caf75365bb327fd7d79ae30c88b7
|
[
"MIT"
] | 50
|
2019-08-29T23:52:43.000Z
|
2021-01-24T19:09:54.000Z
|
src/sa-bsn/target_system/components/component/src/Sensor.cpp
|
gabrielevi10/bsn
|
2d42aa006933caf75365bb327fd7d79ae30c88b7
|
[
"MIT"
] | 4
|
2019-06-15T17:23:57.000Z
|
2020-10-16T20:09:41.000Z
|
#include "component/Sensor.hpp"
Sensor::Sensor(int &argc, char **argv, const std::string &name, const std::string &type, const bool &active, const double &noise_factor, const bsn::resource::Battery &battery, const bool &instant_recharge) : Component(argc, argv, name), type(type), active(active), buffer_size(1), replicate_collect(1), noise_factor(0), battery(battery), data(0.0), instant_recharge(instant_recharge), cost(0.0) {}
Sensor::~Sensor() {}
Sensor& Sensor::operator=(const Sensor &obj) {
this->type = obj.type;
this->active = obj.active;
this->noise_factor = obj.noise_factor;
this->battery = obj.battery;
this->data = obj.data;
this->instant_recharge = obj.instant_recharge;
}
int32_t Sensor::run() {
setUp();
if (!shouldStart) {
Component::shutdownComponent();
}
ros::NodeHandle nh;
ros::Subscriber noise_subs = nh.subscribe("uncertainty_"+ros::this_node::getName(), 10, &Sensor::injectUncertainty, this);
ros::Subscriber reconfig_subs = nh.subscribe("reconfigure_"+ros::this_node::getName(), 10, &Sensor::reconfigure, this);
sendStatus("init");
ros::spinOnce();
while (ros::ok()) {
ros::Rate loop_rate(rosComponentDescriptor.getFreq());
ros::spinOnce();
try {
body();
} catch (const std::exception& e) {
std::cout << "sensor failed: " << e.what() << std::endl;
sendStatus("fail");
cost = 0;
}
loop_rate.sleep();
}
return 0;
}
void Sensor::body() {
if (!isActive() && battery.getCurrentLevel() > 90){
turnOn();
} else if (isActive() && battery.getCurrentLevel() < 2){
turnOff();
}
if(isActive()) {
sendStatus("running");
data = collect();
/*for data replication, as if replicate_collect values were collected*/
{
double sum;
for(int i = 0; i < replicate_collect; ++i) {
double aux_data = data;
apply_noise(aux_data);
sum += aux_data;
}
data = sum/replicate_collect;
}
data = process(data);
transfer(data);
sendStatus("success");
sendEnergyStatus(cost);
cost = 0.0;
} else {
recharge();
throw std::domain_error("out of charge");
}
}
/*
* error = noise_factor (%)
* data +- [(error + rand(0,1)) * error] * data
**/
void Sensor::apply_noise(double &data) {
double offset = 0;
offset = (noise_factor + ((double)rand() / RAND_MAX) * noise_factor) * data;
data += (rand()%2==0)?offset:(-1)*offset;
noise_factor = 0;
}
void Sensor::reconfigure(const archlib::AdaptationCommand::ConstPtr& msg) {
std::string action = msg->action.c_str();
std::vector<std::string> pairs = bsn::utils::split(action, ',');
for (std::vector<std::string>::iterator it = pairs.begin(); it != pairs.end(); ++it){
std::vector<std::string> param = bsn::utils::split(action, '=');
if(param[0]=="freq"){
double new_freq = stod(param[1]);
rosComponentDescriptor.setFreq(new_freq);
} else if (param[0]=="replicate_collect") {
int new_replicate_collect = stoi(param[1]);
if(new_replicate_collect>1 && new_replicate_collect<200) replicate_collect = new_replicate_collect;
}
}
}
void Sensor::injectUncertainty(const archlib::Uncertainty::ConstPtr& msg) {
std::string content = msg->content;
std::vector<std::string> pairs = bsn::utils::split(content, ',');
for (std::vector<std::string>::iterator it = pairs.begin(); it != pairs.end(); ++it){
std::vector<std::string> param = bsn::utils::split(content, '=');
if(param[0]=="noise_factor"){
noise_factor = stod(param[1]);
}
}
}
bool Sensor::isActive() {
return active;
}
void Sensor::turnOn() {
active = true;
}
void Sensor::turnOff() {
active = false;
}
/* battery will always recover in 200seconds
*
* b/s = 100% / 200 seconds = 0.2 %/s
* => recovers 5% battery per second
* if we divide by the execution frequency
* we get the amount of battery we need to
* recover per execution cycle to achieve the
* 0.2 %/s battery recovery rate
*/
void Sensor::recharge() {
if(!instant_recharge) {
if(battery.getCurrentLevel() <= 100) {
battery.generate(1);
// battery.generate((100/2000)/rosComponentDescriptor.getFreq());
}
} else {
battery.generate(100);
}
}
| 29.165605
| 397
| 0.590304
|
gabrielevi10
|
a9a9809d4b02025eb25c5f05d3cd79f34999512b
| 903
|
cpp
|
C++
|
Day 1-9/Day 2/Q1.cpp
|
getoxdev/SDE_Interview_Problems
|
d9203a22ed295b7a5e8ee45f236281c95975e23f
|
[
"MIT"
] | 30
|
2021-05-27T14:11:33.000Z
|
2021-08-02T17:51:02.000Z
|
Day 1-9/Day 2/Q1.cpp
|
getoxdev/SDE_Interview_Problems
|
d9203a22ed295b7a5e8ee45f236281c95975e23f
|
[
"MIT"
] | null | null | null |
Day 1-9/Day 2/Q1.cpp
|
getoxdev/SDE_Interview_Problems
|
d9203a22ed295b7a5e8ee45f236281c95975e23f
|
[
"MIT"
] | 9
|
2021-06-02T09:21:04.000Z
|
2021-07-21T15:05:07.000Z
|
#include<bits/stdc++.h>
#define boost ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define R 1000
#define C 1000
#define deb(x) cout << #x << "=" << x << endl
using namespace std;
//Set matrix zeroes
int main()
{
boost;
int r,c;
cin>>r>>c;
int m[r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
cin>>m[i][j];
}
int row[r]={0},col[c]={0};
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(m[i][j]==1)
{
row[i]=1;
col[j]=1;
}
}
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(row[i]==1||col[j]==1)
m[i][j]=1;
}
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
cout<<m[i][j]<<" ";
cout<<"\n";
}
return 0;
}
| 17.037736
| 66
| 0.378738
|
getoxdev
|
a9aa53a9b142cb0f6b8b7c6c79a7225c1feb3b20
| 3,688
|
cpp
|
C++
|
Codeforces Round #781 (Div. 2)/E.cpp
|
frederickpek/codeforces
|
04d6801583ea5901df6bf63fc6f0c092b9b02136
|
[
"MIT"
] | null | null | null |
Codeforces Round #781 (Div. 2)/E.cpp
|
frederickpek/codeforces
|
04d6801583ea5901df6bf63fc6f0c092b9b02136
|
[
"MIT"
] | null | null | null |
Codeforces Round #781 (Div. 2)/E.cpp
|
frederickpek/codeforces
|
04d6801583ea5901df6bf63fc6f0c092b9b02136
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
typedef vector<int> vi;
class SegmentTree { // OOP style
private:
int n; // n = (int)A.size()
vi A, st, lazy; // the arrays
int l(int p) { return p<<1; } // go to left child
int r(int p) { return (p<<1)+1; } // go to right child
int conquer(int a, int b) {
if (a == -1) return b; // corner case
if (b == -1) return a;
return min(a, b); // RMQ
}
void build(int p, int L, int R) { // O(n)
if (L == R)
st[p] = A[L]; // base case
else {
int m = (L+R)/2;
build(l(p), L , m);
build(r(p), m+1, R);
st[p] = conquer(st[l(p)], st[r(p)]);
}
}
void propagate(int p, int L, int R) {
if (lazy[p] != -1) { // has a lazy flag
st[p] = lazy[p]; // [L..R] has same value
if (L != R) // not a leaf
lazy[l(p)] = lazy[r(p)] = lazy[p]; // propagate downwards
else // L == R, a single index
A[L] = lazy[p]; // time to update this
lazy[p] = -1; // erase lazy flag
}
}
int RMQ(int p, int L, int R, int i, int j) { // O(log n)
propagate(p, L, R); // lazy propagation
if (i > j) return -1; // infeasible
if ((L >= i) && (R <= j)) {
if (R==j) idx = R;
else if (L==i) idx = L;
return st[p]; // found the segment
}
int m = (L+R)/2;
return conquer(RMQ(l(p), L , m, i , min(m, j)),
RMQ(r(p), m+1, R, max(i, m+1), j ));
}
void update(int p, int L, int R, int i, int j, int val) { // O(log n)
propagate(p, L, R); // lazy propagation
if (i > j) return;
if ((L >= i) && (R <= j)) { // found the segment
lazy[p] = val; // update this
propagate(p, L, R); // lazy propagation
}
else {
int m = (L+R)/2;
update(l(p), L , m, i , min(m, j), val);
update(r(p), m+1, R, max(i, m+1), j , val);
int lsubtree = (lazy[l(p)] != -1) ? lazy[l(p)] : st[l(p)];
int rsubtree = (lazy[r(p)] != -1) ? lazy[r(p)] : st[r(p)];
st[p] = (lsubtree <= rsubtree) ? st[l(p)] : st[r(p)];
}
}
public:
int idx = -1;
SegmentTree(int sz) : n(sz), st(4*n), lazy(4*n, -1) {}
SegmentTree(const vi &initialA) : SegmentTree((int)initialA.size()) {
A = initialA;
build(1, 0, n-1);
}
void update(int i, int j, int val) { update(1, 0, n-1, i, j, val); }
pair<int,int> rmq(int i, int j) {
idx = -1;
int val = RMQ(i, j);
return {idx, val};
}
int RMQ(int i, int j) { return RMQ(1, 0, n-1, i, j); }
};
void solve() {
int n;
cin >> n;
vector<int> a(n);
rep(i, n) cin >> a[i];
SegmentTree st(a);
int q;
cin >> q;
rep(k, q) {
int l, r;
cin >> l >> r;
l--; r--;
auto [idx, smallest] = st.rmq(l, r);
int L = 2e9;
if (idx-1>=l) {
auto [ii, cand] = st.rmq(l, idx-1);
L = cand;
}
int R = 2e9;
if (idx+1<=r) {
auto [ii, cand] = st.rmq(idx+1, r);
R = cand;
}
int secondSmallest = min(L, R);
cout << (smallest | secondSmallest) << endl;
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
rep(i, t) solve();
}
| 26.919708
| 74
| 0.404826
|
frederickpek
|
a9ab6ace81a22116b07aa9ddf94f0c06789aa42c
| 19,394
|
cpp
|
C++
|
test/oxtra/encoding/encoding_test.cpp
|
oxtra/oxtra
|
cd538062869bfe68fc8552604c22334589d7380c
|
[
"BSD-3-Clause"
] | 9
|
2019-10-22T19:44:25.000Z
|
2021-05-02T17:47:14.000Z
|
test/oxtra/encoding/encoding_test.cpp
|
oxtra/oxtra
|
cd538062869bfe68fc8552604c22334589d7380c
|
[
"BSD-3-Clause"
] | 1
|
2020-11-16T20:06:14.000Z
|
2020-11-16T20:06:14.000Z
|
test/oxtra/encoding/encoding_test.cpp
|
oxtra/oxtra
|
cd538062869bfe68fc8552604c22334589d7380c
|
[
"BSD-3-Clause"
] | 2
|
2020-11-16T17:05:47.000Z
|
2021-05-02T17:47:16.000Z
|
#include "../../catch2/catch.hpp"
#include "oxtra/codegen/encoding/encoding.h"
#include <stdlib.h>
#include <string.h>
using namespace encoding;
void refactor(const char *assembly, utils::riscv_instruction_t encoded) {
char assembly_[100] = {0};
strcat(assembly_, ".section .text\n.global _start\n\n_start:\n\t");
strcat(assembly_, assembly);
strcat(assembly_, "\n");
FILE *assemblyf = fopen("comp.s", "w");
fprintf(assemblyf, "%s", assembly_);
fclose(assemblyf);
system("/opt/riscv/bin/riscv64-unknown-linux-gnu-gcc comp.s -o comp.elf -static -nostdlib");
system("/opt/riscv/bin/riscv64-unknown-linux-gnu-objcopy -I elf64-little -j .text -O binary comp.elf dump");
char* enc = reinterpret_cast<char*>(&encoded);
char com[5] = {0};
FILE* objdump = fopen("dump", "r");
fread(com, 1, 4, objdump);
fclose(objdump);
REQUIRE(com[0] == enc[0]);
REQUIRE(com[1] == enc[1]);
REQUIRE(com[2] == enc[2]);
REQUIRE(com[3] == enc[3]);
}
void refactor_branch(const char *assembly, utils::riscv_instruction_t encoded) {
char assembly_[100] = {0};
strcat(assembly_, ".section .text\n.global _start\n\n_start:\n\t");
strcat(assembly_, assembly);
strcat(assembly_, "\nlabel:\n");
FILE *assemblyf = fopen("comp.s", "w");
fprintf(assemblyf, "%s", assembly_);
fclose(assemblyf);
system("/opt/riscv/bin/riscv64-unknown-linux-gnu-gcc comp.s -o comp.elf -static -nostdlib");
system("/opt/riscv/bin/riscv64-unknown-linux-gnu-objcopy -I elf64-little -j .text -O binary comp.elf dump");
char* enc = reinterpret_cast<char*>(&encoded);
char com[5] = {0};
FILE* objdump = fopen("dump", "r");
fread(com, 1, 4, objdump);
fclose(objdump);
REQUIRE(com[0] == enc[0]);
REQUIRE(com[1] == enc[1]);
REQUIRE(com[2] == enc[2]);
REQUIRE(com[3] == enc[3]);
}
TEST_CASE("instruction encoding is correct", "[encoding]") {
SECTION("LUI") {
utils::riscv_instruction_t encoded = LUI(RiscVRegister::t4, 0x748);
refactor("lui t4, 0x748", encoded);
}
SECTION("AUIPC") {
utils::riscv_instruction_t encoded = AUIPC(RiscVRegister::t4, 0x748);
refactor("auipc t4, 0x748", encoded);
}
SECTION("JAL") {
utils::riscv_instruction_t encoded = JAL(RiscVRegister::ra, 0x4);
refactor_branch("jal ra, label", encoded);
}
SECTION("JALR") {
utils::riscv_instruction_t encoded = JALR(RiscVRegister::zero, RiscVRegister::ra, 0x0);
refactor("jalr zero, ra, 0x0", encoded);
}
SECTION("BEQ") {
utils::riscv_instruction_t encoded = BEQ(RiscVRegister::t4, RiscVRegister::t5, 0x4);
refactor_branch("beq t4, t5, label", encoded);
}
SECTION("BNE") {
utils::riscv_instruction_t encoded = BNE(RiscVRegister::t4, RiscVRegister::t5, 0x4);
refactor_branch("bne t4, t5, label", encoded);
}
SECTION("BLT") {
utils::riscv_instruction_t encoded = BLT(RiscVRegister::t4, RiscVRegister::t5, 0x4);
refactor_branch("blt t4, t5, label", encoded);
}
SECTION("BGE") {
utils::riscv_instruction_t encoded = BGE(RiscVRegister::t4, RiscVRegister::t5, 0x4);
refactor_branch("bge t4, t5, label", encoded);
}
SECTION("BLTU") {
utils::riscv_instruction_t encoded = BLTU(RiscVRegister::t4, RiscVRegister::t5, 0x4);
refactor_branch("bltu t4, t5, label", encoded);
}
SECTION("BGEU") {
utils::riscv_instruction_t encoded = BGEU(RiscVRegister::t4, RiscVRegister::t5, 0x4);
refactor_branch("bgeu t4, t5, label", encoded);
}
SECTION("LB") {
utils::riscv_instruction_t encoded = LB(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("lb t4, 0x748(t5)", encoded);
}
SECTION("LH") {
utils::riscv_instruction_t encoded = LH(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("lh t4, 0x748(t5)", encoded);
}
SECTION("LW") {
utils::riscv_instruction_t encoded = LW(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("lw t4, 0x748(t5)", encoded);
}
SECTION("LD") {
utils::riscv_instruction_t encoded = LD(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("ld t4, 0x748(t5)", encoded);
}
SECTION("LBU") {
utils::riscv_instruction_t encoded = LBU(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("lbu t4, 0x748(t5)", encoded);
}
SECTION("LHU") {
utils::riscv_instruction_t encoded = LHU(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("lhu t4, 0x748(t5)", encoded);
}
SECTION("LWU") {
utils::riscv_instruction_t encoded = LWU(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("lwu t4, 0x748(t5)", encoded);
}
// gcc syntax has the registers for store instructions reversed
SECTION("SB") {
utils::riscv_instruction_t encoded = SB(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("sb t5, 0x748(t4)", encoded);
}
SECTION("SH") {
utils::riscv_instruction_t encoded = SH(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("sh t5, 0x748(t4)", encoded);
}
SECTION("SW") {
utils::riscv_instruction_t encoded = SW(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("sw t5, 0x748(t4)", encoded);
}
SECTION("SD") {
utils::riscv_instruction_t encoded = SD(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("sd t5, 0x748(t4)", encoded);
}
SECTION("ADDI") {
utils::riscv_instruction_t encoded = ADDI(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("addi t4, t5, 0x748", encoded);
}
SECTION("SLTI") {
utils::riscv_instruction_t encoded = SLTI(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("slti t4, t5, 0x748", encoded);
}
SECTION("SLTIU") {
utils::riscv_instruction_t encoded = SLTIU(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("sltiu t4, t5, 0x748", encoded);
}
SECTION("XORI") {
utils::riscv_instruction_t encoded = XORI(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("xori t4, t5, 0x748", encoded);
}
SECTION("ORI") {
utils::riscv_instruction_t encoded = ORI(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("ori t4, t5, 0x748", encoded);
}
SECTION("ANDI") {
utils::riscv_instruction_t encoded = ANDI(RiscVRegister::t4, RiscVRegister::t5, 0x748);
refactor("andi t4, t5, 0x748", encoded);
}
SECTION("SLLI") {
utils::riscv_instruction_t encoded = SLLI(RiscVRegister::t4, RiscVRegister::t5, 0x11);
refactor("SLLI t4, t5, 0x11", encoded);
}
SECTION("SRLI") {
utils::riscv_instruction_t encoded = SRLI(RiscVRegister::t4, RiscVRegister::t5, 0x11);
refactor("SRLI t4, t5, 0x11", encoded);
}
SECTION("SRAI") {
utils::riscv_instruction_t encoded = SRAI(RiscVRegister::t4, RiscVRegister::t5, 0x11);
refactor("SRAI t4, t5, 0x11", encoded);
}
SECTION("ADD") {
utils::riscv_instruction_t encoded = ADD(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("add t4, t5, t6", encoded);
}
SECTION("SUB") {
utils::riscv_instruction_t encoded = SUB(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("sub t4, t5, t6", encoded);
}
SECTION("SLL") {
utils::riscv_instruction_t encoded = SLL(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("sll t4, t5, t6", encoded);
}
SECTION("SLT") {
utils::riscv_instruction_t encoded = SLT(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("slt t4, t5, t6", encoded);
}
SECTION("SLTU") {
utils::riscv_instruction_t encoded = SLTU(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("sltu t4, t5, t6", encoded);
}
SECTION("XOR") {
utils::riscv_instruction_t encoded = XOR(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("xor t4, t5, t6", encoded);
}
SECTION("SRL") {
utils::riscv_instruction_t encoded = SRL(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("srl t4, t5, t6", encoded);
}
SECTION("SRA") {
utils::riscv_instruction_t encoded = SRA(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("sra t4, t5, t6", encoded);
}
SECTION("OR") {
utils::riscv_instruction_t encoded = OR(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("or t4, t5, t6", encoded);
}
SECTION("AND") {
utils::riscv_instruction_t encoded = AND(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("and t4, t5, t6", encoded);
}
SECTION("MUL") {
utils::riscv_instruction_t encoded = MUL(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("mul t4, t5, t6", encoded);
}
SECTION("MULH") {
utils::riscv_instruction_t encoded = MULH(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("mulh t4, t5, t6", encoded);
}
SECTION("MULHSU") {
utils::riscv_instruction_t encoded = MULHSU(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("mulhsu t4, t5, t6", encoded);
}
SECTION("MULHU") {
utils::riscv_instruction_t encoded = MULHU(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("mulhu t4, t5, t6", encoded);
}
SECTION("DIV") {
utils::riscv_instruction_t encoded = DIV(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("div t4, t5, t6", encoded);
}
SECTION("DIVU") {
utils::riscv_instruction_t encoded = DIVU(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("divu t4, t5, t6", encoded);
}
SECTION("REM") {
utils::riscv_instruction_t encoded = REM(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("rem t4, t5, t6", encoded);
}
SECTION("REMU") {
utils::riscv_instruction_t encoded = REMU(RiscVRegister::t4, RiscVRegister::t5, RiscVRegister::t6);
refactor("remu t4, t5, t6", encoded);
}
SECTION("FLW") {
utils::riscv_instruction_t encoded = FLW(RiscVFloatingRegister::f9, RiscVRegister::t4, 0x748);
refactor("flw f9, 0x748(t4)", encoded);
}
SECTION("FSW") {
utils::riscv_instruction_t encoded = FSW(RiscVRegister::t4, RiscVFloatingRegister::f9, 0x748);
refactor("fsw f9, 0x748(t4)", encoded);
}
SECTION("FMADDS") {
utils::riscv_instruction_t encoded = FMADDS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fmadd.s f6, f7, f8, f9", encoded);
}
SECTION("FMSUBS") {
utils::riscv_instruction_t encoded = FMSUBS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fmsub.s f6, f7, f8, f9", encoded);
}
SECTION("FNMSUBS") {
utils::riscv_instruction_t encoded = FNMSUBS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fnmsub.s f6, f7, f8, f9", encoded);
}
SECTION("FNMADDS") {
utils::riscv_instruction_t encoded = FNMADDS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fnmadd.s f6, f7, f8, f9", encoded);
}
SECTION("FADDS") {
utils::riscv_instruction_t encoded = FADDS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fadd.s f6, f7, f8", encoded);
}
SECTION("FSUBS") {
utils::riscv_instruction_t encoded = FSUBS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsub.s f6, f7, f8", encoded);
}
SECTION("FMULS") {
utils::riscv_instruction_t encoded = FMULS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fmul.s f6, f7, f8", encoded);
}
SECTION("FDIVS") {
utils::riscv_instruction_t encoded = FDIVS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fdiv.s f6, f7, f8", encoded);
}
SECTION("FSQRTS") {
utils::riscv_instruction_t encoded = FSQRTS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7);
refactor("fsqrt.s f6, f7", encoded);
}
SECTION("FSGNJS") {
utils::riscv_instruction_t encoded = FSGNJS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsgnj.s f6, f7, f8", encoded);
}
SECTION("FSGNJNS") {
utils::riscv_instruction_t encoded = FSGNJNS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsgnjn.s f6, f7, f8", encoded);
}
SECTION("FSGNJXS") {
utils::riscv_instruction_t encoded = FSGNJXS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsgnjx.s f6, f7, f8", encoded);
}
SECTION("FMINS") {
utils::riscv_instruction_t encoded = FMINS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fmin.s f6, f7, f8", encoded);
}
SECTION("FMAXS") {
utils::riscv_instruction_t encoded = FMAXS(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fmax.s f6, f7, f8", encoded);
}
SECTION("FCVTWS") {
utils::riscv_instruction_t encoded = FCVTWS(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.w.s t6, f7", encoded);
}
SECTION("FCVTWUS") {
utils::riscv_instruction_t encoded = FCVTWUS(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.wu.s t6, f7", encoded);
}
SECTION("FEQS") {
utils::riscv_instruction_t encoded = FEQS(RiscVRegister::t6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("feq.s t6, f7, f8", encoded);
}
SECTION("FLTS") {
utils::riscv_instruction_t encoded = FLTS(RiscVRegister::t6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("flt.s t6, f7, f8", encoded);
}
SECTION("FLES") {
utils::riscv_instruction_t encoded = FLES(RiscVRegister::t6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fle.s t6, f7, f8", encoded);
}
SECTION("FCVTSW") {
utils::riscv_instruction_t encoded = FCVTSW(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.s.w f7, t6", encoded);
}
SECTION("FCVTSWU") {
utils::riscv_instruction_t encoded = FCVTSWU(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.s.wu f7, t6", encoded);
}
SECTION("FCVTLS") {
utils::riscv_instruction_t encoded = FCVTLS(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.l.s t6, f7", encoded);
}
SECTION("FCVTLUS") {
utils::riscv_instruction_t encoded = FCVTLUS(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.lu.s t6, f7", encoded);
}
SECTION("FCVTSL") {
utils::riscv_instruction_t encoded = FCVTSL(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.s.l f7, t6", encoded);
}
SECTION("FCVTSLU") {
utils::riscv_instruction_t encoded = FCVTSLU(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.s.lu f7, t6", encoded);
}
SECTION("FLW") {
utils::riscv_instruction_t encoded = FLW(RiscVFloatingRegister::f9, RiscVRegister::t4, 0x748);
refactor("flw f9, 0x748(t4)", encoded);
}
SECTION("FSW") {
utils::riscv_instruction_t encoded = FSW(RiscVRegister::t4, RiscVFloatingRegister::f9, 0x748);
refactor("fsw f9, 0x748(t4)", encoded);
}
SECTION("FMADDD") {
utils::riscv_instruction_t encoded = FMADDD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fmadd.d f6, f7, f8, f9", encoded);
}
SECTION("FMSUBD") {
utils::riscv_instruction_t encoded = FMSUBD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fmsub.d f6, f7, f8, f9", encoded);
}
SECTION("FNMSUBD") {
utils::riscv_instruction_t encoded = FNMSUBD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fnmsub.d f6, f7, f8, f9", encoded);
}
SECTION("FNMADDD") {
utils::riscv_instruction_t encoded = FNMADDD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8, RiscVFloatingRegister::f9);
refactor("fnmadd.d f6, f7, f8, f9", encoded);
}
SECTION("FADDD") {
utils::riscv_instruction_t encoded = FADDD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fadd.d f6, f7, f8", encoded);
}
SECTION("FSUBD") {
utils::riscv_instruction_t encoded = FSUBD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsub.d f6, f7, f8", encoded);
}
SECTION("FMULD") {
utils::riscv_instruction_t encoded = FMULD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fmul.d f6, f7, f8", encoded);
}
SECTION("FDIVD") {
utils::riscv_instruction_t encoded = FDIVD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fdiv.d f6, f7, f8", encoded);
}
SECTION("FSQRTD") {
utils::riscv_instruction_t encoded = FSQRTD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7);
refactor("fsqrt.d f6, f7", encoded);
}
SECTION("FSGNJD") {
utils::riscv_instruction_t encoded = FSGNJD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsgnj.d f6, f7, f8", encoded);
}
SECTION("FSGNJND") {
utils::riscv_instruction_t encoded = FSGNJND(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsgnjn.d f6, f7, f8", encoded);
}
SECTION("FSGNJXD") {
utils::riscv_instruction_t encoded = FSGNJXD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fsgnjx.d f6, f7, f8", encoded);
}
SECTION("FMIND") {
utils::riscv_instruction_t encoded = FMIND(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fmin.d f6, f7, f8", encoded);
}
SECTION("FMAXD") {
utils::riscv_instruction_t encoded = FMAXD(RiscVFloatingRegister::f6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fmax.d f6, f7, f8", encoded);
}
SECTION("FCVTWD") {
utils::riscv_instruction_t encoded = FCVTWD(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.w.d t6, f7", encoded);
}
SECTION("FCVTWUD") {
utils::riscv_instruction_t encoded = FCVTWUD(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.wu.d t6, f7", encoded);
}
SECTION("FEQD") {
utils::riscv_instruction_t encoded = FEQD(RiscVRegister::t6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("feq.d t6, f7, f8", encoded);
}
SECTION("FLTD") {
utils::riscv_instruction_t encoded = FLTD(RiscVRegister::t6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("flt.d t6, f7, f8", encoded);
}
SECTION("FLED") {
utils::riscv_instruction_t encoded = FLED(RiscVRegister::t6, RiscVFloatingRegister::f7, RiscVFloatingRegister::f8);
refactor("fle.d t6, f7, f8", encoded);
}
SECTION("FCVTDW") {
utils::riscv_instruction_t encoded = FCVTDW(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.d.w f7, t6", encoded);
}
SECTION("FCVTDWU") {
utils::riscv_instruction_t encoded = FCVTDWU(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.d.wu f7, t6", encoded);
}
SECTION("FCVTLD") {
utils::riscv_instruction_t encoded = FCVTLD(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.l.d t6, f7", encoded);
}
SECTION("FCVTLUD") {
utils::riscv_instruction_t encoded = FCVTLUD(RiscVRegister::t6, RiscVFloatingRegister::f7);
refactor("fcvt.lu.d t6, f7", encoded);
}
SECTION("FCVTDL") {
utils::riscv_instruction_t encoded = FCVTDL(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.d.l f7, t6", encoded);
}
SECTION("FCVTDLU") {
utils::riscv_instruction_t encoded = FCVTDLU(RiscVFloatingRegister::f7, RiscVRegister::t6);
refactor("fcvt.d.lu f7, t6", encoded);
}
system("rm comp.*");
system("rm dump");
}
| 33.670139
| 155
| 0.714087
|
oxtra
|
a9ab6af87adce41a19d46985ce2361e13b03ec66
| 272
|
cpp
|
C++
|
test/special.cpp
|
DarthPigrum/TypeSI
|
3505cad5113c1c6c907c48b3bd71e24e9ddb32bc
|
[
"BSL-1.0"
] | null | null | null |
test/special.cpp
|
DarthPigrum/TypeSI
|
3505cad5113c1c6c907c48b3bd71e24e9ddb32bc
|
[
"BSL-1.0"
] | null | null | null |
test/special.cpp
|
DarthPigrum/TypeSI
|
3505cad5113c1c6c907c48b3bd71e24e9ddb32bc
|
[
"BSL-1.0"
] | null | null | null |
#include "si_base.hpp"
#include "si_prefix.hpp"
#include "si_special.hpp"
#include <gtest/gtest.h>
TEST(SpecialUnits, Gram) {
EXPECT_EQ(typeid(Si::Prefix<std::milli, Si::Special::Gram<double>>),
typeid(Si::Prefix<std::micro, Si::Base::Kilogram<double>>));
}
| 30.222222
| 72
| 0.683824
|
DarthPigrum
|
a9ad58da5829d2f16fcc1b28726e9bf8034af167
| 2,079
|
h++
|
C++
|
include/ogonek/normalization/normalize.h++
|
libogonek/ogonek
|
46b7edbf6b7ff89892f5ba25494749b442e771b3
|
[
"CC0-1.0"
] | 25
|
2016-10-21T12:37:23.000Z
|
2021-02-22T05:46:46.000Z
|
include/ogonek/normalization/normalize.h++
|
libogonek/ogonek
|
46b7edbf6b7ff89892f5ba25494749b442e771b3
|
[
"CC0-1.0"
] | null | null | null |
include/ogonek/normalization/normalize.h++
|
libogonek/ogonek
|
46b7edbf6b7ff89892f5ba25494749b442e771b3
|
[
"CC0-1.0"
] | 4
|
2016-09-05T10:23:18.000Z
|
2020-07-09T19:37:37.000Z
|
// Ogonek
//
// Written in 2012-2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// Normalization function
#ifndef OGONEK_NORMALIZE_HPP
#define OGONEK_NORMALIZE_HPP
#include <ogonek/sequence/properties.h++>
#include <ogonek/normalization/detail/normalizing_sequence.h++>
#include <wheels/meta.h++>
#include <ogonek/detail/ranges.h++>
#include <ogonek/normalization/detail/normalizing_iterator.h++>
#include <boost/range/iterator_range.hpp>
namespace ogonek {
namespace result_of {
template <typename NormalForm, typename Seq>
using normalize = wheels::meta::Invoke<detail::normalize_impl<NormalForm, Seq>>;
} // namespace result_of
template <typename NormalForm,
typename Seq,
wheels::meta::EnableIf<detail::is_well_formed<Seq>>...>
result_of::normalize<NormalForm, Seq> normalize_ex(Seq&& s) {
return detail::normalize_impl<NormalForm, Seq>::call(std::forward<Seq>(s));
}
template <typename NormalForm,
typename UnicodeSequence,
typename Iterator = detail::UnicodeSequenceIterator<UnicodeSequence, assume_valid_t>,
typename NormalizingIterator = detail::normalizing_iterator<NormalForm, Iterator>,
typename NormalizingRange = boost::iterator_range<NormalizingIterator>>
//typename NormalizingRange = detail::tagged_iterator_range<NormalizingIterator, detail::normalized_tag<NormalForm>>>
NormalizingRange normalize(UnicodeSequence const& sequence) {
return detail::wrap_range<NormalizingIterator>(detail::as_code_point_range(sequence, assume_valid));
}
} // namespace ogonek
#endif // OGONEK_NORMALIZE_HPP
| 40.764706
| 131
| 0.733045
|
libogonek
|
a9b0206a44fd1fdf0d17e1f2771c9f40dfe9bc91
| 2,164
|
hpp
|
C++
|
include/flecs/addons/cpp/module.hpp
|
logankaser/flecs
|
6638a030604542835908463feabbe621c58b057a
|
[
"MIT"
] | 2
|
2021-09-09T13:20:15.000Z
|
2021-09-09T20:23:25.000Z
|
include/flecs/addons/cpp/module.hpp
|
NrdyBhu1/flecs
|
b6a36158ba42f23638c370d5f38aa55774987a65
|
[
"MIT"
] | null | null | null |
include/flecs/addons/cpp/module.hpp
|
NrdyBhu1/flecs
|
b6a36158ba42f23638c370d5f38aa55774987a65
|
[
"MIT"
] | null | null | null |
namespace flecs
{
////////////////////////////////////////////////////////////////////////////////
//// Define a module
////////////////////////////////////////////////////////////////////////////////
template <typename T>
flecs::entity module(const flecs::world& world) {
flecs::entity result = world.id<T>().entity();
ecs_set_scope(world, result);
return result;
}
////////////////////////////////////////////////////////////////////////////////
//// Import a module
////////////////////////////////////////////////////////////////////////////////
template <typename T>
ecs_entity_t do_import(world& world, const char *symbol) {
ecs_trace_1("import %s", _::name_helper<T>::name());
ecs_log_push();
ecs_entity_t scope = ecs_get_scope(world);
ecs_set_scope(world, 0);
// Initialize module component type & don't allow it to be registered as a
// tag, as this would prevent calling emplace()
auto m_c = component<T>(world, nullptr, false);
ecs_add_module_tag(world, m_c);
world.emplace<T>(world);
ecs_set_scope(world, scope);
// // It should now be possible to lookup the module
ecs_entity_t m = ecs_lookup_symbol(world, symbol, true);
ecs_assert(m != 0, ECS_MODULE_UNDEFINED, symbol);
ecs_assert(m == m_c, ECS_INTERNAL_ERROR, NULL);
ecs_log_pop();
return m;
}
template <typename T>
flecs::entity import(world& world) {
char *symbol = _::symbol_helper<T>::symbol();
ecs_entity_t m = ecs_lookup_symbol(world.c_ptr(), symbol, true);
if (!_::cpp_type<T>::registered()) {
/* Module is registered with world, initialize static data */
if (m) {
_::cpp_type<T>::init(world.c_ptr(), m, false);
/* Module is not yet registered, register it now */
} else {
m = do_import<T>(world, symbol);
}
/* Module has been registered, but could have been for another world. Import
* if module hasn't been registered for this world. */
} else if (!m) {
m = do_import<T>(world, symbol);
}
ecs_os_free(symbol);
return flecs::entity(world, m);
}
} // namespace flecs
| 28.473684
| 80
| 0.538355
|
logankaser
|
a9b5acd464cf204b0c13947d12ec1c9d8f1951f0
| 773
|
cpp
|
C++
|
solutions/1005/20101031T152007Z-3278259.cpp
|
Mistereo/timus-solutions
|
062540304c33312b75e0e8713c4b36c80fb220ab
|
[
"MIT"
] | 11
|
2019-10-29T15:34:53.000Z
|
2022-03-14T14:45:09.000Z
|
solutions/1005/20101031T152007Z-3278259.cpp
|
Mistereo/timus-solutions
|
062540304c33312b75e0e8713c4b36c80fb220ab
|
[
"MIT"
] | null | null | null |
solutions/1005/20101031T152007Z-3278259.cpp
|
Mistereo/timus-solutions
|
062540304c33312b75e0e8713c4b36c80fb220ab
|
[
"MIT"
] | 6
|
2018-06-30T12:06:55.000Z
|
2021-03-20T08:46:33.000Z
|
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int comb(int n, int k, int sum, int array[])
{
vector<int> mask(k, 0);
mask.resize(n, 1);
int min=sum;
do
{
int x=0;
for (int i=0; i < mask.size(); i++){
if (!mask[i]) {
x+=array[i];
}
}
if(abs(sum-x-x)<min) {
min=abs(sum-x-x);
}
} while (next_permutation(mask.begin(), mask.end()));
return min;
}
void main () {
int n;
cin >> n;
int *a = new int[n];
int sum=0, k=0;
for(int i=0; i<n; i++) {
cin >> a[i];
sum+=a[i];
}
k = n/2;
int temp = 0;
int min = sum;
for (int i=1; i<=n/2; i++) {
temp = comb(n,i,sum,a);
if (temp < min)
min=temp;
}
cout << min << endl;
system("pause");
}
| 17.177778
| 55
| 0.50194
|
Mistereo
|
a9c315adcd8c274980e63fa2c2249545ad7c537f
| 824
|
cpp
|
C++
|
index.cpp
|
advanced-programmming/plusminus-cpp
|
1c2bc335cdaeb7e480b0ded8c34aef9278556c60
|
[
"MIT"
] | null | null | null |
index.cpp
|
advanced-programmming/plusminus-cpp
|
1c2bc335cdaeb7e480b0ded8c34aef9278556c60
|
[
"MIT"
] | null | null | null |
index.cpp
|
advanced-programmming/plusminus-cpp
|
1c2bc335cdaeb7e480b0ded8c34aef9278556c60
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include <iomanip>
using namespace std;
void plusMinus(vector<int> array);
int main() {
int arraysize = 0;
cin>>arraysize;
vector<int> array;
int number = 0;
for(int i = 0; i < arraysize; i++){
cin>>number;
array.push_back(number);
}
plusMinus(array);
return 0;
}
void plusMinus(vector<int> array) {
double pos = 0.00000;
double neg = 0.00000;
double zer = 0.00000;
double size = array.size() * 1.00000;
for(int i = 0; i < size; i++) {
if(array[i] > 0){
pos++;
} else if (array[i] == 0) {
zer++;
} else {
neg++;
}
}
pos /= size;
neg /= size;
zer /= size;
cout<<fixed<<setprecision(6)<<pos<<endl<<neg<<endl<<zer<<endl;
}
| 17.913043
| 66
| 0.510922
|
advanced-programmming
|
a9c82ad487d78846a9f4c73d61634745f58f30ec
| 1,302
|
hpp
|
C++
|
poc/tstins4/devlogger.hpp
|
upenn-acg/barracuda
|
db2549b62593934d81e3e8141302dd344f85a407
|
[
"BSD-3-Clause"
] | 3
|
2020-05-08T04:37:48.000Z
|
2021-01-31T15:57:15.000Z
|
poc/tstins4/devlogger.hpp
|
upenn-acg/barracuda
|
db2549b62593934d81e3e8141302dd344f85a407
|
[
"BSD-3-Clause"
] | 1
|
2020-11-22T18:24:12.000Z
|
2020-11-22T18:24:12.000Z
|
poc/tstins4/devlogger.hpp
|
upenn-acg/barracuda
|
db2549b62593934d81e3e8141302dd344f85a407
|
[
"BSD-3-Clause"
] | 2
|
2019-12-04T05:43:51.000Z
|
2019-12-04T07:57:31.000Z
|
#pragma once
__device__ void __store_op(const void* address, unsigned char op)
{
unsigned int active = __ballot(1);
unsigned int myidx = threadIdx.x % WARP_SIZE;
unsigned int ldridx = __ffs(active) - 1;
int pos = 0;
const int tbid = (blockIdx.x + pcqnum - 1) % pcqnum;
const int size = pcqbuffer_size;
PCHeader* pcheader = PCHEADER(pcqheader, tbid, pcqbuffer_size);
PCRecord* pcstart = PCSTART(pcheader);
PCRecord* record = NULL;
if(ldridx == myidx)
{
volatile unsigned int* tail = (volatile unsigned int*)&pcheader->tail;
pos = atomicAdd(&pcheader->write_head, 1);
while((pos - *tail) >= size)
__threadfence_system();
}
pos = __shfl(pos, ldridx);
record = pcstart + (pos % size);
DEBUGONLY(printf("bi=%i ti=%i myidx=%i ldridx=%i pos=%i record=%p ra=%p\n", blockIdx.x, threadIdx.x, myidx, ldridx, pos, record, &record->address[myidx]);)
record->address[myidx] = (slimptr_t)(uintptr_t)address;
if(ldridx == myidx)
{
// XXX - support 3d, stream id
record->tid = BUILD_ADDRESS(0, blockIdx.x, threadIdx.x);
record->active = active;
record->op = op;
while(atomicCAS(&pcheader->read_head, pos, pos + 1) != pos)
__threadfence_system();
}
}
| 34.263158
| 159
| 0.61828
|
upenn-acg
|
a9cb087bbf07db62ca7ce4c4dd0807595d7cd505
| 860
|
cpp
|
C++
|
stream/src/main.cpp
|
IamWangYunKai/BallDetection
|
71671f40d451eae174efad944fb324b1cd9ec89e
|
[
"MIT"
] | null | null | null |
stream/src/main.cpp
|
IamWangYunKai/BallDetection
|
71671f40d451eae174efad944fb324b1cd9ec89e
|
[
"MIT"
] | null | null | null |
stream/src/main.cpp
|
IamWangYunKai/BallDetection
|
71671f40d451eae174efad944fb324b1cd9ec89e
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
mutex mtx;
template <typename T>
void change(T *p, T *q){
T tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
void get_video(VideoCapture &cap, Mat *latest_img, Mat *new_img) {
while (true) {
cap.read(*new_img);
mtx.lock();
change(latest_img, new_img);
mtx.unlock();
std::chrono::milliseconds dura(30);
std::this_thread::sleep_for(dura);
}
}
int main(){
VideoCapture cap(0);
Mat img1(Size(640,480), CV_8UC3), img2(Size(640, 480), CV_8UC3);
Mat *latest_img, *new_img;
latest_img = &img1;
new_img = &img2;
std::thread t{ get_video, cap, latest_img, new_img };
t.detach();
while (true) {
imshow("Image", *latest_img);
waitKey(10);
}
return 0;
}
| 17.916667
| 66
| 0.666279
|
IamWangYunKai
|
a9cbc05d053b377e197edc8677b483ea8bcaf06c
| 712
|
hpp
|
C++
|
engine/screens/include/TextDisplayScreen.hpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 60
|
2019-08-21T04:08:41.000Z
|
2022-03-10T13:48:04.000Z
|
engine/screens/include/TextDisplayScreen.hpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | 3
|
2021-03-18T15:11:14.000Z
|
2021-10-20T12:13:07.000Z
|
engine/screens/include/TextDisplayScreen.hpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | 8
|
2019-11-16T06:29:05.000Z
|
2022-01-23T17:33:43.000Z
|
#pragma once
#include <deque>
#include "Screen.hpp"
#include "Colours.hpp"
#include "Symbol.hpp"
// A generic screen that can be used to display text (help files, etc).
class TextDisplayScreen : public Screen
{
public:
TextDisplayScreen(DisplayPtr display, const std::string& new_title_text_sid, const std::vector<TextDisplayPair>& display_text, const bool preserve_formatting = false, const std::deque<Symbol>& symbols = {});
protected:
void initialize(const std::string& new_title_text_sid, const bool preserve_formatting);
// Each string in the vector represents a line to be displayed on
// screen.
std::vector<TextDisplayPair> text;
std::deque<Symbol> replacement_symbols;
};
| 33.904762
| 211
| 0.744382
|
prolog
|
a9cd520ee0f9d54cdb0c0853ac14a396e06d4197
| 1,310
|
cpp
|
C++
|
src/augmented_account.cpp
|
skybaboon/dailycashmanager
|
0b022cc230a8738d5d27a799728da187e22f17f8
|
[
"Apache-2.0"
] | 4
|
2016-07-05T07:42:07.000Z
|
2020-07-15T15:27:22.000Z
|
src/augmented_account.cpp
|
skybaboon/dailycashmanager
|
0b022cc230a8738d5d27a799728da187e22f17f8
|
[
"Apache-2.0"
] | 1
|
2020-05-07T20:58:21.000Z
|
2020-05-07T20:58:21.000Z
|
src/augmented_account.cpp
|
skybaboon/dailycashmanager
|
0b022cc230a8738d5d27a799728da187e22f17f8
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2013 Matthew Harvey
*
* 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 "augmented_account.hpp"
#include "account.hpp"
#include "commodity.hpp"
#include "dcm_database_connection.hpp"
#include <jewel/decimal.hpp>
#include <sqloxx/handle.hpp>
using jewel::Decimal;
using sqloxx::Handle;
namespace dcm
{
AugmentedAccount::AugmentedAccount
( DcmDatabaseConnection& p_database_connection,
Handle<Commodity> const& p_commodity
):
account(p_database_connection),
technical_opening_balance(0, p_commodity->precision())
{
}
AugmentedAccount::AugmentedAccount
( Handle<Account> const& p_account,
jewel::Decimal const& p_technical_opening_balance
):
account(p_account),
technical_opening_balance(p_technical_opening_balance)
{
}
} // namespace dcm
| 26.2
| 75
| 0.755725
|
skybaboon
|
a9d37e111b99e5c184a9e00de1cd74f8027ea8c4
| 1,646
|
cpp
|
C++
|
src/pca9685.cpp
|
ruwix/balance-bot
|
6493f0ae5ed150c4a57f651205ac9fe4883f14d8
|
[
"MIT"
] | null | null | null |
src/pca9685.cpp
|
ruwix/balance-bot
|
6493f0ae5ed150c4a57f651205ac9fe4883f14d8
|
[
"MIT"
] | null | null | null |
src/pca9685.cpp
|
ruwix/balance-bot
|
6493f0ae5ed150c4a57f651205ac9fe4883f14d8
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <array>
#include <algorithm>
#include "pca9685.hpp"
#include "i2c.hpp"
PCA9685::PCA9685(I2C i2c, float freq) : i2c(i2c)
{
i2c.enable(PCA9685_ADDRESS);
if (freq > 0)
{
setPWMFreq(freq);
}
}
void PCA9685::setPWMFreq(int freq)
{
freq = (freq > 1000 ? 1000 : (freq < 40 ? 40 : freq));
int prescale = (int)(25000000.0f / (4096 * freq) - 0.5f);
int settings = i2c.readByte(PCA9685_MODE1) & 0x7F;
int sleep = settings | 0x10;
int wake = settings & 0xEF;
int restart = wake | 0x80;
i2c.writeByte(PCA9685_MODE1, sleep);
i2c.writeByte(PCA9685_PRESCALE, prescale);
i2c.writeByte(PCA9685_MODE1, wake);
i2c.delay(5);
i2c.writeByte(PCA9685_MODE1, restart);
}
void PCA9685::setPWM(int pin, int on, int off)
{
int reg = PIN(pin);
i2c.writeByte(reg, on & 0xFF);
i2c.writeByte(reg + 1, on >> 8);
i2c.writeByte(reg + 2, off & 0xFF);
i2c.writeByte(reg + 3, off >> 8);
}
void PCA9685::setPWM(int pin, int val)
{
int reg = PIN(pin);
val = std::min(val, 4095);
if (val == 0)
{
setPWM(pin, 0, 4096);
}
else if (val == 4095)
{
setPWM(pin, 4096, 0);
}
else
{
setPWM(pin, 0, val);
}
}
std::array<int, 2> PCA9685::getPWM(int pin)
{
int reg = PIN(pin);
std::array<int, 2> ret;
ret[0] = i2c.readByte(reg);
ret[0] |= i2c.readByte(reg + 1) << 8;
ret[1] = i2c.readByte(reg + 2);
ret[1] |= i2c.readByte(reg + 3) << 8;
return ret;
}
void PCA9685::reset()
{
i2c.writeByte(PCA9685_ALL_LED_ON_L, 0x0);
i2c.writeByte(PCA9685_ALL_LED_ON_L + 2, 0x1000);
}
| 21.102564
| 61
| 0.583232
|
ruwix
|
a9d7e38ace670c0b6a49bdce99453de78e4ab36c
| 651
|
cpp
|
C++
|
domains/dubins_traffic/dubins_traffic_utils/examples/standalone/helloroadnet.cpp
|
fmrchallenge/fmrbenchmark
|
529520a2b254f7da366b681983182c9e25555b6c
|
[
"Apache-2.0"
] | 14
|
2015-05-28T22:52:43.000Z
|
2021-07-08T00:21:12.000Z
|
domains/dubins_traffic/dubins_traffic_utils/examples/standalone/helloroadnet.cpp
|
fmrchallenge/fmrbenchmark
|
529520a2b254f7da366b681983182c9e25555b6c
|
[
"Apache-2.0"
] | 15
|
2016-02-07T20:57:09.000Z
|
2021-04-30T23:42:06.000Z
|
domains/dubins_traffic/dubins_traffic_utils/examples/standalone/helloroadnet.cpp
|
fmrchallenge/fmrbenchmark
|
529520a2b254f7da366b681983182c9e25555b6c
|
[
"Apache-2.0"
] | 5
|
2015-12-28T20:53:26.000Z
|
2018-03-08T23:30:44.000Z
|
#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include "roadnet.hpp"
using namespace dubins_traffic;
int main()
{
Eigen::Vector3d transform( 1.0, 0.0, 1.6 );
dubins_traffic::RoadNetwork rd( 2.0, transform, 2, 3 );
std::cout << rd << std::endl;
double x, y;
rd.map_point( 0, 0, x, y );
std::cerr << "(0, 0) -> (" << x << ", " << y << ")" << std::endl;
rd.map_point( 1, 2, x, y );
std::cerr << "(1, 2) -> (" << x << ", " << y << ")" << std::endl;
for (size_t idx = 0; idx < rd.number_of_segments(); idx++)
std::cerr << rd.mapped_segment( idx ).transpose() << std::endl;
return 0;
}
| 23.25
| 71
| 0.526882
|
fmrchallenge
|
a9ecc8748c324e9c8291f8ad83ff9298ec37d0c5
| 909
|
cpp
|
C++
|
_includes/leet098/leet098.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | null | null | null |
_includes/leet098/leet098.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | 8
|
2019-12-19T04:46:05.000Z
|
2022-02-26T03:45:22.000Z
|
_includes/leet098/leet098.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
return dfs(root,NULL,NULL);
}
private:
bool dfs(TreeNode* root,TreeNode* minNode,TreeNode* maxNode){
if(root->left) {
if(root->left->val>=root->val||minNode!=NULL&&root->left->val<=minNode->val)
return false;
if(!dfs(root->left,minNode,root))
return false;
}
if(root->right) {
if(root->right->val<=root->val||maxNode!=NULL&&root->right->val>=maxNode->val)
return false;
if(!dfs(root->right,root,maxNode))
return false;
}
return true;
}
};
| 28.40625
| 90
| 0.525853
|
mingdaz
|
a9efe0aa88184dfd39d89090d594d5170326eb8a
| 4,587
|
cpp
|
C++
|
cpp/godot-cpp/src/gen/XMLParser.cpp
|
GDNative-Gradle/proof-of-concept
|
162f467430760cf959f68f1638adc663fd05c5fd
|
[
"MIT"
] | 1
|
2021-03-16T09:51:00.000Z
|
2021-03-16T09:51:00.000Z
|
cpp/godot-cpp/src/gen/XMLParser.cpp
|
GDNative-Gradle/proof-of-concept
|
162f467430760cf959f68f1638adc663fd05c5fd
|
[
"MIT"
] | null | null | null |
cpp/godot-cpp/src/gen/XMLParser.cpp
|
GDNative-Gradle/proof-of-concept
|
162f467430760cf959f68f1638adc663fd05c5fd
|
[
"MIT"
] | null | null | null |
#include "XMLParser.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
namespace godot {
XMLParser::___method_bindings XMLParser::___mb = {};
void XMLParser::___init_method_bindings() {
___mb.mb_get_attribute_count = godot::api->godot_method_bind_get_method("XMLParser", "get_attribute_count");
___mb.mb_get_attribute_name = godot::api->godot_method_bind_get_method("XMLParser", "get_attribute_name");
___mb.mb_get_attribute_value = godot::api->godot_method_bind_get_method("XMLParser", "get_attribute_value");
___mb.mb_get_current_line = godot::api->godot_method_bind_get_method("XMLParser", "get_current_line");
___mb.mb_get_named_attribute_value = godot::api->godot_method_bind_get_method("XMLParser", "get_named_attribute_value");
___mb.mb_get_named_attribute_value_safe = godot::api->godot_method_bind_get_method("XMLParser", "get_named_attribute_value_safe");
___mb.mb_get_node_data = godot::api->godot_method_bind_get_method("XMLParser", "get_node_data");
___mb.mb_get_node_name = godot::api->godot_method_bind_get_method("XMLParser", "get_node_name");
___mb.mb_get_node_offset = godot::api->godot_method_bind_get_method("XMLParser", "get_node_offset");
___mb.mb_get_node_type = godot::api->godot_method_bind_get_method("XMLParser", "get_node_type");
___mb.mb_has_attribute = godot::api->godot_method_bind_get_method("XMLParser", "has_attribute");
___mb.mb_is_empty = godot::api->godot_method_bind_get_method("XMLParser", "is_empty");
___mb.mb_open = godot::api->godot_method_bind_get_method("XMLParser", "open");
___mb.mb_open_buffer = godot::api->godot_method_bind_get_method("XMLParser", "open_buffer");
___mb.mb_read = godot::api->godot_method_bind_get_method("XMLParser", "read");
___mb.mb_seek = godot::api->godot_method_bind_get_method("XMLParser", "seek");
___mb.mb_skip_section = godot::api->godot_method_bind_get_method("XMLParser", "skip_section");
}
XMLParser *XMLParser::_new()
{
return (XMLParser *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"XMLParser")());
}
int64_t XMLParser::get_attribute_count() const {
return ___godot_icall_int(___mb.mb_get_attribute_count, (const Object *) this);
}
String XMLParser::get_attribute_name(const int64_t idx) const {
return ___godot_icall_String_int(___mb.mb_get_attribute_name, (const Object *) this, idx);
}
String XMLParser::get_attribute_value(const int64_t idx) const {
return ___godot_icall_String_int(___mb.mb_get_attribute_value, (const Object *) this, idx);
}
int64_t XMLParser::get_current_line() const {
return ___godot_icall_int(___mb.mb_get_current_line, (const Object *) this);
}
String XMLParser::get_named_attribute_value(const String name) const {
return ___godot_icall_String_String(___mb.mb_get_named_attribute_value, (const Object *) this, name);
}
String XMLParser::get_named_attribute_value_safe(const String name) const {
return ___godot_icall_String_String(___mb.mb_get_named_attribute_value_safe, (const Object *) this, name);
}
String XMLParser::get_node_data() const {
return ___godot_icall_String(___mb.mb_get_node_data, (const Object *) this);
}
String XMLParser::get_node_name() const {
return ___godot_icall_String(___mb.mb_get_node_name, (const Object *) this);
}
int64_t XMLParser::get_node_offset() const {
return ___godot_icall_int(___mb.mb_get_node_offset, (const Object *) this);
}
XMLParser::NodeType XMLParser::get_node_type() {
return (XMLParser::NodeType) ___godot_icall_int(___mb.mb_get_node_type, (const Object *) this);
}
bool XMLParser::has_attribute(const String name) const {
return ___godot_icall_bool_String(___mb.mb_has_attribute, (const Object *) this, name);
}
bool XMLParser::is_empty() const {
return ___godot_icall_bool(___mb.mb_is_empty, (const Object *) this);
}
Error XMLParser::open(const String file) {
return (Error) ___godot_icall_int_String(___mb.mb_open, (const Object *) this, file);
}
Error XMLParser::open_buffer(const PoolByteArray buffer) {
return (Error) ___godot_icall_int_PoolByteArray(___mb.mb_open_buffer, (const Object *) this, buffer);
}
Error XMLParser::read() {
return (Error) ___godot_icall_int(___mb.mb_read, (const Object *) this);
}
Error XMLParser::seek(const int64_t position) {
return (Error) ___godot_icall_int_int(___mb.mb_seek, (const Object *) this, position);
}
void XMLParser::skip_section() {
___godot_icall_void(___mb.mb_skip_section, (const Object *) this);
}
}
| 41.324324
| 199
| 0.792893
|
GDNative-Gradle
|
a9f01dd4df43db2f233e44740bfc1831c5075455
| 1,721
|
cpp
|
C++
|
jetson/carControl/src/0.3/lane_detection/test_lane_detection.cpp
|
thanhwins/DriveCarLessChallenge
|
716304f3e25b383781ade5f1560ef0d538fc634e
|
[
"MIT"
] | 1
|
2017-12-19T15:53:55.000Z
|
2017-12-19T15:53:55.000Z
|
jetson/carControl/src/0.3/lane_detection/test_lane_detection.cpp
|
thanhwins/DriveCarLessChallenge
|
716304f3e25b383781ade5f1560ef0d538fc634e
|
[
"MIT"
] | null | null | null |
jetson/carControl/src/0.3/lane_detection/test_lane_detection.cpp
|
thanhwins/DriveCarLessChallenge
|
716304f3e25b383781ade5f1560ef0d538fc634e
|
[
"MIT"
] | 1
|
2019-11-27T03:01:55.000Z
|
2019-11-27T03:01:55.000Z
|
#include "api_lane_detection.h"
int
main( int argc, char** argv )
{
string videoFileName = argv[1];
cout<< "Opening File: "<< videoFileName << endl<< flush;
cv::VideoCapture video;
bool isOpenVideo = video.open(videoFileName);
// bool isOpenVideo = video.open(0);
if(!isOpenVideo)
{
cout<< "Can not read image" << endl<< flush;
return 1;
}
cv::Mat imgInput;
cv::Mat imgGray;
MSAC msac;
cv::Rect roi = cv::Rect(0, VIDEO_FRAME_HEIGHT*3/4,
VIDEO_FRAME_WIDTH, VIDEO_FRAME_HEIGHT/4);
api_vanishing_point_init( msac );
char key = 0;
double st = 0, et = 0, fps = 0;
double freq = getTickFrequency();
vector< Point > points;
int max_size = 5;
while(true)
{
video.read( imgInput );
if(imgInput.empty())
{
cout<< "Can not read image" << endl;
break;
}
// Convert to gray
cv::cvtColor(imgInput, imgGray, CV_BGR2GRAY);
st = getTickCount();
Point vp;
api_get_vanishing_point( imgGray, roi, msac, vp, true, "Canny");
if( points.size() <= max_size )
{
points.push_back(vp);
}
if( points.size() > max_size )
{
points.erase(points.begin(), points.begin() + 1);
for( int i = 0; i < points.size()-1; i++ )
{
}
}
et = getTickCount();
fps = 1.0 / ((et-st)/freq);
cout<< endl<< "FPS: "<< fps<< flush;
cout<< endl<< "VP: "<< vp<< flush;
// imshow("input", imgGray );
key = waitKey(-1);
if( key == 27 ) break;
}
return 0;
}
| 18.912088
| 72
| 0.499709
|
thanhwins
|
a9f2a679802d39255e1bacc8f9e646ee877f068c
| 2,414
|
cpp
|
C++
|
src/main.cpp
|
imaphatduc/Hypr
|
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
|
[
"BSD-3-Clause"
] | 277
|
2021-11-19T20:15:18.000Z
|
2022-03-29T12:07:59.000Z
|
src/main.cpp
|
imaphatduc/Hypr
|
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
|
[
"BSD-3-Clause"
] | 46
|
2021-11-21T10:25:58.000Z
|
2022-03-23T15:04:51.000Z
|
src/main.cpp
|
imaphatduc/Hypr
|
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
|
[
"BSD-3-Clause"
] | 28
|
2021-12-07T02:49:16.000Z
|
2022-03-22T05:26:07.000Z
|
/*
Hypr Window Manager for X.
Started by Vaxry on 2021 / 11 / 17
*/
#include <fstream>
#include "windowManager.hpp"
#include "defines.hpp"
#include "bar/Bar.hpp"
int main(int argc, char** argv) {
clearLogs();
Debug::log(LOG, "Hypr debug log. Built on " + std::string(__DATE__) + " at " + std::string(__TIME__));
// Create all pipes
g_pWindowManager->createAndOpenAllPipes();
Debug::log(LOG, "Pipes done! Forking!");
if (fork() == 0) {
// Child. Bar.
// Sleep for 2 seconds. When launching on a real Xorg session there is some race condition there
// I don't know where it is but this will fix it for now.
// Feel free to search for it.
std::this_thread::sleep_for(std::chrono::seconds(2));
const int BARRET = barMainThread();
Debug::log(BARRET == 0 ? LOG : ERR, "Bar exited with code " + std::to_string(BARRET) + "!");
return 0;
}
Debug::log(LOG, "Parent continuing!");
g_pWindowManager->DisplayConnection = xcb_connect(NULL, NULL);
if (const auto RET = xcb_connection_has_error(g_pWindowManager->DisplayConnection); RET != 0) {
Debug::log(CRIT, "Connection Failed! Return: " + std::to_string(RET));
return RET;
}
g_pWindowManager->Screen = xcb_setup_roots_iterator(xcb_get_setup(g_pWindowManager->DisplayConnection)).data;
if (!g_pWindowManager->Screen) {
Debug::log(CRIT, "Screen was null!");
return 1;
}
// get atoms
for (auto& ATOM : HYPRATOMS) {
xcb_intern_atom_cookie_t cookie = xcb_intern_atom(g_pWindowManager->DisplayConnection, 0, ATOM.first.length(), ATOM.first.c_str());
xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(g_pWindowManager->DisplayConnection, cookie, NULL);
if (!reply) {
Debug::log(ERR, "Atom failed: " + ATOM.first);
continue;
}
ATOM.second = reply->atom;
}
g_pWindowManager->setupManager();
Debug::log(LOG, "Hypr Started!");
while (g_pWindowManager->handleEvent()) {
;
}
Debug::log(LOG, "Hypr reached the end! Exiting...");
xcb_disconnect(g_pWindowManager->DisplayConnection);
if (const auto err = xcb_connection_has_error(g_pWindowManager->DisplayConnection); err != 0) {
Debug::log(CRIT, "Exiting because of error " + std::to_string(err));
return err;
}
return 0;
}
| 29.439024
| 139
| 0.634217
|
imaphatduc
|
a9f2ecfc32c59cb23b5c6943dfe31f41336965b9
| 43,049
|
cpp
|
C++
|
ecl/hqlcpp/hqlcatom.cpp
|
oxhead/HPCC-Platform
|
62e092695542a9bbea1bb3672f0d1ff572666cfc
|
[
"Apache-2.0"
] | null | null | null |
ecl/hqlcpp/hqlcatom.cpp
|
oxhead/HPCC-Platform
|
62e092695542a9bbea1bb3672f0d1ff572666cfc
|
[
"Apache-2.0"
] | null | null | null |
ecl/hqlcpp/hqlcatom.cpp
|
oxhead/HPCC-Platform
|
62e092695542a9bbea1bb3672f0d1ff572666cfc
|
[
"Apache-2.0"
] | null | null | null |
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC 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 "platform.h"
#include "jlib.hpp"
#include "jexcept.hpp"
#include "jmisc.hpp"
#include "javahash.hpp"
#include "eclhelper.hpp"
#include "hql.hpp"
#include "hqlatoms.hpp"
#include "hqlcatom.hpp"
IAtom * _accessedFromChild_Atom;
IAtom * activeActivityMarkerAtom;
IAtom * activeMatchTextAtom;
IAtom * activeMatchUnicodeAtom;
IAtom * activeMatchUtf8Atom;
IAtom * activeProductionMarkerAtom;
IAtom * activeValidateMarkerAtom;
IAtom * activityIdMarkerAtom;
IAtom * bitfieldOffsetAtom;
IAtom * blobHelperAtom;
IAtom * branchAtom;
IAtom * checkpointAtom;
IAtom * childAtom;
IAtom * classAtom;
IAtom * clearAtom;
IAtom * __clearHelperAtom;
IAtom * _conditionalRowMarker_Atom;
IAtom * csvReadMarkerAtom;
IAtom * decimalAtom;
IAtom * declareAtom;
IAtom * delayedAtom;
IAtom * dependencyAtom;
IAtom * deserializerAtom;
IAtom * dictionaryAtom;
IAtom * eclAtom;
IAtom * endAtom;
IAtom * ensureCapacityAtom;
IAtom * fileAtom;
IAtom * funnelAtom;
IAtom * forceAllCheckAtom;
IAtom * goAtom;
IAtom * guardAtom;
IAtom * helperAtom;
IAtom * indexLayoutMarkerAtom;
IAtom * initAtom;
IAtom * insideOnCreateAtom;
IAtom * insideOnStartAtom;
IAtom * instanceAtom;
IAtom * isLastBitfieldAtom;
IAtom * _loop_Atom;
IAtom * _loopFirst_Atom;
IAtom * mainprototypesAtom;
IAtom * multiInstanceAtom;
IAtom * _noAccess_Atom;
IAtom * _noReplicate_Atom;
IAtom * noSetAtom;
IAtom * _noVirtual_Atom;
IAtom * numResultsAtom;
IAtom * packingAtom;
IAtom * parentHelpersAtom;
IAtom * pathAtom;
IAtom * prefetcherInstanceMarkerAtom;
IAtom * quickAtom;
IAtom * _regexFindInstance_Atom;
IAtom * _regexInstance_Atom;
IAtom * resultsAtom;
IAtom * rowAllocatorMarkerAtom;
IAtom * rtlFieldKeyMarkerAtom;
IAtom * _selfJoinPlaceholder_Atom;
IAtom * serializerAtom;
IAtom * serializerInstanceMarkerAtom;
IAtom * skipActionMarkerAtom;
IAtom * skipReturnMarkerAtom;
IAtom * speedAtom;
IAtom * _spill_Atom;
IAtom * _spillReason_Atom;
IAtom * _steppedMeta_Atom;
IAtom * subgraphAtom;
IAtom * _translated_Atom;
IAtom * utf8Atom;
IAtom * wrapperAtom;
IAtom * xmlColumnProviderAtom;
IAtom * xmlReadMarkerAtom;
IIdAtom * acosId;
IIdAtom * addAggregateRowId;
IIdAtom * addAllId;
IIdAtom * addRangeId;
IIdAtom * addWorkunitAssertFailureId;
IIdAtom * an2bId;
IIdAtom * an2fId;
IIdAtom * an2l4Id;
IIdAtom * an2l8Id;
IIdAtom * an2ls4Id;
IIdAtom * an2ls8Id;
IIdAtom * appendRowsToRowsetId;
IIdAtom * appendSetXId;
IIdAtom * ascii2ebcdicId;
IIdAtom * asinId;
IIdAtom * atan2Id;
IIdAtom * atanId;
IIdAtom * bool2DataId;
IIdAtom * bool2StrId;
IIdAtom * bool2StrXId;
IIdAtom * bool2VStrId;
IIdAtom * bool2VStrXId;
IIdAtom * castIntId[9][2];
IIdAtom * checkFieldOverflowId;
IIdAtom * checkRowOverflowId;
IIdAtom * clibExpId;
IIdAtom * cloneVStringId;
IIdAtom * cloneVStringXId;
IIdAtom * codeGeneratorId;
IIdAtom * codepage2UnicodeId;
IIdAtom * codepage2UnicodeXId;
IIdAtom * codepageToUtf8Id;
IIdAtom * codepageToUtf8XId;
IIdAtom * codepage2VUnicodeId;
IIdAtom * codepage2VUnicodeXId;
IIdAtom * columnGetBoolId;
IIdAtom * columnGetDataId;
IIdAtom * columnGetDataXId;
IIdAtom * columnGetIntId;
IIdAtom * columnGetQStringId;
IIdAtom * columnGetSetIsAllId;
IIdAtom * columnGetStringId;
IIdAtom * columnGetStringXId;
IIdAtom * columnGetUnicodeXId;
IIdAtom * columnGetUtf8XId;
IIdAtom * columnReadBoolId;
IIdAtom * columnReadDataId;
IIdAtom * columnReadDataXId;
IIdAtom * columnReadIntId;
IIdAtom * columnReadQStringId;
IIdAtom * columnReadSetIsAllId;
IIdAtom * columnReadStringId;
IIdAtom * columnReadStringXId;
IIdAtom * columnReadUnicodeXId;
IIdAtom * columnReadUtf8XId;
IIdAtom * compareDataDataId;
IIdAtom * compareEStrEStrId;
IIdAtom * compareQStrQStrId;
IIdAtom * compareStrBlankId;
IIdAtom * compareStrStrId;
IIdAtom * compareUnicodeUnicodeId;
IIdAtom * compareUnicodeUnicodeStrengthId;
IIdAtom * compareUtf8Utf8Id;
IIdAtom * compareUtf8Utf8StrengthId;
IIdAtom * compareVStrVStrId;
IIdAtom * compareVUnicodeVUnicodeId;
IIdAtom * compareVUnicodeVUnicodeStrengthId;
IIdAtom * concatId;
IIdAtom * concatExtendId;
IIdAtom * concatStr2StrId;
IIdAtom * concatStrFId;
IIdAtom * concatStrExtendId;
IIdAtom * concatUnicodeId;
IIdAtom * concatUnicodeExtendId;
IIdAtom * concatUnicodeFId;
IIdAtom * concatUnicodeToUnicodeId;
IIdAtom * concatUtf8Id;
IIdAtom * concatUtf8ToUtf8Id;
IIdAtom * concatVStr2StrId;
IIdAtom * concatVStrId;
IIdAtom * concatVStrFId;
IIdAtom * concatVUnicodeId;
IIdAtom * concatVUnicodeFId;
IIdAtom * concatVUnicodeToUnicodeId;
IIdAtom * cosId;
IIdAtom * coshId;
IIdAtom * countProviderId;
IIdAtom * countRowsId;
IIdAtom * countToSizeId;
IIdAtom * crcDataId;
IIdAtom * crcUnicodeId;
IIdAtom * crcUtf8Id;
IIdAtom * crcVStrId;
IIdAtom * crcVUnicodeId;
IIdAtom * createBlobId;
IIdAtom * createDataRangeLowId;
IIdAtom * createDataRangeHighId;
IIdAtom * createOrderId;
IIdAtom * createQStrRangeLowId;
IIdAtom * createQStrRangeHighId;
IIdAtom * createQuotedStringId;
IIdAtom * createRangeLowId;
IIdAtom * createRangeHighId;
IIdAtom * createRealNullId;
IIdAtom * createRowFromJsonId;
IIdAtom * createRowFromXmlId;
IIdAtom * createRowStreamId;
IIdAtom * createStrRangeLowId;
IIdAtom * createStrRangeHighId;
IIdAtom * createUnicodeRangeLowId;
IIdAtom * createUnicodeRangeHighId;
IIdAtom * createRegexId;
IIdAtom * createWRegexId;
IIdAtom * csvStr2BoolId;
IIdAtom * ctxGetRowJsonId;
IIdAtom * ctxGetRowXmlId;
IIdAtom * data2BoolId;
IIdAtom * dataset2DatasetXId;
IIdAtom * dataset2RowsetXId;
IIdAtom * DecAbsId;
IIdAtom * DecAddId;
IIdAtom * DecCompareDecimalId;
IIdAtom * DecCompareUDecimalId;
IIdAtom * DecCompareNullId;
IIdAtom * DecDistinctId;
IIdAtom * DecDistinctRId;
IIdAtom * DecDivideId;
IIdAtom * DecModulusId;
IIdAtom * DecMulId;
IIdAtom * DecNegateId;
IIdAtom * DecPopDecimalId;
IIdAtom * DecPopInt64Id;
IIdAtom * DecPopLongId;
IIdAtom * DecPopRealId;
IIdAtom * DecPopStringId;
IIdAtom * DecPopStringXId;
IIdAtom * DecPopUDecimalId;
IIdAtom * DecPopVStringId;
IIdAtom * DecPopVStringXId;
IIdAtom * DecPushCStringId;
IIdAtom * DecPushDecimalId;
IIdAtom * DecPushInt64Id;
IIdAtom * DecPushLongId;
IIdAtom * DecPushQStringId;
IIdAtom * DecPushRealId;
IIdAtom * DecPushStringId;
IIdAtom * DecPushUDecimalId;
IIdAtom * DecPushUInt64Id;
IIdAtom * DecPushUnicodeId;
IIdAtom * DecPushUtf8Id;
IIdAtom * DecRoundId;
IIdAtom * DecRoundUpId;
IIdAtom * DecRoundToId;
IIdAtom * DecSetPrecisionId;
IIdAtom * DecSubId;
IIdAtom * DecTruncateId;
IIdAtom * DecTruncateAtId;
IIdAtom * DecValidId;
IIdAtom * DecValidTosId;
IIdAtom * deleteFileId;
IIdAtom * deserializeRawId;
IIdAtom * deserializeChildDictionaryFromDatasetFromStreamId;
IIdAtom * deserializeChildDictionaryFromStreamId;
IIdAtom * deserializeChildRowsetFromStreamId;
IIdAtom * deserializeCStringXId;
IIdAtom * deserializeDataXId;
IIdAtom * deserializeDatasetXId;
IIdAtom * deserializeDictionaryXId;
IIdAtom * deserializeGroupedDatasetXId;
IIdAtom * deserializeQStrXId;
IIdAtom * deserializeRowId;
IIdAtom * deserializeRowsetXId;
IIdAtom * deserializeGroupedRowsetXId;
IIdAtom * deserializeSetId;
IIdAtom * deserializeStringXId;
IIdAtom * deserializeUnicodeXId;
IIdAtom * deserializeUtf8XId;
IIdAtom * deserializeVUnicodeXId;
IIdAtom * deserializerReadNId;
IIdAtom * deserializerReadPackedIntId;
IIdAtom * deserializerReadSizeId;
IIdAtom * deserializerReadUtf8Id;
IIdAtom * deserializerReadVStrId;
IIdAtom * deserializerReadVUniId;
IIdAtom * deserializerPeekId;
IIdAtom * deserializerBeginNestedId;
IIdAtom * deserializerFinishedNestedId;
IIdAtom * deserializerSkipNId;
IIdAtom * deserializerSkipPackedIntId;
IIdAtom * deserializerSkipUtf8Id;
IIdAtom * deserializerSkipVStrId;
IIdAtom * deserializerSkipVUniId;
IIdAtom * destroyRegexId;
IIdAtom * destroyWRegexId;
IIdAtom * destructMetaMemberId;
IIdAtom * dictionaryCountId;
IIdAtom * dictionaryExistsId;
IIdAtom * dictionaryLookupId;
IIdAtom * dictionaryLookupExistsId;
IIdAtom * doNotifyId;
IIdAtom * doNotifyTargetId;
IIdAtom * ebcdic2asciiId;
IIdAtom * en2fId;
IIdAtom * en2l4Id;
IIdAtom * en2l8Id;
IIdAtom * en2ls4Id;
IIdAtom * en2ls8Id;
IIdAtom * ensureCapacityId;
IIdAtom * ensureRowAvailableId;
IIdAtom * __eogId;
IIdAtom * estr2EStrId;
IIdAtom * estr2VStrId;
IIdAtom * estr2VStrXId;
IIdAtom * evaluateChildQueryInstanceId;
IIdAtom * ex2fId;
IIdAtom * executeGraphId;
IIdAtom * executeChildQueryInstanceId;
IIdAtom * f2anId;
IIdAtom * f2axId;
IIdAtom * f2vnId;
IIdAtom * f2vxId;
IIdAtom * failDivideByZeroId;
IIdAtom * _failId;
IIdAtom * fileExistsId;
IIdAtom * finalizeRowClearId;
IIdAtom * freeId;
IIdAtom * freeExceptionId;
IIdAtom * getBytesFromBuilderId;
IIdAtom * getChildQueryDictionaryResultId;
IIdAtom * getChildQueryLinkedResultId;
IIdAtom * getChildQueryLinkedRowResultId;
IIdAtom * getClusterSizeId;
IIdAtom * getDatasetHashId;
IIdAtom * getECLId;
IIdAtom * getEnvId;
IIdAtom * getEventExtraId;
IIdAtom * getEventNameId;
IIdAtom * getExpandLogicalNameId;
IIdAtom * getExternalResultHashId;
IIdAtom * getFailMessageId;
IIdAtom * getFilePositionId;
IIdAtom * getGraphLoopCounterId;
IIdAtom * getIsValidId;
IIdAtom * getLocalDictionaryResultId;
IIdAtom * getLocalFailMessageId;
IIdAtom * getLocalFilePositionId;
IIdAtom * getLocalLinkedResultId;
IIdAtom * getLocalLinkedRowResultId;
IIdAtom * getMatchedId;
IIdAtom * getMatchLengthId;
IIdAtom * getMatchPositionId;
IIdAtom * getMatchRowId;
IIdAtom * getMatchTextId;
IIdAtom * getMatchUnicodeId;
IIdAtom * getMatchUtf8Id;
IIdAtom * getPackedSignedId;
IIdAtom * getPackedSizeId;
IIdAtom * getPackedUnsignedId;
IIdAtom * getProductionResultId;
IIdAtom * getProductionTextId;
IIdAtom * getProductionUnicodeId;
IIdAtom * getProductionUtf8Id;
IIdAtom * getResultBoolId;
IIdAtom * getResultDataId;
IIdAtom * getResultDatasetId;
IIdAtom * getResultDecimalId;
IIdAtom * getResultDictionaryId;
IIdAtom * getResultHashId;
IIdAtom * getResultIntId;
IIdAtom * getResultQStringId;
IIdAtom * getResultRealId;
IIdAtom * getResultRowsetId;
IIdAtom * getResultSetId;
IIdAtom * getResultStringId;
IIdAtom * getResultStringFId;
IIdAtom * getResultUnicodeId;
IIdAtom * getResultVarStringId;
IIdAtom * getResultVarUnicodeId;
IIdAtom * getRootResultId;
IIdAtom * getWorkflowIdId;
IIdAtom * getWuidId;
IIdAtom * groupedDataset2RowsetXId;
IIdAtom * groupedRowset2DatasetXId;
IIdAtom * hash32DataId;
IIdAtom * hash32Data1Id;
IIdAtom * hash32Data2Id;
IIdAtom * hash32Data3Id;
IIdAtom * hash32Data4Id;
IIdAtom * hash32Data5Id;
IIdAtom * hash32Data6Id;
IIdAtom * hash32Data7Id;
IIdAtom * hash32Data8Id;
IIdAtom * hash32UnicodeId;
IIdAtom * hash32Utf8Id;
IIdAtom * hash32VStrId;
IIdAtom * hash32VUnicodeId;
IIdAtom * hash64DataId;
IIdAtom * hash64UnicodeId;
IIdAtom * hash64Utf8Id;
IIdAtom * hash64VStrId;
IIdAtom * hash64VUnicodeId;
IIdAtom * hashDataId;
IIdAtom * hashDataNCId;
IIdAtom * hashMd5FinishId;
IIdAtom * hashMd5InitId;
IIdAtom * hashMd5DataId;
IIdAtom * hashUnicodeId;
IIdAtom * hashUtf8Id;
IIdAtom * hashVStrId;
IIdAtom * hashVStrNCId;
IIdAtom * hashVUnicodeId;
IIdAtom * IIndirectMemberVisitor_visitRowId;
IIdAtom * IIndirectMemberVisitor_visitRowsetId;
IIdAtom * initProcessId;
IIdAtom * intFormatId;
IIdAtom * isResultId;
IIdAtom * keyUnicodeXId;
IIdAtom * keyUnicodeStrengthXId;
IIdAtom * killRangeId;
IIdAtom * l42anId;
IIdAtom * l42axId;
IIdAtom * l42vnId;
IIdAtom * l42vxId;
IIdAtom * l82anId;
IIdAtom * l82axId;
IIdAtom * l82vnId;
IIdAtom * l82vxId;
IIdAtom * linkdataset2linkdatasetId;
IIdAtom * linkRowId;
IIdAtom * linkRowsetId;
IIdAtom * lnId;
IIdAtom * loadResourceId;
IIdAtom * log10Id;
IIdAtom * lookupBlobId;
IIdAtom * ls42anId;
IIdAtom * ls42axId;
IIdAtom * ls42vnId;
IIdAtom * ls42vxId;
IIdAtom * ls82anId;
IIdAtom * ls82axId;
IIdAtom * ls82vnId;
IIdAtom * ls82vxId;
IIdAtom * memcmpId;
IIdAtom * memcpyId;
IIdAtom * memsetId;
IIdAtom * newWhenActionArgId;
IIdAtom * newCountAggregateArgId;
IIdAtom * newDegroupArgId;
IIdAtom * newExistsAggregateArgId;
IIdAtom * newFunnelArgId;
IIdAtom * newGraphLoopResultWriteArgId;
IIdAtom * newLibraryConstantRawIteratorArgId;
IIdAtom * newLocalResultReadArgId;
IIdAtom * newLocalResultSpillArgId;
IIdAtom * newMemorySpillReadArgId;
IIdAtom * newMemorySpillSplitArgId;
IIdAtom * newNullArgId;
IIdAtom * newSelectNArgId;
IIdAtom * newSplitArgId;
IIdAtom * newWorkUnitReadArgId;
IIdAtom * newWorkUnitWriteArgId;
IIdAtom * offsetProviderId;
IIdAtom * outputXmlBeginNestedId;
IIdAtom * outputXmlBeginArrayId;
IIdAtom * outputXmlBoolId;
IIdAtom * outputXmlDataId;
IIdAtom * outputXmlDecimalId;
IIdAtom * outputXmlEndArrayId;
IIdAtom * outputXmlEndNestedId;
IIdAtom * outputXmlIntId;
IIdAtom * outputXmlQStringId;
IIdAtom * outputXmlRealId;
IIdAtom * outputXmlSetAllId;
IIdAtom * outputXmlStringId;
IIdAtom * outputXmlUIntId;
IIdAtom * outputXmlUnicodeId;
IIdAtom * outputXmlUtf8Id;
IIdAtom * powerId;
IIdAtom * prefixDiffStrId;
IIdAtom * prefixDiffUnicodeId;
IIdAtom * processFieldBoolId;
IIdAtom * processFieldDataId;
IIdAtom * processFieldDecimalId;
IIdAtom * processFieldIntId;
IIdAtom * processFieldQStringId;
IIdAtom * processFieldRealId;
IIdAtom * processFieldStringId;
IIdAtom * processFieldUIntId;
IIdAtom * processFieldUnicodeId;
IIdAtom * processFieldUtf8Id;
IIdAtom * processFieldSetAllId;
IIdAtom * processFieldBeginSetId;
IIdAtom * processFieldBeginDatasetId;
IIdAtom * processFieldBeginRowId;
IIdAtom * processFieldEndSetId;
IIdAtom * processFieldEndDatasetId;
IIdAtom * processFieldEndRowId;
IIdAtom * qstr2BoolId;
IIdAtom * qstr2DataId;
IIdAtom * qstr2DataXId;
IIdAtom * qstrToQStrId;
IIdAtom * qstrToQStrXId;
IIdAtom * qstr2StrId;
IIdAtom * qstr2StrXId;
IIdAtom * qstr2VStrId;
IIdAtom * qstrLengthId;
IIdAtom * qstrSizeId;
IIdAtom * queryFailCodeId;
IIdAtom * queryLocalFailCodeId;
IIdAtom * queryLocalResultId;
IIdAtom * queryLogicalFilenameId;
IIdAtom * rankedFromOrderId;
IIdAtom * rankFromOrderId;
IIdAtom * readIntId[9][2];
IIdAtom * readSwapIntId[9][2];
IIdAtom * realFormatId;
IIdAtom * regexFindXId;
IIdAtom * regexGetFindStrId;
IIdAtom * regexNewSetStrPatternId;
IIdAtom * regexNewSetUStrPatternId;
IIdAtom * regexNewStrFindId;
IIdAtom * regexNewStrFoundId;
IIdAtom * regexNewStrFoundXId;
IIdAtom * regexNewStrReplaceXId;
IIdAtom * regexNewUStrFindId;
IIdAtom * regexNewUStrFoundId;
IIdAtom * regexNewUStrFoundXId;
IIdAtom * regexNewUStrReplaceXId;
IIdAtom * regexReplaceXId;
IIdAtom * releaseRowId;
IIdAtom * releaseRowsetId;
IIdAtom * reportFieldOverflowId;
IIdAtom * reportRowOverflowId;
IIdAtom * responseinfoId;
IIdAtom * restoreClusterId;
IIdAtom * returnPersistVersionId;
IIdAtom * reverseIntId[9][2];
IIdAtom * roundId;
IIdAtom * roundToId;
IIdAtom * roundupId;
IIdAtom * rowset2DatasetXId;
IIdAtom * rtlCopyRowLinkChildrenId;
IIdAtom * rtlDeserializeDictionaryId;
IIdAtom * rtlDeserializeDictionaryFromDatasetId;
IIdAtom * rtlDeserializeRowId;
IIdAtom * rtlDeserializeToBuilderId;
IIdAtom * rtlLinkChildrenId;
IIdAtom * rtlMaxId;
IIdAtom * rtlMinId;
IIdAtom * rtlRandomId;
IIdAtom * rtlSerializeDictionaryId;
IIdAtom * rtlSerializeDictionaryToDatasetId;
IIdAtom * rtlSerializeToBuilderId;
IIdAtom * searchTableInteger4Id;
IIdAtom * searchTableInteger8Id;
IIdAtom * searchTableUInteger4Id;
IIdAtom * searchTableUInteger8Id;
IIdAtom * searchUnicodeTableId;
IIdAtom * searchUtf8TableId;
IIdAtom * searchVUnicodeTableId;
IIdAtom * selectClusterId;
IIdAtom * serializeChildDictionaryToStreamId;
IIdAtom * serializeChildDictionaryToDatasetToStreamId;
IIdAtom * serializeChildRowsetToStreamId;
IIdAtom * serializeCStringXId;
IIdAtom * serializeDataXId;
IIdAtom * serializeDatasetXId;
IIdAtom * serializeGroupedDatasetXId;
IIdAtom * serializeStringXId;
IIdAtom * serializeBoolId;
IIdAtom * serializeDictionaryXId;
IIdAtom * serializeFixedDataId;
IIdAtom * serializeFixedStringId;
IIdAtom * serializeLPDataId;
IIdAtom * serializeLPQStringId;
IIdAtom * serializeLPStringId;
IIdAtom * serializeQStrXId;
IIdAtom * serializeRawId;
IIdAtom * serializeReal4Id;
IIdAtom * serializeReal8Id;
IIdAtom * serializeRowId;
IIdAtom * serializeRowsetXId;
IIdAtom * serializeGroupedRowsetXId;
IIdAtom * serializeSetId;
IIdAtom * serializeUnicodeXId;
IIdAtom * serializeUtf8XId;
IIdAtom * serializerPutId;
IIdAtom * serializerBeginNestedId;
IIdAtom * serializerEndNestedId;
IIdAtom * setConditionCodeId;
IIdAtom * setMethodId;
IIdAtom * setOwnMethodId;
IIdAtom * setPackedSignedId;
IIdAtom * setPackedUnsignedId;
IIdAtom * setResultBoolId;
IIdAtom * setResultDataId;
IIdAtom * setResultDatasetId;
IIdAtom * setResultDecimalId;
IIdAtom * setResultIntId;
IIdAtom * setResultQStringId;
IIdAtom * setResultRawId;
IIdAtom * setResultRealId;
IIdAtom * setResultSetId;
IIdAtom * setResultStringId;
IIdAtom * setResultUIntId;
IIdAtom * setResultUnicodeId;
IIdAtom * setResultVarStringId;
IIdAtom * setResultVarUnicodeId;
IIdAtom * setWorkflowConditionId;
IIdAtom * set2SetXId;
IIdAtom * sinId;
IIdAtom * sinhId;
IIdAtom * sqrtId;
IIdAtom * str2DataId;
IIdAtom * str2DataXId;
IIdAtom * strToQStrId;
IIdAtom * strToQStrXId;
IIdAtom * str2StrId;
IIdAtom * str2StrXId;
IIdAtom * str2VStrId;
IIdAtom * str2VStrXId;
IIdAtom * strcpyId;
IIdAtom * strlenId;
IIdAtom * subDataFTId;
IIdAtom * subDataFTXId;
IIdAtom * subDataFXId;
IIdAtom * subQStrFTId;
IIdAtom * subQStrFTXId;
IIdAtom * subQStrFXId;
IIdAtom * subStrFTId;
IIdAtom * subStrFTXId;
IIdAtom * subStrFXId;
IIdAtom * sysFailId;
IIdAtom * tanId;
IIdAtom * tanhId;
IIdAtom * trimAllId;
IIdAtom * trimBothId;
IIdAtom * trimLeftId;
IIdAtom * trimRightId;
IIdAtom * trimStrLenId;
IIdAtom * trimUnicodeAllId;
IIdAtom * trimUnicodeBothId;
IIdAtom * trimUnicodeLeftId;
IIdAtom * trimUnicodeRightId;
IIdAtom * trimUnicodeStrLenId;
IIdAtom * trimUtf8AllId;
IIdAtom * trimUtf8BothId;
IIdAtom * trimUtf8LeftId;
IIdAtom * trimUtf8RightId;
IIdAtom * trimUtf8StrLenId;
IIdAtom * trimVAllId;
IIdAtom * trimVBothId;
IIdAtom * trimVLeftId;
IIdAtom * trimVRightId;
IIdAtom * trimVStrLenId;
IIdAtom * trimVUnicodeAllId;
IIdAtom * trimVUnicodeBothId;
IIdAtom * trimVUnicodeLeftId;
IIdAtom * trimVUnicodeRightId;
IIdAtom * trimVUnicodeStrLenId;
IIdAtom * truncateId;
IIdAtom * UCharId;
IIdAtom * unicode2CodepageId;
IIdAtom * unicode2CodepageXId;
IIdAtom * unicode2DataId;
IIdAtom * unicode2DataXId;
IIdAtom * unicode2UnicodeId;
IIdAtom * unicode2UnicodeXId;
IIdAtom * unicodeToUtf8Id;
IIdAtom * unicodeToUtf8XId;
IIdAtom * unicode2VCodepageId;
IIdAtom * unicode2VCodepageXId;
IIdAtom * unicode2VUnicodeId;
IIdAtom * unicode2VUnicodeXId;
IIdAtom * unicodeNullTerminateId;
IIdAtom * unicodeStrcpyId;
IIdAtom * unicodeStrlenId;
IIdAtom * unicodeSubStrFXId;
IIdAtom * unicodeSubStrFTXId;
IIdAtom * utf82CodepageId;
IIdAtom * utf82CodepageXId;
IIdAtom * utf82DataId;
IIdAtom * utf82DataXId;
IIdAtom * utf82UnicodeId;
IIdAtom * utf82UnicodeXId;
IIdAtom * utf8ToUtf8Id;
IIdAtom * utf8ToUtf8XId;
IIdAtom * utf8LengthId;
IIdAtom * utf8SizeId;
IIdAtom * utf8SubStrFTXId;
IIdAtom * utf8SubStrFXId;
IIdAtom * validRealId;
IIdAtom * vcodepage2UnicodeId;
IIdAtom * vcodepage2UnicodeXId;
IIdAtom * vcodepage2VUnicodeId;
IIdAtom * vcodepage2VUnicodeXId;
IIdAtom * vn2bId;
IIdAtom * vn2fId;
IIdAtom * vn2l4Id;
IIdAtom * vn2l8Id;
IIdAtom * vn2ls4Id;
IIdAtom * vn2ls8Id;
IIdAtom * vstr2DataId;
IIdAtom * vstr2StrId;
IIdAtom * vstr2VStrId;
IIdAtom * vunicode2CodepageId;
IIdAtom * vunicode2CodepageXId;
IIdAtom * vunicode2DataId;
IIdAtom * vunicode2DataXId;
IIdAtom * vunicode2UnicodeId;
IIdAtom * vunicode2UnicodeXId;
IIdAtom * vunicode2VCodepageId;
IIdAtom * vunicode2VCodepageXId;
IIdAtom * vunicode2VUnicodeId;
IIdAtom * vunicode2VUnicodeXId;
IIdAtom * walkIndirectMetaMemberId;
IIdAtom * wregexFindXId;
IIdAtom * wregexGetFindStrId;
IIdAtom * wregexReplaceXId;
IIdAtom * writeEbcdicId;
IIdAtom * writeIntId[9];
IIdAtom * writeRealId;
IIdAtom * writeSignedId;
IIdAtom * writeStringId;
IIdAtom * writeUnicodeId;
IIdAtom * writeUnsignedId;
IIdAtom * writeUtf8Id;
IIdAtom * xmlDecodeStrId;
IIdAtom * xmlDecodeUStrId;
IIdAtom * xmlEncodeStrId;
IIdAtom * xmlEncodeUStrId;
//===========================================================================
//MORE: Need to change many MAKEATOM to MAKEID in this file, and most of the explicit calls should be removed/changed
#define MAKEID(x) x##Id = createIdAtom(#x)
#define MAKEATOM(x) x##Atom = createLowerCaseAtom(#x)
#define MAKESYSATOM(x) _##x##_Atom = createLowerCaseAtom("$_" #x "_")
MODULE_INIT(INIT_PRIORITY_HQLATOM-1)
{
MAKEID(clibExp);
MAKEID(_fail);
acosId = createIdAtom("_acos");
MAKEID(addAggregateRow);
MAKEID(addAll);
MAKEID(addRange);
MAKEID(addWorkunitAssertFailure);
MAKEID(an2b);
MAKEID(an2f);
MAKEID(an2l4);
MAKEID(an2l8);
MAKEID(an2ls4);
MAKEID(an2ls8);
MAKEID(appendRowsToRowset);
MAKEID(appendSetX);
MAKEID(ascii2ebcdic);
asinId = createIdAtom("_asin");
atan2Id = createIdAtom("_atan2");
atanId = createIdAtom("_atan");
MAKEID(bool2Data);
MAKEID(bool2Str);
MAKEID(bool2StrX);
MAKEID(bool2VStr);
MAKEID(bool2VStrX);
_clear(castIntId);
castIntId[3][true] = createIdAtom("castInt3");
castIntId[5][true] = createIdAtom("castInt5");
castIntId[6][true] = createIdAtom("castInt6");
castIntId[7][true] = createIdAtom("castInt7");
castIntId[3][false] = createIdAtom("castUInt3");
castIntId[5][false] = createIdAtom("castUInt5");
castIntId[6][false] = createIdAtom("castUInt6");
castIntId[7][false] = createIdAtom("castUInt7");
MAKEID(checkFieldOverflow);
MAKEID(checkRowOverflow);
MAKEID(cloneVString);
MAKEID(cloneVStringX);
MAKEID(codeGenerator);
MAKEID(codepage2Unicode);
MAKEID(codepage2UnicodeX);
MAKEID(codepageToUtf8);
MAKEID(codepageToUtf8X);
MAKEID(codepage2VUnicode);
MAKEID(codepage2VUnicodeX);
MAKEID(columnGetBool);
MAKEID(columnGetData);
MAKEID(columnGetDataX);
MAKEID(columnGetInt);
MAKEID(columnGetQString);
MAKEID(columnGetSetIsAll);
MAKEID(columnGetString);
MAKEID(columnGetStringX);
MAKEID(columnGetUnicodeX);
MAKEID(columnGetUtf8X);
MAKEID(columnReadBool);
MAKEID(columnReadData);
MAKEID(columnReadDataX);
MAKEID(columnReadInt);
MAKEID(columnReadQString);
MAKEID(columnReadSetIsAll);
MAKEID(columnReadString);
MAKEID(columnReadStringX);
MAKEID(columnReadUnicodeX);
MAKEID(columnReadUtf8X);
MAKEID(compareDataData);
MAKEID(compareEStrEStr);
MAKEID(compareQStrQStr);
MAKEID(compareStrBlank);
MAKEID(compareStrStr);
MAKEID(compareUnicodeUnicode);
MAKEID(compareUnicodeUnicodeStrength);
MAKEID(compareUtf8Utf8);
MAKEID(compareUtf8Utf8Strength);
MAKEID(compareVStrVStr);
MAKEID(compareVUnicodeVUnicode);
MAKEID(compareVUnicodeVUnicodeStrength);
MAKEID(concat);
MAKEID(concatExtend);
MAKEID(concatStr2Str);
MAKEID(concatStrExtend);
MAKEID(concatStrF);
MAKEID(concatUnicode);
MAKEID(concatUnicodeExtend);
MAKEID(concatUnicodeF);
MAKEID(concatUnicodeToUnicode);
MAKEID(concatUtf8);
MAKEID(concatUtf8ToUtf8);
MAKEID(concatVStr2Str);
MAKEID(concatVStr);
MAKEID(concatVStrF);
MAKEID(concatVUnicode);
MAKEID(concatVUnicodeF);
MAKEID(concatVUnicodeToUnicode);
cosId = createIdAtom("_cos");
coshId = createIdAtom("_cosh");
MAKEID(countProvider);
MAKEID(countRows);
MAKEID(countToSize);
MAKEID(crcData);
MAKEID(crcUnicode);
MAKEID(crcUtf8);
MAKEID(crcVStr);
MAKEID(crcVUnicode);
MAKEID(createBlob);
MAKEID(createDataRangeLow);
MAKEID(createDataRangeHigh);
MAKEID(createOrder);
MAKEID(createQStrRangeLow);
MAKEID(createQStrRangeHigh);
MAKEID(createQuotedString);
MAKEID(createRangeLow);
MAKEID(createRangeHigh);
MAKEID(createRealNull);
MAKEID(createRegex);
MAKEID(createRowFromJson);
MAKEID(createRowFromXml);
MAKEID(createRowStream);
MAKEID(createStrRangeLow);
MAKEID(createStrRangeHigh);
MAKEID(createUnicodeRangeLow);
MAKEID(createUnicodeRangeHigh);
MAKEID(createWRegex);
MAKEID(csvStr2Bool);
MAKEID(ctxGetRowJson);
MAKEID(ctxGetRowXml);
MAKEID(data2Bool);
MAKEID(dataset2DatasetX);
MAKEID(dataset2RowsetX);
MAKEID(DecAbs);
MAKEID(DecAdd);
MAKEID(DecCompareDecimal);
MAKEID(DecCompareUDecimal);
MAKEID(DecCompareNull);
MAKEID(DecDistinct);
MAKEID(DecDistinctR);
MAKEID(DecDivide);
MAKEID(DecModulus);
MAKEID(DecMul);
MAKEID(DecNegate);
MAKEID(DecPopDecimal);
MAKEID(DecPopInt64);
MAKEID(DecPopLong);
MAKEID(DecPopReal);
MAKEID(DecPopString);
MAKEID(DecPopStringX);
MAKEID(DecPopUDecimal);
MAKEID(DecPopVString);
MAKEID(DecPopVStringX);
MAKEID(DecPushCString);
MAKEID(DecPushDecimal);
MAKEID(DecPushInt64);
MAKEID(DecPushLong);
MAKEID(DecPushReal);
MAKEID(DecPushQString);
MAKEID(DecPushString);
MAKEID(DecPushUDecimal);
MAKEID(DecPushUInt64);
MAKEID(DecPushUnicode);
MAKEID(DecPushUtf8);
MAKEID(DecRound);
MAKEID(DecRoundUp);
MAKEID(DecRoundTo);
MAKEID(DecSetPrecision);
MAKEID(DecSub);
MAKEID(DecTruncate);
MAKEID(DecTruncateAt);
MAKEID(DecValid);
MAKEID(DecValidTos);
MAKEID(deleteFile);
MAKEID(deserializeRaw);
MAKEID(deserializeChildDictionaryFromStream);
MAKEID(deserializeChildDictionaryFromDatasetFromStream);
MAKEID(deserializeChildRowsetFromStream);
MAKEID(deserializeCStringX);
MAKEID(deserializeDataX);
MAKEID(deserializeDatasetX);
MAKEID(deserializeDictionaryX);
MAKEID(deserializeGroupedDatasetX);
MAKEID(deserializeQStrX);
MAKEID(deserializeRow);
MAKEID(deserializeRowsetX);
MAKEID(deserializeGroupedRowsetX);
MAKEID(deserializeSet);
MAKEID(deserializeStringX);
MAKEID(deserializeUnicodeX);
MAKEID(deserializeUtf8X);
MAKEID(deserializeVUnicodeX);
MAKEID(deserializerReadN);
MAKEID(deserializerReadPackedInt);
MAKEID(deserializerReadSize);
MAKEID(deserializerReadUtf8);
MAKEID(deserializerReadVStr);
MAKEID(deserializerReadVUni);
MAKEID(deserializerPeek);
MAKEID(deserializerBeginNested);
MAKEID(deserializerFinishedNested);
MAKEID(deserializerSkipN);
MAKEID(deserializerSkipPackedInt);
MAKEID(deserializerSkipUtf8);
MAKEID(deserializerSkipVStr);
MAKEID(deserializerSkipVUni);
MAKEID(destroyRegex);
MAKEID(destroyWRegex);
MAKEID(destructMetaMember);
MAKEID(dictionaryCount);
MAKEID(dictionaryExists);
MAKEID(dictionaryLookup);
MAKEID(dictionaryLookupExists);
MAKEID(doNotify);
MAKEID(doNotifyTarget);
MAKEID(ebcdic2ascii);
MAKEID(en2f);
MAKEID(en2l4);
MAKEID(en2l8);
MAKEID(en2ls4);
MAKEID(en2ls8);
MAKEID(ensureCapacity);
MAKEID(ensureRowAvailable);
MAKEID(__eog);
estr2EStrId = createIdAtom("eStr2EStr");
estr2VStrId = createIdAtom("eStr2VStr");
estr2VStrXId = createIdAtom("EStr2VStrX");
MAKEID(evaluateChildQueryInstance);
MAKEID(ex2f);
MAKEID(executeGraph);
MAKEID(executeChildQueryInstance);
MAKEID(f2an);
f2axId = createIdAtom("_f2ax");
MAKEID(f2vn);
MAKEID(f2vx);
MAKEID(failDivideByZero);
MAKEID(fileExists);
MAKEID(finalizeRowClear);
MAKEID(free);
MAKEID(freeException);
MAKEID(getBytesFromBuilder);
MAKEID(getChildQueryDictionaryResult);
MAKEID(getChildQueryLinkedResult);
MAKEID(getChildQueryLinkedRowResult);
MAKEID(getClusterSize);
MAKEID(getDatasetHash);
MAKEID(getECL);
MAKEID(getEnv);
MAKEID(getEventExtra);
MAKEID(getEventName);
MAKEID(getExpandLogicalName);
MAKEID(getExternalResultHash);
MAKEID(getFailMessage);
MAKEID(getFilePosition);
MAKEID(getGraphLoopCounter);
MAKEID(getIsValid);
MAKEID(getLocalDictionaryResult);
MAKEID(getLocalFailMessage);
MAKEID(getLocalFilePosition);
MAKEID(getLocalLinkedResult);
MAKEID(getLocalLinkedRowResult);
MAKEID(getMatched);
MAKEID(getMatchLength);
MAKEID(getMatchPosition);
MAKEID(getMatchRow);
MAKEID(getMatchText);
MAKEID(getMatchUnicode);
MAKEID(getMatchUtf8);
MAKEID(getPackedSigned);
MAKEID(getPackedSize);
MAKEID(getPackedUnsigned);
MAKEID(getProductionResult);
MAKEID(getProductionText);
MAKEID(getProductionUnicode);
MAKEID(getProductionUtf8);
MAKEID(getResultBool);
MAKEID(getResultData);
MAKEID(getResultDataset);
MAKEID(getResultDecimal);
MAKEID(getResultDictionary);
MAKEID(getResultHash);
MAKEID(getResultInt);
MAKEID(getResultQString);
MAKEID(getResultReal);
MAKEID(getResultRowset);
MAKEID(getResultSet);
MAKEID(getResultString);
MAKEID(getResultStringF);
MAKEID(getResultUnicode);
MAKEID(getResultVarString);
MAKEID(getResultVarUnicode);
MAKEID(getRootResult);
MAKEID(getWorkflowId);
MAKEID(getWuid);
MAKEID(groupedDataset2RowsetX);
MAKEID(groupedRowset2DatasetX);
MAKEID(hash32Data);
MAKEID(hash32Data1);
MAKEID(hash32Data2);
MAKEID(hash32Data3);
MAKEID(hash32Data4);
MAKEID(hash32Data5);
MAKEID(hash32Data6);
MAKEID(hash32Data7);
MAKEID(hash32Data8);
MAKEID(hash32VStr);
MAKEID(hash32Unicode);
MAKEID(hash32Utf8);
MAKEID(hash32VUnicode);
MAKEID(hash64Data);
MAKEID(hash64VStr);
MAKEID(hash64Unicode);
MAKEID(hash64Utf8);
MAKEID(hash64VUnicode);
MAKEID(hashData);
MAKEID(hashDataNC);
MAKEID(hashMd5Finish);
MAKEID(hashMd5Init);
MAKEID(hashMd5Data);
MAKEID(hashVStr);
MAKEID(hashVStrNC);
MAKEID(hashUnicode);
MAKEID(hashUtf8);
MAKEID(hashVUnicode);
MAKEID(IIndirectMemberVisitor_visitRow);
MAKEID(IIndirectMemberVisitor_visitRowset);
intFormatId = createIdAtom("_intformat");
MAKEID(isResult);
MAKEID(keyUnicodeX);
MAKEID(keyUnicodeStrengthX);
MAKEID(killRange);
MAKEID(l42an);
MAKEID(l42ax);
MAKEID(l42vn);
MAKEID(l42vx);
MAKEID(l82an);
MAKEID(l82ax);
MAKEID(l82vn);
MAKEID(l82vx);
MAKEID(linkdataset2linkdataset);
MAKEID(linkRow);
MAKEID(linkRowset);
lnId = createIdAtom("_ln");
MAKEID(loadResource);
MAKEID(lookupBlob);
log10Id = createIdAtom("_log10");
MAKEID(ls42an);
MAKEID(ls42ax);
MAKEID(ls42vn);
MAKEID(ls42vx);
MAKEID(ls82an);
MAKEID(ls82ax);
MAKEID(ls82vn);
MAKEID(ls82vx);
MAKEID(memcmp);
MAKEID(memcpy);
MAKEID(memset);
MAKEID(newWhenActionArg);
MAKEID(newCountAggregateArg);
MAKEID(newDegroupArg);
MAKEID(newExistsAggregateArg);
MAKEID(newFunnelArg);
MAKEID(newGraphLoopResultWriteArg);
MAKEID(newLibraryConstantRawIteratorArg);
MAKEID(newLocalResultReadArg);
MAKEID(newLocalResultSpillArg);
MAKEID(newMemorySpillReadArg);
MAKEID(newMemorySpillSplitArg);
MAKEID(newNullArg);
MAKEID(newSelectNArg);
MAKEID(newSplitArg);
MAKEID(newWorkUnitReadArg);
MAKEID(newWorkUnitWriteArg);
MAKEID(offsetProvider);
MAKEID(outputXmlBeginArray);
MAKEID(outputXmlBeginNested);
MAKEID(outputXmlBool);
MAKEID(outputXmlData);
MAKEID(outputXmlDecimal);
MAKEID(outputXmlEndArray);
MAKEID(outputXmlEndNested);
MAKEID(outputXmlInt);
MAKEID(outputXmlQString);
MAKEID(outputXmlReal);
MAKEID(outputXmlSetAll);
MAKEID(outputXmlString);
MAKEID(outputXmlUInt);
MAKEID(outputXmlUnicode);
MAKEID(outputXmlUtf8);
powerId = createIdAtom("_power");
MAKEID(prefixDiffStr);
MAKEID(prefixDiffUnicode);
MAKEID(processFieldBool);
MAKEID(processFieldData);
MAKEID(processFieldDecimal);
MAKEID(processFieldInt);
MAKEID(processFieldQString);
MAKEID(processFieldReal);
MAKEID(processFieldString);
MAKEID(processFieldUInt);
MAKEID(processFieldUnicode);
MAKEID(processFieldUtf8);
MAKEID(processFieldSetAll);
MAKEID(processFieldBeginSet);
MAKEID(processFieldBeginDataset);
MAKEID(processFieldBeginRow);
MAKEID(processFieldEndSet);
MAKEID(processFieldEndDataset);
MAKEID(processFieldEndRow);
MAKEID(qstr2Bool);
MAKEID(qstr2Data);
MAKEID(qstr2DataX);
MAKEID(qstrToQStr);
MAKEID(qstrToQStrX);
MAKEID(qstr2Str);
MAKEID(qstr2StrX);
MAKEID(qstr2VStr);
MAKEID(qstrLength);
MAKEID(qstrSize);
MAKEID(queryFailCode);
MAKEID(queryLocalFailCode);
MAKEID(queryLocalResult);
MAKEID(queryLogicalFilename);
MAKEID(rankedFromOrder);
MAKEID(rankFromOrder);
readIntId[3][true] = createIdAtom("readInt3");
readIntId[5][true] = createIdAtom("readInt5");
readIntId[6][true] = createIdAtom("readInt6");
readIntId[7][true] = createIdAtom("readInt7");
readIntId[3][false] = createIdAtom("readUInt3");
readIntId[5][false] = createIdAtom("readUInt5");
readIntId[6][false] = createIdAtom("readUInt6");
readIntId[7][false] = createIdAtom("readUInt7");
readSwapIntId[3][true] = createIdAtom("readSwapInt3");
readSwapIntId[5][true] = createIdAtom("readSwapInt5");
readSwapIntId[6][true] = createIdAtom("readSwapInt6");
readSwapIntId[7][true] = createIdAtom("readSwapInt7");
readSwapIntId[3][false] = createIdAtom("readSwapUInt3");
readSwapIntId[5][false] = createIdAtom("readSwapUInt5");
readSwapIntId[6][false] = createIdAtom("readSwapUInt6");
readSwapIntId[7][false] = createIdAtom("readSwapUInt7");
realFormatId = createIdAtom("_realformat");
MAKEID(regexFindX);
MAKEID(regexGetFindStr);
MAKEID(regexNewSetStrPattern);
MAKEID(regexNewSetUStrPattern);
MAKEID(regexNewStrFind);
MAKEID(regexNewStrFound);
MAKEID(regexNewStrFoundX);
MAKEID(regexNewStrReplaceX);
MAKEID(regexNewUStrFind);
MAKEID(regexNewUStrFound);
MAKEID(regexNewUStrFoundX);
MAKEID(regexNewUStrReplaceX);
MAKEID(regexReplaceX);
MAKEID(releaseRow);
MAKEID(releaseRowset);
MAKEID(reportFieldOverflow);
MAKEID(reportRowOverflow);
MAKEID(responseinfo);
MAKEID(restoreCluster);
MAKEID(returnPersistVersion);
reverseIntId[2][false] = createIdAtom("revUInt2");
reverseIntId[3][false] = createIdAtom("revUInt3");
reverseIntId[4][false] = createIdAtom("revUInt4");
reverseIntId[5][false] = createIdAtom("revUInt5");
reverseIntId[6][false] = createIdAtom("revUInt6");
reverseIntId[7][false] = createIdAtom("revUInt7");
reverseIntId[8][false] = createIdAtom("revUInt8");
reverseIntId[2][true] = createIdAtom("revInt2");
reverseIntId[3][true] = createIdAtom("revInt3");
reverseIntId[4][true] = createIdAtom("revInt4");
reverseIntId[5][true] = createIdAtom("revInt5");
reverseIntId[6][true] = createIdAtom("revInt6");
reverseIntId[7][true] = createIdAtom("revInt7");
reverseIntId[8][true] = createIdAtom("revInt8");
roundId = createIdAtom("_round");
MAKEID(roundTo);
roundupId = createIdAtom("_roundup");
MAKEID(rowset2DatasetX);
MAKEID(rtlCopyRowLinkChildren);
MAKEID(rtlDeserializeDictionary);
MAKEID(rtlDeserializeDictionaryFromDataset);
MAKEID(rtlDeserializeRow);
MAKEID(rtlDeserializeToBuilder);
MAKEID(rtlLinkChildren);
MAKEID(rtlMax);
MAKEID(rtlMin);
MAKEID(rtlRandom);
MAKEID(rtlSerializeDictionary);
MAKEID(rtlSerializeDictionaryToDataset);
MAKEID(rtlSerializeToBuilder);
MAKEID(searchTableInteger4);
MAKEID(searchTableInteger8);
MAKEID(searchTableUInteger4);
MAKEID(searchTableUInteger8);
MAKEID(searchUnicodeTable);
MAKEID(searchVUnicodeTable);
MAKEID(searchUtf8Table);
MAKEID(selectCluster);
MAKEID(serializeBool);
MAKEID(serializeChildDictionaryToStream);
MAKEID(serializeChildDictionaryToDatasetToStream);
MAKEID(serializeChildRowsetToStream);
MAKEID(serializeCStringX);
MAKEID(serializeDataX);
MAKEID(serializeDatasetX);
MAKEID(serializeStringX);
MAKEID(serializeDictionaryX);
MAKEID(serializeFixedData);
MAKEID(serializeFixedString);
MAKEID(serializeGroupedDatasetX);
MAKEID(serializeGroupedRowsetX);
MAKEID(serializeLPData);
MAKEID(serializeLPQString);
MAKEID(serializeLPString);
MAKEID(serializeQStrX);
MAKEID(serializeRaw);
MAKEID(serializeReal4);
MAKEID(serializeReal8);
MAKEID(serializeRow);
MAKEID(serializeRowsetX);
MAKEID(serializeSet);
MAKEID(serializeUnicodeX);
MAKEID(serializeUtf8X);
MAKEID(serializerPut);
MAKEID(serializerBeginNested);
MAKEID(serializerEndNested);
MAKEID(setConditionCode);
MAKEID(setMethod);
MAKEID(setOwnMethod);
MAKEID(setPackedSigned);
MAKEID(setPackedUnsigned);
MAKEID(setResultBool);
MAKEID(setResultData);
MAKEID(setResultDataset);
MAKEID(setResultDecimal);
MAKEID(setResultInt);
MAKEID(setResultQString);
MAKEID(setResultRaw);;
MAKEID(setResultReal);
MAKEID(setResultSet);
MAKEID(setResultString);
MAKEID(setResultUInt);
MAKEID(setResultUnicode);
MAKEID(setResultVarString);
MAKEID(setResultVarUnicode);
MAKEID(setWorkflowCondition);
MAKEID(set2SetX);
sinId = createIdAtom("_sin");
sinhId = createIdAtom("_sinh");
sqrtId = createIdAtom("_sqrt");
MAKEID(str2Data);
MAKEID(str2DataX);
MAKEID(strToQStr);
MAKEID(strToQStrX);
MAKEID(str2Str);
MAKEID(str2StrX);
MAKEID(str2VStr);
MAKEID(str2VStrX);
MAKEID(strcpy);
MAKEID(strlen);
MAKEID(subDataFT);
MAKEID(subDataFTX);
MAKEID(subDataFX);
MAKEID(subQStrFT);
MAKEID(subQStrFTX);
MAKEID(subQStrFX);
MAKEID(subStrFX);
MAKEID(subStrFT);
MAKEID(subStrFTX);
MAKEID(sysFail);
tanId = createIdAtom("_tan");
tanhId = createIdAtom("_tanh");
MAKEID(trimAll);
MAKEID(trimBoth);
MAKEID(trimLeft);
MAKEID(trimRight);
MAKEID(trimStrLen);
MAKEID(trimUnicodeAll);
MAKEID(trimUnicodeBoth);
MAKEID(trimUnicodeLeft);
MAKEID(trimUnicodeRight);
MAKEID(trimUnicodeStrLen);
MAKEID(trimUtf8All);
MAKEID(trimUtf8Both);
MAKEID(trimUtf8Left);
MAKEID(trimUtf8Right);
MAKEID(trimUtf8StrLen);
MAKEID(trimVAll);
MAKEID(trimVBoth);
MAKEID(trimVLeft);
MAKEID(trimVRight);
MAKEID(trimVStrLen);
MAKEID(trimVUnicodeAll);
MAKEID(trimVUnicodeBoth);
MAKEID(trimVUnicodeLeft);
MAKEID(trimVUnicodeRight);
MAKEID(trimVUnicodeStrLen);
truncateId = createIdAtom("_truncate");
MAKEID(UChar);
MAKEID(unicode2Codepage);
MAKEID(unicode2CodepageX);
MAKEID(unicode2Data);
MAKEID(unicode2DataX);
MAKEID(unicode2CodepageX);
MAKEID(unicode2Unicode);
MAKEID(unicode2UnicodeX);
MAKEID(unicodeToUtf8);
MAKEID(unicodeToUtf8X);
MAKEID(unicode2VCodepage);
MAKEID(unicode2VCodepageX);
MAKEID(unicode2VUnicode);
MAKEID(unicode2VUnicodeX);
MAKEID(unicodeNullTerminate);
MAKEID(unicodeStrcpy);
MAKEID(unicodeStrlen);
MAKEID(unicodeSubStrFX);
MAKEID(unicodeSubStrFTX);
MAKEID(utf82Codepage);
MAKEID(utf82CodepageX);
MAKEID(utf82Data);
MAKEID(utf82DataX);
MAKEID(utf82Unicode);
MAKEID(utf82UnicodeX);
MAKEID(utf8ToUtf8);
MAKEID(utf8ToUtf8X);
MAKEID(utf8Length);
MAKEID(utf8Size);
MAKEID(utf8SubStrFX);
MAKEID(utf8SubStrFTX);
MAKEID(validReal);
MAKEID(vcodepage2Unicode);
MAKEID(vcodepage2UnicodeX);
MAKEID(vcodepage2VUnicode);
MAKEID(vcodepage2VUnicodeX);
MAKEID(vn2b);
MAKEID(vn2f);
MAKEID(vn2l4);
MAKEID(vn2l8);
MAKEID(vn2ls4);
MAKEID(vn2ls8);
MAKEID(vstr2Data);
MAKEID(vstr2Str);
MAKEID(vstr2VStr);
MAKEID(vunicode2Codepage);
MAKEID(vunicode2CodepageX);
MAKEID(vunicode2Data);
MAKEID(vunicode2DataX);
MAKEID(vunicode2Unicode);
MAKEID(vunicode2UnicodeX);
MAKEID(vunicode2VCodepage);
MAKEID(vunicode2VCodepageX);
MAKEID(vunicode2VUnicode);
MAKEID(vunicode2VUnicodeX);
MAKEID(walkIndirectMetaMember);
MAKEID(wregexFindX);
MAKEID(wregexGetFindStr);
MAKEID(wregexReplaceX);
MAKEID(writeEbcdic);
writeIntId[3] = createIdAtom("writeInt3");
writeIntId[5] = createIdAtom("writeInt5");
writeIntId[6] = createIdAtom("writeInt6");
writeIntId[7] = createIdAtom("writeInt7");
MAKEID(writeReal);
MAKEID(writeSigned);
MAKEID(writeString);
MAKEID(writeUnicode);
MAKEID(writeUnsigned);
MAKEID(writeUtf8);
MAKEID(xmlDecodeStr);
MAKEID(xmlDecodeUStr);
MAKEID(xmlEncodeStr);
MAKEID(xmlEncodeUStr);
//Atoms
MAKEATOM(activeActivityMarker);
MAKEATOM(activeMatchText);
MAKEATOM(activeMatchUnicode);
MAKEATOM(activeMatchUtf8);
MAKEATOM(activeProductionMarker);
MAKEATOM(activeValidateMarker);
MAKEATOM(activityIdMarker);
MAKEATOM(bitfieldOffset);
MAKEATOM(blobHelper);
MAKEATOM(branch);
MAKEATOM(checkpoint);
MAKEATOM(child);
MAKEATOM(class);
MAKEATOM(clear);
MAKEATOM(__clearHelper);
MAKEATOM(csvReadMarker);
MAKEATOM(decimal);
MAKEATOM(declare);
MAKEATOM(dictionary);
MAKEATOM(delayed);
MAKEATOM(dependency);
MAKEATOM(deserializer);
MAKEATOM(ecl);
MAKEATOM(end);
MAKEATOM(ensureCapacity);
MAKEATOM(file);
MAKEATOM(forceAllCheck);
MAKEATOM(funnel);
MAKEATOM(go);
MAKEATOM(guard);
MAKEATOM(helper);
MAKEATOM(indexLayoutMarker);
MAKEATOM(init);
MAKEATOM(insideOnCreate);
MAKEATOM(insideOnStart);
MAKEATOM(instance);
MAKEATOM(isLastBitfield);
MAKEATOM(mainprototypes);
MAKEATOM(multiInstance);
MAKEATOM(noSet);
MAKEATOM(numResults);
MAKEATOM(packing);
MAKEATOM(parentHelpers);
MAKEATOM(path);
MAKEATOM(prefetcherInstanceMarker);
MAKEATOM(quick);
MAKEATOM(results);
MAKEATOM(rowAllocatorMarker);
MAKEATOM(rtlFieldKeyMarker);
MAKEATOM(serializer);
MAKEATOM(serializerInstanceMarker);
MAKEATOM(skipActionMarker);
MAKEATOM(skipReturnMarker);
MAKEATOM(speed);
MAKEATOM(subgraph);
utf8Atom = createAtom("utf-8");
MAKEATOM(wrapper);
MAKEATOM(xmlColumnProvider);
MAKEATOM(xmlReadMarker);
MAKESYSATOM(accessedFromChild);
MAKESYSATOM(conditionalRowMarker);
MAKESYSATOM(loop);
MAKESYSATOM(loopFirst);
MAKESYSATOM(noAccess);
MAKESYSATOM(noReplicate);
MAKESYSATOM(noVirtual);
MAKESYSATOM(regexFindInstance);
MAKESYSATOM(regexInstance);
MAKESYSATOM(selfJoinPlaceholder);
MAKESYSATOM(spill);
MAKESYSATOM(spillReason);
MAKESYSATOM(steppedMeta);
MAKESYSATOM(translated);
return true;
}
| 28.795318
| 117
| 0.755349
|
oxhead
|
a9f7d5e11d48d70389957fad91cbb5fd9232ac89
| 3,694
|
cpp
|
C++
|
MathOperationsOnImage/src/main.cpp
|
blongho/CV1
|
896f35850e962f148665f0426184bd9cc87aed5d
|
[
"MIT"
] | null | null | null |
MathOperationsOnImage/src/main.cpp
|
blongho/CV1
|
896f35850e962f148665f0426184bd9cc87aed5d
|
[
"MIT"
] | null | null | null |
MathOperationsOnImage/src/main.cpp
|
blongho/CV1
|
896f35850e962f148665f0426184bd9cc87aed5d
|
[
"MIT"
] | 1
|
2020-06-14T03:48:33.000Z
|
2020-06-14T03:48:33.000Z
|
#include "Base.h"
#include "ContrastAndBrightness.h"
int main(int argc, char** argv)
{
try
{
const std::string path = "../../images/messi5.jpg";
//Mat image = imread(path);
//const double scalingFactor = 1 / 255.0;
//const double shift = 0;
//Mat contrastHigh = image.clone();
//Mat bright = image.clone();
////imshow("Origingal image ", image);
////imageInfo(image);
////Converting from unsigned char to float(32bit)
//image.convertTo(image, CV_32FC3, scalingFactor, shift);
////imshow("Converted image", image);
////imageInfo(image);
////Converting from float to unsigned char
//image.convertTo(image, CV_8UC3, 1.0 / scalingFactor, shift);
////imageInfo(image);
////imshow("Restored image", image);
//// Changing the contrast
//const double contrastPercentage = 30;
//// Multiply with scaling factor to increase contrast
//// Convert contrastHigh to float
//contrastHigh.convertTo(contrastHigh, CV_64F);
//contrastHigh = contrastHigh * (1 + contrastPercentage / 100.0);
////imshow("Improved contrast ", contrastHigh);
////imageInfo(contrastHigh);
//// Altering the brightness simply implies adding/subtracting some offset value to/from the RGB values
//const int brightnessOffset = 30;
//Mat brightHigh = image.clone();
//Mat brightHighChannels[3];
//split(brightHigh, brightHighChannels);
//for (int i = 0; i < 3; i++) {
// add(brightHighChannels[i], brightnessOffset, brightHighChannels[i]);
//}
//merge(brightHighChannels, 3, brightHigh);
////imshow("Original Image", image);
////imshow("Brightened Image", brightHigh);
////imshow("Constract Image", contrastHigh);
//double minVal, maxVal;
//cout << "Original Image Datatype : " << type2str(image.type()) << endl;
//cout << "Contrast Image Datatype : " << type2str(contrastHigh.type()) << endl;
//cout << "Brightness Image Datatype : " << type2str(brightHigh.type()) << endl;
//minMaxLoc(image, &minVal, &maxVal);
//cout << "Original Image Highest Pixel Intensity : " << maxVal << endl;
//minMaxLoc(contrastHigh, &minVal, &maxVal);
//cout << "Contrast Image Highest Pixel Intensity : " << maxVal << endl;
//minMaxLoc(brightHigh, &minVal, &maxVal);
////cout << "Brightness Image Highest Pixel Intensity : " << maxVal << endl;
//printOn("Brightness Image Highest Pixel Intensity", maxVal);
//printOn("This is a long combination of values", 24.6, 'j', 4);
//uint8_t data[] = { 100,110,120,130 };
//Mat a(2, 2, CV_8UC1, data);
//printOn(a);
//const uint8_t scalar{ 130 };
//printOn(a + scalar);
//printOn(a - scalar);
//Mat addition;
//add(a, Scalar(130), addition);
//printOn(addition);
//int dataInt[] = { 100,110,120,130 };
//Mat b(2, 2, CV_32SC1, dataInt);
//b = b + 130;
//printOn("Corrected", b);
//b.convertTo(b, CV_8UC1);
//printOn("Converted back to originala", b);
///*
//It is a good practice to convert the uint8 to float and normalize the range to [0,1]
//and change it back to [0,255] after doing all arithmetic operations
//*/
//Mat a_float32;
//a.convertTo(a_float32, CV_32F, 1.0 / 255.0, 0);
//a_float32 = a_float32 + 130.0 / 255.0;
//printOn("Convert float", a_float32);
//Mat c;
//a_float32.convertTo(c, CV_32F, 255.0, 0.0);
//cout << c;
//// Clipped output
//Mat b_uint8;
//c.convertTo(b_uint8, CV_8UC1);
//cout << b_uint8;
Mat image = imread(path);
transform(image);
gammaCorrection(image, -10.0f);
}
catch (const std::exception & e)
{
cerr << "Error " << e.what() << endl;
}
const auto key = waitKey(0);
cout << "Key pressed is : ascii value = " << key << ", printable: " << static_cast<char>(key) << endl;
return 0;
}
| 30.528926
| 105
| 0.643476
|
blongho
|
a9f9f7f843fcbc42803d6ec66652c56f0ac6f405
| 2,986
|
cpp
|
C++
|
src/gl_engine/mesh/Cube.cpp
|
russkev/opengl
|
73417d1697d1964cfa001efc8e54eb90da95ed6e
|
[
"MIT"
] | 5
|
2020-03-26T11:55:55.000Z
|
2021-07-30T04:14:21.000Z
|
src/gl_engine/mesh/Cube.cpp
|
russkev/opengl
|
73417d1697d1964cfa001efc8e54eb90da95ed6e
|
[
"MIT"
] | 3
|
2020-12-05T06:02:07.000Z
|
2021-06-02T03:42:34.000Z
|
src/gl_engine/mesh/Cube.cpp
|
russkev/opengl
|
73417d1697d1964cfa001efc8e54eb90da95ed6e
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Cube.h"
#include "Vertex.h"
namespace glen
{
// // ----- MAIN ----- // //
Mesh Cube::create_cube()
{
return create_cube(1.0f, true);
}
Mesh Cube::create_cube(const float width, const bool is_default)
{
float half_width = is_default ? 1.0f : width / 2.0f;
Mesh newCube;
Mesh up_face = create_cube_face(
glm::vec3(-half_width, half_width * 2, +half_width),
glm::vec3(+half_width, half_width * 2, +half_width),
glm::vec3(-half_width, half_width * 2, -half_width),
glm::vec3(+half_width, half_width * 2, -half_width)
);
Mesh bottom_face = create_cube_face(
glm::vec3(+half_width, 0, +half_width),
glm::vec3(-half_width, 0, +half_width),
glm::vec3(+half_width, 0, -half_width),
glm::vec3(-half_width, 0, -half_width)
);
newCube += bottom_face;
Mesh right_face = create_cube_face(
glm::vec3(+half_width, half_width * 2, -half_width),
glm::vec3(+half_width, half_width * 2, +half_width),
glm::vec3(+half_width, 0, -half_width),
glm::vec3(+half_width, 0, +half_width)
);
newCube += right_face;
Mesh left_face = create_cube_face(
glm::vec3(-half_width, half_width * 2, +half_width),
glm::vec3(-half_width, half_width * 2, -half_width),
glm::vec3(-half_width, 0, +half_width),
glm::vec3(-half_width, 0, -half_width)
);
newCube += left_face;
Mesh front_face = create_cube_face(
glm::vec3(-half_width, half_width * 2, -half_width),
glm::vec3(+half_width, half_width * 2, -half_width),
glm::vec3(-half_width, 0, -half_width),
glm::vec3(+half_width, 0, -half_width)
);
newCube += front_face;
Mesh back_face = create_cube_face(
glm::vec3(+half_width, half_width * 2, +half_width),
glm::vec3(-half_width, half_width * 2, +half_width),
glm::vec3(+half_width, 0, +half_width),
glm::vec3(-half_width, 0, +half_width)
);
newCube += back_face;
newCube += up_face;
newCube += bottom_face;
newCube += right_face;
newCube += left_face;
newCube += front_face;
newCube += back_face;
newCube.make_indices_smooth();
newCube.make_tangents();
return newCube;
}
// // ----- HELPER ----- // //
Mesh Cube::create_cube_face(glm::vec3 top_left, glm::vec3 top_right, glm::vec3 bottom_left, glm::vec3 bottom_right)
{
// Vertix order is like this:
//
// tl-----tr
// | |
// | |
// bl-----br
//
Mesh newFace;
// Vertex Normals
glm::vec3 face_normal = glm::cross(top_right - top_left, bottom_left - top_left);
// Vertex UVs
glm::vec2 uv1 = { 0.0f, 1.0f };
glm::vec2 uv2 = { 1.0f, 1.0f };
glm::vec2 uv3 = { 0.0f, 0.0f };
glm::vec2 uv4 = { 1.0f, 0.0f };
// Vertices
Vertex vert1 = { top_left, face_normal, uv2 };
Vertex vert2 = { top_right, face_normal, uv1 };
Vertex vert3 = { bottom_left, face_normal, uv4 };
Vertex vert4 = { bottom_right, face_normal, uv3 };
newFace.append_triangle(vert1, vert2, vert3);
newFace.append_triangle(vert2, vert4, vert3);
return newFace;
}
}
| 26.660714
| 116
| 0.645345
|
russkev
|
a9fa7114f5f45ab15f9589d93bf21bd1c796c0c2
| 1,312
|
cpp
|
C++
|
aws-cpp-sdk-rum/source/model/CwLog.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-rum/source/model/CwLog.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-rum/source/model/CwLog.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/rum/model/CwLog.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace CloudWatchRUM
{
namespace Model
{
CwLog::CwLog() :
m_cwLogEnabled(false),
m_cwLogEnabledHasBeenSet(false),
m_cwLogGroupHasBeenSet(false)
{
}
CwLog::CwLog(JsonView jsonValue) :
m_cwLogEnabled(false),
m_cwLogEnabledHasBeenSet(false),
m_cwLogGroupHasBeenSet(false)
{
*this = jsonValue;
}
CwLog& CwLog::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("CwLogEnabled"))
{
m_cwLogEnabled = jsonValue.GetBool("CwLogEnabled");
m_cwLogEnabledHasBeenSet = true;
}
if(jsonValue.ValueExists("CwLogGroup"))
{
m_cwLogGroup = jsonValue.GetString("CwLogGroup");
m_cwLogGroupHasBeenSet = true;
}
return *this;
}
JsonValue CwLog::Jsonize() const
{
JsonValue payload;
if(m_cwLogEnabledHasBeenSet)
{
payload.WithBool("CwLogEnabled", m_cwLogEnabled);
}
if(m_cwLogGroupHasBeenSet)
{
payload.WithString("CwLogGroup", m_cwLogGroup);
}
return payload;
}
} // namespace Model
} // namespace CloudWatchRUM
} // namespace Aws
| 17.038961
| 69
| 0.71189
|
perfectrecall
|
a9fead9c26abc93cea21bb343f1a4dcadae253c6
| 6,905
|
hh
|
C++
|
src/include/simeng/Instruction.hh
|
viper12590/SimEng
|
e9fc4d24a8823e553e042c60801aa0a0e3f077ca
|
[
"Apache-2.0"
] | null | null | null |
src/include/simeng/Instruction.hh
|
viper12590/SimEng
|
e9fc4d24a8823e553e042c60801aa0a0e3f077ca
|
[
"Apache-2.0"
] | null | null | null |
src/include/simeng/Instruction.hh
|
viper12590/SimEng
|
e9fc4d24a8823e553e042c60801aa0a0e3f077ca
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <vector>
#include "simeng/MemoryInterface.hh"
#include "simeng/RegisterFileSet.hh"
#include "simeng/RegisterValue.hh"
#include "simeng/span.hh"
using InstructionException = short;
namespace simeng {
/** A branch result prediction for an instruction. */
struct BranchPrediction {
/** Whether the branch will be taken. */
bool taken;
/** The branch instruction's target address. If `taken = false`, the value
* will be ignored. */
uint64_t target;
};
/** An abstract instruction definition.
* Each supported ISA should provide a derived implementation of this class. */
class Instruction {
public:
virtual ~Instruction(){};
/** Check whether an exception has been encountered while processing this
* instruction. */
bool exceptionEncountered() const;
/** Retrieve the source registers this instruction reads. */
virtual const span<Register> getOperandRegisters() const = 0;
/** Retrieve the destination registers this instruction will write to.
* A register value of -1 signifies a Zero Register read, and should not be
* renamed. */
virtual const span<Register> getDestinationRegisters() const = 0;
/** Override the specified source register with a renamed physical register.
*/
virtual void renameSource(uint8_t i, Register renamed) = 0;
/** Override the specified destination register with a renamed physical
* register. */
virtual void renameDestination(uint8_t i, Register renamed) = 0;
/** Provide a value for the operand at the specified index. */
virtual void supplyOperand(uint8_t i, const RegisterValue& value) = 0;
/** Check whether the operand at index `i` has had a value supplied. */
virtual bool isOperandReady(int i) const = 0;
/** Check whether all operand values have been supplied, and the instruction
* is ready to execute. */
virtual bool canExecute() const = 0;
/** Execute the instruction. */
virtual void execute() = 0;
/** Check whether the instruction has executed and has results ready to
* write back. */
bool hasExecuted() const;
/** Mark the instruction as ready to commit. */
void setCommitReady();
/** Check whether the instruction has written its values back and is ready to
* commit. */
bool canCommit() const;
/** Retrieve register results. */
virtual const span<RegisterValue> getResults() const = 0;
/** Generate memory addresses this instruction wishes to access. */
virtual span<const MemoryAccessTarget> generateAddresses() = 0;
/** Provide data from a requested memory address. */
virtual void supplyData(uint64_t address, const RegisterValue& data) = 0;
/** Retrieve previously generated memory addresses. */
virtual span<const MemoryAccessTarget> getGeneratedAddresses() const = 0;
/** Retrieve supplied memory data. */
virtual span<const RegisterValue> getData() const = 0;
/** Check whether all required data has been supplied. */
bool hasAllData() const;
/** Early misprediction check; see if it's possible to determine whether the
* next instruction address was mispredicted without executing the
* instruction. Returns a {mispredicted, target} tuple representing whether
* the instruction was mispredicted, and the correct target address. */
virtual std::tuple<bool, uint64_t> checkEarlyBranchMisprediction() const = 0;
/** Check for misprediction. */
bool wasBranchMispredicted() const;
/** Retrieve branch address. */
uint64_t getBranchAddress() const;
/** Was the branch taken? */
bool wasBranchTaken() const;
/** Is this a store operation? */
virtual bool isStore() const = 0;
/** Is this a load operation? */
virtual bool isLoad() const = 0;
/** Is this a branch operation? */
virtual bool isBranch() const = 0;
/** Is this a return instruction? */
virtual bool isRET() const = 0;
/** Is this a branch and link instruction? */
virtual bool isBL() const = 0;
/** Is this a SVE instruction? */
/** Maybe remove as aarch64 exclusive? */
virtual bool isSVE() const = 0;
/** Set this instruction's instruction memory address. */
void setInstructionAddress(uint64_t address);
/** Get this instruction's instruction memory address. */
uint64_t getInstructionAddress() const;
/** Supply a branch prediction. */
void setBranchPrediction(BranchPrediction prediction);
/** Set this instruction's sequence ID. */
void setSequenceId(uint64_t seqId);
/** Retrieve this instruction's sequence ID. */
uint64_t getSequenceId() const;
/** Mark this instruction as flushed. */
void setFlushed();
/** Check whether this instruction has been flushed. */
bool isFlushed() const;
/** Retrieve the instruction group this instruction belongs to. */
virtual uint16_t getGroup() const = 0;
/** Retrieve the number of cycles this instruction will take to execute. */
uint16_t getLatency() const;
/** Retrieve the number of cycles this instruction will take to be prcoessed
* by the LSQ. */
uint16_t getLSQLatency() const;
/** Retrieve the number of cycles this instruction will block the unit
* executing it. */
uint16_t getStallCycles() const;
/** Get this instruction's supported set of ports. */
virtual const std::vector<uint8_t>& getSupportedPorts() = 0;
bool shouldSplitRequests() const;
protected:
/** Whether an exception has been encountered. */
bool exceptionEncountered_ = false;
/** The location in memory of this instruction was decoded at. */
uint64_t instructionAddress_;
/** Whether or not this instruction has been executed. */
bool executed_ = false;
/** Whether or not this instruction is ready to commit. */
bool canCommit_ = false;
// Memory
/** The number of data items that still need to be supplied. */
uint8_t dataPending_ = 0;
// Branches
/** The predicted branching result. */
BranchPrediction prediction_;
/** A branching address calculated by this instruction during execution. */
uint64_t branchAddress_;
/** Was the branch taken? */
bool branchTaken_ = false;
// Flushing
/** This instruction's sequence ID; a higher ID represents a chronologically
* newer instruction. */
uint64_t sequenceId_;
/** Has this instruction been flushed? */
bool flushed_ = false;
/** The number of cycles this instruction takes to execute. */
uint16_t latency_ = 1;
/** The number of cycles a load or store instruction takes to execute within
* the load/store queue. */
uint16_t lsqExecutionLatency_ = 1;
/** The number of cycles this instruction will stall the unit executing it
* for. */
uint16_t stallCycles_ = 1;
/** The execution ports that this instruction can be issued to. */
std::vector<uint8_t> supportedPorts_ = {};
/** Whether this instructions' memory accesses should be treated as many
* independent requests. **/
bool splitMemoryRequests_ = false;
};
} // namespace simeng
| 31.386364
| 79
| 0.711803
|
viper12590
|
e7024cb4383ac67965b02c31bee80e74a252b898
| 1,566
|
cpp
|
C++
|
Practice/2018/2018.8.24/CF125E.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.8.24/CF125E.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.8.24/CF125E.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=5010;
const int maxM=101000;
const int inf=2147483647;
class Edge
{
public:
int u,v,w,opt,id;
};
int n,m,K;
Edge E[maxM];
int mst,cnt;
int UFS[maxN];
void Calc(int C);
int Find(int x);
bool cmp(Edge A,Edge B);
int main(){
scanf("%d%d%d",&n,&m,&K);
int L=0,R=0,pos,tot=0;
for (int i=1;i<=m;i++){
scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].w);
if ((E[i].u==1)||(E[i].v==1)) E[i].opt=1,tot++;
L-=E[i].w;R+=E[i].w;E[i].id=i;
}
if ((tot<K)||((K==0)&&(n>1))){
printf("-1\n");return 0;
}
do{
int mid=(L+R)>>1;
Calc(mid);
if (cnt>=K) pos=mid,L=mid+1;
else R=mid-1;
}
while (L<=R);
Calc(pos);
printf("%d\n",n-1);
for (int i=1;i<=n;i++) UFS[i]=i;
tot=0;
for (int i=1;i<=m;i++)
if (Find(E[i].u)!=Find(E[i].v)){
if ((E[i].opt)&&(tot==K)) continue;
printf("%d ",E[i].id);
if (E[i].opt) tot++;
UFS[Find(E[i].u)]=Find(E[i].v);
}
printf("\n");
return 0;
}
void Calc(int c){
for (int i=1;i<=m;i++) if (E[i].opt) E[i].w+=c;
sort(&E[1],&E[m+1],cmp);
for (int i=1;i<=n;i++) UFS[i]=i;
mst=0;cnt=0;
for (int i=1;i<=m;i++)
if (Find(E[i].u)!=Find(E[i].v)){
UFS[Find(E[i].u)]=Find(E[i].v);
mst+=E[i].w;cnt+=E[i].opt;
}
for (int i=1;i<=m;i++) if (E[i].opt) E[i].w-=c;
return;
}
int Find(int x){
if (UFS[x]!=x) UFS[x]=Find(UFS[x]);
return UFS[x];
}
bool cmp(Edge A,Edge B){
if (A.w!=B.w) return A.w<B.w;
return A.opt==1;
}
| 17.595506
| 49
| 0.533206
|
SYCstudio
|
e704f172c737d318b95b35f2e45a420ff85c289d
| 3,216
|
cpp
|
C++
|
tcaplusdb/src/v20190823/model/ServerMachineInfo.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 43
|
2019-08-14T08:14:12.000Z
|
2022-03-30T12:35:09.000Z
|
tcaplusdb/src/v20190823/model/ServerMachineInfo.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 12
|
2019-07-15T10:44:59.000Z
|
2021-11-02T12:35:00.000Z
|
tcaplusdb/src/v20190823/model/ServerMachineInfo.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 28
|
2019-07-12T09:06:22.000Z
|
2022-03-30T08:04:18.000Z
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcaplusdb/v20190823/model/ServerMachineInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcaplusdb::V20190823::Model;
using namespace std;
ServerMachineInfo::ServerMachineInfo() :
m_serverUidHasBeenSet(false),
m_machineTypeHasBeenSet(false)
{
}
CoreInternalOutcome ServerMachineInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ServerUid") && !value["ServerUid"].IsNull())
{
if (!value["ServerUid"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ServerMachineInfo.ServerUid` IsString=false incorrectly").SetRequestId(requestId));
}
m_serverUid = string(value["ServerUid"].GetString());
m_serverUidHasBeenSet = true;
}
if (value.HasMember("MachineType") && !value["MachineType"].IsNull())
{
if (!value["MachineType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ServerMachineInfo.MachineType` IsString=false incorrectly").SetRequestId(requestId));
}
m_machineType = string(value["MachineType"].GetString());
m_machineTypeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void ServerMachineInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_serverUidHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServerUid";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_serverUid.c_str(), allocator).Move(), allocator);
}
if (m_machineTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MachineType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_machineType.c_str(), allocator).Move(), allocator);
}
}
string ServerMachineInfo::GetServerUid() const
{
return m_serverUid;
}
void ServerMachineInfo::SetServerUid(const string& _serverUid)
{
m_serverUid = _serverUid;
m_serverUidHasBeenSet = true;
}
bool ServerMachineInfo::ServerUidHasBeenSet() const
{
return m_serverUidHasBeenSet;
}
string ServerMachineInfo::GetMachineType() const
{
return m_machineType;
}
void ServerMachineInfo::SetMachineType(const string& _machineType)
{
m_machineType = _machineType;
m_machineTypeHasBeenSet = true;
}
bool ServerMachineInfo::MachineTypeHasBeenSet() const
{
return m_machineTypeHasBeenSet;
}
| 28.714286
| 147
| 0.711443
|
suluner
|
e70a50eb5052450210d868af25091fb9f527d5eb
| 1,410
|
cpp
|
C++
|
server/homeserver/home/DeviceUtils.cpp
|
williamkoehler/home-server
|
ce99af73ea2e53fea3939fe0c4442433e65ac670
|
[
"MIT"
] | 1
|
2021-07-05T21:11:59.000Z
|
2021-07-05T21:11:59.000Z
|
server/homeserver/home/DeviceUtils.cpp
|
williamkoehler/home-server
|
ce99af73ea2e53fea3939fe0c4442433e65ac670
|
[
"MIT"
] | null | null | null |
server/homeserver/home/DeviceUtils.cpp
|
williamkoehler/home-server
|
ce99af73ea2e53fea3939fe0c4442433e65ac670
|
[
"MIT"
] | null | null | null |
#include "Device.hpp"
#include "Home.hpp"
namespace server
{
//! Timer
Device::Timer::Timer(Ref<Device> device, home::TimerCallback<home::Device>* callback)
: device(device), timer(*Home::GetInstance()->GetService()), callback(callback)
{
}
Device::Timer::~Timer()
{
}
void Device::Timer::TimerCallback(const boost::system::error_code& err)
{
if (!err)
{
// Invoke timer
Invoke();
timer.expires_from_now(boost::posix_time::seconds(interval));
timer.async_wait(boost::bind(&Device::Timer::TimerCallback, this, boost::placeholders::_1));
}
}
void Device::Timer::Start(size_t i)
{
interval = i;
timer.expires_from_now(boost::posix_time::seconds(interval));
timer.async_wait(boost::bind(&Device::Timer::TimerCallback, this, boost::placeholders::_1));
}
void Device::Timer::Invoke()
{
if (((home::TimerCallback<home::Device>*)callback)(device->plugin.get(), boost::reinterpret_pointer_cast<home::Device>(device)))
device->TakeSnapshot();
}
void Device::Timer::Stop()
{
timer.cancel();
}
//! Event
Device::Event::Event(Ref<Device> device, home::TimerCallback<home::Device>* callback)
: device(device), callback(callback)
{
}
Device::Event::~Event()
{
}
void Device::Event::Invoke()
{
if (((home::TimerCallback<home::Device>*)callback)(device->plugin.get(), boost::reinterpret_pointer_cast<home::Device>(device)))
device->TakeSnapshot();
}
}
| 24.310345
| 130
| 0.685106
|
williamkoehler
|
e70b21ab88fc6062aa6e86fe704ee55178ba29de
| 2,066
|
hpp
|
C++
|
water/types/tests/link.hpp
|
watercpp/water
|
7a9a292a2513529cf5dabac1bc7a755055dac9b5
|
[
"MIT"
] | 5
|
2017-04-18T18:18:50.000Z
|
2018-08-03T09:13:26.000Z
|
water/types/tests/link.hpp
|
watercpp/water
|
7a9a292a2513529cf5dabac1bc7a755055dac9b5
|
[
"MIT"
] | null | null | null |
water/types/tests/link.hpp
|
watercpp/water
|
7a9a292a2513529cf5dabac1bc7a755055dac9b5
|
[
"MIT"
] | null | null | null |
// Copyright 2017 Johan Paulsson
// This file is part of the Water C++ Library. It is licensed under the MIT License.
// See the license.txt file in this distribution or https://watercpp.com/license.txt
//\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_
#ifndef WATER_TYPES_TESTS_LINK_HPP
#define WATER_TYPES_TESTS_LINK_HPP
#include <water/types/link.hpp>
namespace water { namespace types { namespace tests {
namespace link_hpp {
typedef insert<link<>, void> l1;
typedef insert<l1, int> l2;
typedef insert<l2, type_plain<l2>, size<l2>::result> l3;
template<typename a_, typename b_, int at_ = 0, int a_size_ = size<a_>::result, int b_size_ = size<b_>::result>
struct equal_all : false_result
{};
template<typename a_, typename b_, int size_>
struct equal_all<a_, b_, size_, size_, size_> : true_result
{};
template<typename a_, typename b_, int at_, int size_>
struct equal_all<a_, b_, at_, size_, size_> : ifel_type<
equal<at<a_, at_>, at<b_, at_>>,
equal_all<a_, b_, at_ + 1>,
false_result
> {};
int constexpr assert1 =
type_assert<equal<l1, void> >::assert +
type_assert<equal<l2, int> >::assert +
type_assert<equal<at<l2, 1>, void> >::assert +
type_assert<equal<at<l3, 2>, type_plain<l2> > >::assert +
type_assert<equal_plain<at<l3, 2>::result, l2> >::assert +
type_assert<equal_plain<types::pull<l2>::result, link<int, link<void> > > >::assert +
type_assert<equal_all<
l3,
link<int, link<void, link<type_plain<l2> > > >
> >::assert +
type_assert<nots<enum_result<
offset<at<insert<at<l3, 3>, long>, -3> >::result
> > >::assert +
type_assert<equal<
size<at<insert<at<l3, 3>, long>, -3> >,
size<insert<l3, long, 3> >
> >::assert +
type_assert<equal_all<
at<insert<at<l3, 3>, long>, -3>,
insert<l3, long, 3>
> >::assert;
}
}}}
#endif
| 36.892857
| 115
| 0.590513
|
watercpp
|
e70d0258066a2afdc4b617efbb9e432ddf0caf6e
| 8,886
|
cpp
|
C++
|
ngraph/test/backend/cum_sum.in.cpp
|
artyomtugaryov/openvino
|
f2c2636bb52ff6a6c6d2b4dba89fad666a66c96f
|
[
"Apache-2.0"
] | null | null | null |
ngraph/test/backend/cum_sum.in.cpp
|
artyomtugaryov/openvino
|
f2c2636bb52ff6a6c6d2b4dba89fad666a66c96f
|
[
"Apache-2.0"
] | null | null | null |
ngraph/test/backend/cum_sum.in.cpp
|
artyomtugaryov/openvino
|
f2c2636bb52ff6a6c6d2b4dba89fad666a66c96f
|
[
"Apache-2.0"
] | null | null | null |
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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 <algorithm>
#include <cinttypes>
#include <cmath>
#include <cstdlib>
#include <random>
#include <string>
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "runtime/backend.hpp"
#include "util/all_close.hpp"
#include "util/all_close_f.hpp"
#include "util/ndarray.hpp"
#include "util/random.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
static std::mt19937_64 random_generator;
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
NGRAPH_TEST(${BACKEND_NAME}, cum_sum_default)
{
Shape shape{1, 4};
auto A = make_shared<op::Parameter>(element::Type_t::f32, shape);
auto axis = make_shared<op::Parameter>(element::Type_t::i32, Shape{1});
auto f = make_shared<Function>(make_shared<op::CumSum>(A, axis), ParameterVector{A, axis});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::Type_t::f32, shape);
copy_data(a, vector<float>{1, 2, 3, 4});
auto axis_tensor = backend->create_tensor(axis->get_element_type(), axis->get_shape());
copy_data(axis_tensor, vector<int32_t>{1});
auto result = backend->create_tensor(element::Type_t::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, axis_tensor});
EXPECT_TRUE(test::all_close_f((vector<float>{1, 3, 6, 10}), read_vector<float>(result)));
}
NGRAPH_TEST(${BACKEND_NAME}, cum_sum_2dim)
{
Shape shape{2, 4};
auto A = make_shared<op::Parameter>(element::Type_t::f32, shape);
auto axis = make_shared<op::Parameter>(element::Type_t::i64, Shape{1});
auto f = make_shared<Function>(make_shared<op::CumSum>(A, axis), ParameterVector{A, axis});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::Type_t::f32, shape);
copy_data(a, vector<float>{0, 1, 2, 3, 4, 5, 6, 7});
auto axis_tensor = backend->create_tensor(axis->get_element_type(), axis->get_shape());
copy_data(axis_tensor, vector<int64_t>{0});
auto result = backend->create_tensor(element::Type_t::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, axis_tensor});
EXPECT_TRUE(
test::all_close_f((vector<float>{0, 1, 2, 3, 4, 6, 8, 10}), read_vector<float>(result)));
}
NGRAPH_TEST(${BACKEND_NAME}, cum_sum_2dim_default_axis)
{
Shape shape{2, 4};
auto A = make_shared<op::Parameter>(element::Type_t::f32, shape);
auto f = make_shared<Function>(make_shared<op::CumSum>(A), ParameterVector{A});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::Type_t::f32, shape);
copy_data(a, vector<float>{0, 1, 2, 3, 4, 5, 6, 7});
auto result = backend->create_tensor(element::Type_t::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a});
EXPECT_TRUE(
test::all_close_f((vector<float>{0, 1, 2, 3, 4, 6, 8, 10}), read_vector<float>(result)));
}
NGRAPH_TEST(${BACKEND_NAME}, cum_sum_3d)
{
auto test_cumsum_3d = [](const int32_t axis_val) -> void {
Shape shape{3, 2, 4};
auto A = make_shared<op::Parameter>(element::Type_t::f32, shape);
auto axis = make_shared<op::Parameter>(element::Type_t::i32, Shape{1});
auto f = make_shared<Function>(make_shared<op::CumSum>(A, axis), ParameterVector{A, axis});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::Type_t::f32, shape);
copy_data(a, vector<float>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23});
auto axis_tensor = backend->create_tensor(axis->get_element_type(), axis->get_shape());
copy_data(axis_tensor, vector<int32_t>{axis_val});
auto result = backend->create_tensor(element::Type_t::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, axis_tensor});
if (axis_val == 0)
{
EXPECT_TRUE(
test::all_close_f((vector<float>{0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14,
16, 18, 20, 22, 24, 27, 30, 33, 36, 39, 42, 45}),
read_vector<float>(result)));
}
else if (axis_val == 1)
{
EXPECT_TRUE(
test::all_close_f((vector<float>{0, 1, 2, 3, 4, 6, 8, 10, 8, 9, 10, 11,
20, 22, 24, 26, 16, 17, 18, 19, 36, 38, 40, 42}),
read_vector<float>(result)));
}
else if (axis_val == 2)
{
EXPECT_TRUE(
test::all_close_f((vector<float>{0, 1, 3, 6, 4, 9, 15, 22, 8, 17, 27, 38,
12, 25, 39, 54, 16, 33, 51, 70, 20, 41, 63, 86}),
read_vector<float>(result)));
}
};
test_cumsum_3d(0);
test_cumsum_3d(1);
test_cumsum_3d(2);
}
NGRAPH_TEST(${BACKEND_NAME}, cum_sum_2dim_allmodes)
{
auto test_cum_sum_allmodes = [](const int64_t axis_val, int exclusive, int reverse) {
Shape shape{2, 4};
auto A = make_shared<op::Parameter>(element::Type_t::f32, shape);
auto axis = make_shared<op::Parameter>(element::Type_t::i64, Shape{1});
auto f = make_shared<Function>(make_shared<op::CumSum>(A, axis, exclusive, reverse),
ParameterVector{A, axis});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::Type_t::f32, shape);
copy_data(a, vector<float>{0, 1, 2, 3, 4, 5, 6, 7});
auto axis_tensor = backend->create_tensor(axis->get_element_type(), axis->get_shape());
copy_data(axis_tensor, vector<int64_t>{axis_val});
auto result = backend->create_tensor(element::Type_t::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, axis_tensor});
if (axis_val == 1 && exclusive == 1 && reverse == 0)
{
EXPECT_TRUE(test::all_close_f((vector<float>{0, 0, 1, 3, 0, 4, 9, 15}),
read_vector<float>(result)));
}
else if (axis_val == 1 && exclusive == 0 && reverse == 1)
{
EXPECT_TRUE(test::all_close_f((vector<float>{6, 6, 5, 3, 22, 18, 13, 7}),
read_vector<float>(result)));
}
else if (axis_val == 1 && exclusive == 1 && reverse == 1)
{
EXPECT_TRUE(test::all_close_f((vector<float>{6, 5, 3, 0, 18, 13, 7, 0}),
read_vector<float>(result)));
}
else if (axis_val == 0 && exclusive == 0 && reverse == 0)
{
EXPECT_TRUE(test::all_close_f((vector<float>{0, 1, 2, 3, 4, 6, 8, 10}),
read_vector<float>(result)));
}
else if (axis_val == 0 && exclusive == 1 && reverse == 1)
{
EXPECT_TRUE(test::all_close_f((vector<float>{4, 5, 6, 7, 0, 0, 0, 0}),
read_vector<float>(result)));
}
else if (axis_val == 0 && exclusive == 0 && reverse == 1)
{
EXPECT_TRUE(test::all_close_f((vector<float>{4, 6, 8, 10, 4, 5, 6, 7}),
read_vector<float>(result)));
}
};
test_cum_sum_allmodes(1, 1, 0);
test_cum_sum_allmodes(-1, 0, 1);
test_cum_sum_allmodes(-1, 1, 1);
test_cum_sum_allmodes(0, 0, 0);
test_cum_sum_allmodes(0, 1, 1);
test_cum_sum_allmodes(0, 0, 1);
}
| 42.113744
| 99
| 0.57765
|
artyomtugaryov
|
e70f25b3d81e2fe22aff074de79b3771aa004cac
| 808
|
cpp
|
C++
|
netflix.cpp
|
deepanshu1422/450Questions
|
614a6bcb66f3202a62c375c0c0a63365e1021110
|
[
"Apache-2.0"
] | null | null | null |
netflix.cpp
|
deepanshu1422/450Questions
|
614a6bcb66f3202a62c375c0c0a63365e1021110
|
[
"Apache-2.0"
] | null | null | null |
netflix.cpp
|
deepanshu1422/450Questions
|
614a6bcb66f3202a62c375c0c0a63365e1021110
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
using namespace std;
void breakinto(string s)
{ int space=0;
int counter=0;
for(int i=0;i<s.size()-1;i++)
{
if(s.at(i)==' ')
{
space=i;
}
counter++;
if(counter%140>0)
{
if(s[i]!=' ')
{
i=space;
}
s.append("")
}
}
}
int main()
{
string s="Articles is a piece of writing and is produced either in a printed or electronic form, in newspaper, magazine, journal or website. It has a large readership in mind. It is based on surveys, research, facts and analysis etc. Articles may be short or slightly long may be upto 1500 words. It is written with a definite objective and informs the readers about some concept.";
breakinto(s);
}
| 25.25
| 386
| 0.565594
|
deepanshu1422
|
e71069da049c846a9d1b53fc14b2f3fe638f1a4f
| 519
|
cpp
|
C++
|
pismeni/2016-april/4b.cpp
|
Dunsteer/paralelni-sistemi
|
776193d457457c438cd5ba7ef17a54969450477c
|
[
"MIT"
] | 1
|
2021-08-22T17:14:49.000Z
|
2021-08-22T17:14:49.000Z
|
pismeni/2016-april/4b.cpp
|
Dunsteer/paralelni-sistemi
|
776193d457457c438cd5ba7ef17a54969450477c
|
[
"MIT"
] | null | null | null |
pismeni/2016-april/4b.cpp
|
Dunsteer/paralelni-sistemi
|
776193d457457c438cd5ba7ef17a54969450477c
|
[
"MIT"
] | 1
|
2021-08-31T19:34:46.000Z
|
2021-08-31T19:34:46.000Z
|
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define N 6
int main()
{
int m = 4;
int a[N];
int j;
a[0] = m;
int c = m;
#pragma omp parallel for reduction(+:m)
for (j = 0; j < N; j++)
{
a[j] = c + ((j - 1) * j) / 2;
m += j;
printf("Running\n");
}
/*#pragma omp parallel for reduction(+:m)
for (j = 0; j < N; j++)
{
m += j;
}*/
printf("M: %d.\n\nA:", m);
for (int i = 0; i < N; i++)
printf("%d ", a[i]);
}
| 16.21875
| 45
| 0.400771
|
Dunsteer
|
e710f10d3def65703d22659465097c9f659cc254
| 268
|
cpp
|
C++
|
old/AtCoder/abc099/C.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
old/AtCoder/abc099/C.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
old/AtCoder/abc099/C.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "vector.hpp"
int main() {
int n;
cin >> n;
vector<int> dp(n + 1);
iota(dp, 0);
for (int i = 0; i < n; ++i) {
for (int k : {6, 9}) {
for (int j = k; i + j <= n; j *= k) chmin(dp[i + j], dp[i] + 1);
}
}
cout << dp.back() << endl;
}
| 17.866667
| 70
| 0.414179
|
not522
|
e712756781999469607a95047870411336ad9228
| 2,727
|
cpp
|
C++
|
ProceduralMesh/MyActor.cpp
|
devilmhzx/UE4-Cpp-Tutorials
|
2cbf9d44dd4fa1c4eb68530f692065fc2c36b55d
|
[
"MIT"
] | 531
|
2016-10-19T14:04:55.000Z
|
2022-03-28T06:34:25.000Z
|
ProceduralMesh/MyActor.cpp
|
devilmhzx/UE4-Cpp-Tutorials
|
2cbf9d44dd4fa1c4eb68530f692065fc2c36b55d
|
[
"MIT"
] | null | null | null |
ProceduralMesh/MyActor.cpp
|
devilmhzx/UE4-Cpp-Tutorials
|
2cbf9d44dd4fa1c4eb68530f692065fc2c36b55d
|
[
"MIT"
] | 172
|
2016-10-18T14:53:11.000Z
|
2022-03-22T10:39:44.000Z
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyActor.h"
// Sets default values
AMyActor::AMyActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
CustomMesh = CreateDefaultSubobject<UProceduralMeshComponent>("CustomMesh");
SetRootComponent(CustomMesh);
CustomMesh->bUseAsyncCooking = true;
}
// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
Super::BeginPlay();
GenerateCubeMesh();
}
void AMyActor::AddTriangle(int32 V1, int32 V2, int32 V3)
{
Triangles.Add(V1);
Triangles.Add(V2);
Triangles.Add(V3);
}
void AMyActor::GenerateCubeMesh()
{
//6 sides on cube, 4 verts each (corners)
//These are relative locations to the placed Actor in the world
Vertices.Add(FVector(0, -100, 0)); //lower left - 0
Vertices.Add(FVector(0, -100, 100)); //upper left - 1
Vertices.Add(FVector(0, 100, 0)); //lower right - 2
Vertices.Add(FVector(0, 100, 100)); //upper right - 3
Vertices.Add(FVector(100, -100, 0)); //lower front left - 4
Vertices.Add(FVector(100, -100, 100)); //upper front left - 5
Vertices.Add(FVector(100, 100, 100)); //upper front right - 6
Vertices.Add(FVector(100, 100, 0)); //lower front right - 7
//Back face of cube
AddTriangle(0, 2, 3); //normal face
//AddTriangle(3, 2, 0); // flipped face
AddTriangle(3, 1, 0);
//Left face of cube
AddTriangle(0, 1, 4);
AddTriangle(4, 1, 5);
//Front face of cube
AddTriangle(4, 5, 7);
AddTriangle(7, 5, 6);
//Right face of cube
AddTriangle(7, 6, 3);
AddTriangle(3, 2, 7);
//Top face
AddTriangle(1, 3, 5);
AddTriangle(6, 5, 3);
//bottom face
AddTriangle(2, 0, 4);
AddTriangle(4, 7, 2);
TArray<FLinearColor> VertexColors;
VertexColors.Add(FLinearColor(0.f, 0.f, 1.f));
VertexColors.Add(FLinearColor(1.f, 0.f, 0.f));
VertexColors.Add(FLinearColor(1.f, 0.f, 0.f));
VertexColors.Add(FLinearColor(0.f, 1.f, 0.f));
VertexColors.Add(FLinearColor(0.5f, 1.f, 0.5f));
VertexColors.Add(FLinearColor(0.f, 1.f, 0.f));
VertexColors.Add(FLinearColor(1.f, 1.f, 0.f));
VertexColors.Add(FLinearColor(0.f, 1.f, 1.f));
CustomMesh->CreateMeshSection_LinearColor(0, Vertices, Triangles, TArray<FVector>(), TArray<FVector2D>(), VertexColors, TArray<FProcMeshTangent>(),true);
}
// Called every frame
void AMyActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
//Moving the mesh
for (int32 index = 0; index < Vertices.Num(); index++)
{
//Moving each vertex 1 unit forward
Vertices[index] += FVector(1, 0, 0);
}
CustomMesh->UpdateMeshSection(0, Vertices, TArray<FVector>(), TArray<FVector2D>(), TArray<FColor>(), TArray<FProcMeshTangent>());
}
| 26.475728
| 154
| 0.693803
|
devilmhzx
|
e713952134a02313c3046472b135e0275d6ab776
| 4,053
|
cpp
|
C++
|
Connections/MSPBSL_ConnectionFRAMFamily.cpp
|
KirillSmirnov/trik-mspbsl-library
|
ee5e5bfe7aa00a8421a4d8203c82adb5445ecbe0
|
[
"BSD-3-Clause"
] | 1
|
2015-11-29T18:33:02.000Z
|
2015-11-29T18:33:02.000Z
|
Connections/MSPBSL_ConnectionFRAMFamily.cpp
|
KirillSmirnov/trik-mspbsl-library
|
ee5e5bfe7aa00a8421a4d8203c82adb5445ecbe0
|
[
"BSD-3-Clause"
] | null | null | null |
Connections/MSPBSL_ConnectionFRAMFamily.cpp
|
KirillSmirnov/trik-mspbsl-library
|
ee5e5bfe7aa00a8421a4d8203c82adb5445ecbe0
|
[
"BSD-3-Clause"
] | 1
|
2015-11-29T18:33:13.000Z
|
2015-11-29T18:33:13.000Z
|
/*
* MSPBSL_ConnectionFRAMFamily
*
* A subclass to add FRAM specific connection functions
*
* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/
*
*
* 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 Texas Instruments Incorporated 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 "MSPBSL_ConnectionFRAMFamily.h"
/***************************************************************************//**
* FRAM General Connection Class Constructor.
*
* Creates a 5/6xx General Connection using the supplied parameters
*
* \param initString an initialization string for the connection
*
* \return a MSPBSL_ConnectionFRAMFamily class
******************************************************************************/
MSPBSL_ConnectionFRAMFamily::MSPBSL_ConnectionFRAMFamily(std::string initString) : MSPBSL_Connection5xxUART( initString)
{
}
/***************************************************************************//**
* MSPBSL_ConnectionFRAMFamily Class Destructor.
*
******************************************************************************/
MSPBSL_ConnectionFRAMFamily::~MSPBSL_ConnectionFRAMFamily(void)
{
}
/***************************************************************************//**
* A function to send the mass erase command
*
* This function handles the special case of Mass erase for FRAM devices.
* This means it sends the mass erase, then reinitializes the COM port to 9600 baud
* then unlocks the BSL again using the default password
*
* \return A string describing the error code
******************************************************************************/
uint16_t MSPBSL_ConnectionFRAMFamily::massErase(void)
{
uint16_t retValue;
retValue = MSPBSL_Connection5xx::massErase(); // after a mass erase, the FRAM devices reset themselves
if( retValue != ACK )
{
return retValue;
}
thePacketHandler->getPhysicalInterface()->physicalInterfaceCommand("BAUD:9600");
retValue = MSPBSL_Connection5xx::RX_Password();
if( retValue != ACK )
{
return retValue;
}
return retValue;
}
/***************************************************************************//**
* An error description function
*
* This function is meant to return a string which fully describes an error code
* which could be returned from any function within this class
*
* \param err the 16 bit error code
*
* \return A string describing the error code
******************************************************************************/
std::string MSPBSL_ConnectionFRAMFamily::getErrorInformation( uint16_t err )
{
return MSPBSL_Connection5xxUART::getErrorInformation( err );
}
| 39.349515
| 120
| 0.64224
|
KirillSmirnov
|
e715b9f40aea2d6f5274f66a1977e0506ec75303
| 2,172
|
cpp
|
C++
|
VS2005/DigiLEDv2.0/DesignApp/EthernetPort.cpp
|
cuongquay/led-matrix-display
|
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
|
[
"Apache-2.0"
] | null | null | null |
VS2005/DigiLEDv2.0/DesignApp/EthernetPort.cpp
|
cuongquay/led-matrix-display
|
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
|
[
"Apache-2.0"
] | null | null | null |
VS2005/DigiLEDv2.0/DesignApp/EthernetPort.cpp
|
cuongquay/led-matrix-display
|
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
|
[
"Apache-2.0"
] | 1
|
2020-06-13T08:34:26.000Z
|
2020-06-13T08:34:26.000Z
|
// EthernetPort.cpp : implementation file
//
#include "stdafx.h"
#include "DigiLED.h"
#include "EthernetPort.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CEthernetPort
CEthernetPort::CEthernetPort()
{
BOOL bRet = FALSE;
bRet = Create(_stData.m_nClientPort,SOCK_DGRAM,FD_READ|FD_WRITE);
if (bRet != TRUE){
UINT uErr = GetLastError();
TCHAR szError[256];
wsprintf(szError, _T("Server Receive Socket Create() failed: %d"), uErr);
AfxMessageBox(szError);
}
m_bReadyToSend = true;
}
CEthernetPort::~CEthernetPort()
{
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CEthernetPort, CAsyncSocket)
//{{AFX_MSG_MAP(CEthernetPort)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// CEthernetPort member functions
void CEthernetPort::OnReceive(int nErrorCode)
{
::SendMessage(m_hWndMsg,mg_nDefaultEthMsg,WPARAM(0),LPARAM(nErrorCode));
CAsyncSocket::OnReceive(nErrorCode);
}
void CEthernetPort::OnSend(int nErrorCode)
{
CAsyncSocket::OnSend(nErrorCode);
}
int CEthernetPort::Send(const void* lpBuf, int nBufLen, int nFlags)
{
if ( ! m_bReadyToSend )
return(false);
m_bReadyToSend = false;
int dwBytes;
CAsyncSocket *paSocket = this;
// Specify destination here (IP number obscured - could use computer name instead)
if ((dwBytes = CAsyncSocket::SendTo((LPCTSTR)lpBuf,nBufLen,_stData.m_nClientPort,_stData.m_csClientIp)) == SOCKET_ERROR)
{
UINT uErr = GetLastError();
if (uErr != WSAEWOULDBLOCK)
{
TCHAR szError[256];
wsprintf(szError, _T("Can not send to %s on port %d ."),_stData.m_csClientIp,_stData.m_nClientPort);
AfxMessageBox(szError);
}
return(false);
}
Sleep(1);
return(true);
}
| 26.814815
| 129
| 0.587017
|
cuongquay
|
e7194a93396469de665e89f31dff41caaf4acb9e
| 3,285
|
cxx
|
C++
|
Testing/Code/Adapter/TestImageToVtk.cxx
|
Piyusha23/IAFEMesh
|
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
|
[
"BSD-4-Clause-UC"
] | null | null | null |
Testing/Code/Adapter/TestImageToVtk.cxx
|
Piyusha23/IAFEMesh
|
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
|
[
"BSD-4-Clause-UC"
] | null | null | null |
Testing/Code/Adapter/TestImageToVtk.cxx
|
Piyusha23/IAFEMesh
|
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
|
[
"BSD-4-Clause-UC"
] | null | null | null |
/*=========================================================================
*
* Program: IaFeMesh
* Module: $RCSfile: TestImageToVtk.cxx,v $
* Language: C++
* Date: $Date: 2012/12/07 19:08:59 $
* Version: $Revision: 1.1.1.1 $
*
* Copyright (c) Nicole Grosland. All rights reserved.
*
* This software is distributed WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the above copyright notices for more information.
*
*=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
#include "vtkPoints.h"
#include "vtkHexahedron.h"
#include "vtkTetra.h"
#include "itkImage.h"
#include "itkMesh.h"
#include "itkVertexCell.h"
#include "itkImageToHexahedronMeshSource.h"
#include "vtkUnstructuredGridWriter.h"
#include "vtkUnstructuredGrid.h"
#include "itkAutomaticTopologyMeshSource.h"
#include "itkImageToVTKImageFilter.h"
int main( int argc, char * argv[] )
{
std::cout << "TestImageToVtk:" << std::endl;
typedef signed short PixelType;
typedef itk::Image< PixelType, 3 > ImageType;
ImageType::Pointer image = ImageType::New();
const ImageType::SizeType size = {{10,10,10}};
const ImageType::IndexType index = {{0,0,0}};
double imageSpacing[3];
imageSpacing[0] = 2.0; imageSpacing[1] = 2.0; imageSpacing[2] = 2.0;
ImageType::RegionType region;
region.SetSize( size );
region.SetIndex( index );
image->SetLargestPossibleRegion( region );
image->SetBufferedRegion( region );
image->SetRequestedRegion( region );
image->SetSpacing(imageSpacing);
image->Allocate();
for (int x=0;x<1;x++)
{
for (int y=0;y<2;y++)
{
for (int z=0;z<3;z++)
{
ImageType::IndexType tmpIndex;
tmpIndex[0] = x; tmpIndex[1] = y; tmpIndex[2] = z;
image->SetPixel(tmpIndex, 1);
}
}
}
typedef itk::ImageToVTKImageFilter<ImageType> ImageToVtkType;
ImageToVtkType::Pointer toVtkFilter = ImageToVtkType::New();
toVtkFilter->SetInput( image );
toVtkFilter->Update();
vtkImageData *vtkImage = toVtkFilter->GetOutput();
int dims[3];
vtkImage->GetDimensions(dims);
if ((dims[0] != 10) || (dims[1] != 10) || (dims[2] != 10))
{
std::cout << "Error: Invalid VTK image dimensions" << std::endl;
return EXIT_FAILURE;
}
double res[3];
vtkImage->GetSpacing(res);
if ((res[0] != 2.0) || (res[1] != 2.0) || (res[2] != 2.0))
{
std::cout << "Error: Invalid VTK image spacing" << std::endl;
return EXIT_FAILURE;
}
for (int x=0;x<10;x++)
{
for (int y=0;y<10;y++)
{
for (int z=0;z<10;z++)
{
PixelType *ptr = (PixelType *) vtkImage->GetScalarPointer(x,y,z);
PixelType result;
if ((x < 1) && (y < 2) && (z < 3))
{
result = 1;
}
else
{
result = 0;
}
if (*ptr != result)
{
std::cout << "Error: Invalid VTK voxel data" << std::endl;
return EXIT_FAILURE;
}
}
}
}
return EXIT_SUCCESS;
}
| 24.699248
| 77
| 0.567123
|
Piyusha23
|
e71a80ed3166f9665841a0b43c1c65ee2919c8e1
| 2,304
|
cpp
|
C++
|
dlgSine.cpp
|
RDamman/SpeakerWorkshop
|
87a38d04197a07a9a7878b3f60d5e0706782163c
|
[
"OML"
] | 12
|
2019-06-07T10:06:41.000Z
|
2021-03-22T22:13:59.000Z
|
dlgSine.cpp
|
RDamman/SpeakerWorkshop
|
87a38d04197a07a9a7878b3f60d5e0706782163c
|
[
"OML"
] | 1
|
2019-05-09T07:38:12.000Z
|
2019-07-10T04:20:55.000Z
|
dlgSine.cpp
|
RDamman/SpeakerWorkshop
|
87a38d04197a07a9a7878b3f60d5e0706782163c
|
[
"OML"
] | 3
|
2020-09-08T08:27:33.000Z
|
2021-05-13T09:25:43.000Z
|
// dlgsine.cpp : implementation file
//
#include "stdafx.h"
#include "audtest.h"
#include "zFormEdt.h"
#include "dlgsine.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgSine property page
IMPLEMENT_DYNCREATE(CDlgSine, CPropertyPage)
CDlgSine::CDlgSine() : CPropertyPage(CDlgSine::IDD), m_cPhase(), m_cFreq()
{
EnableAutomation();
//{{AFX_DATA_INIT(CDlgSine)
//}}AFX_DATA_INIT
}
CDlgSine::~CDlgSine()
{
}
void CDlgSine::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. This implementation deletes the
// object. Add additional cleanup required for your object before
// deleting it from memory.
delete this;
}
void CDlgSine::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
m_cPhase.DDX_Value( pDX, m_fPhase);
m_cFreq.DDX_Value( pDX, m_fFreq);
//{{AFX_DATA_MAP(CDlgSine)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgSine, CPropertyPage)
//{{AFX_MSG_MAP(CDlgSine)
ON_NOTIFY(UDN_DELTAPOS, IDC_SCRL1, OnDeltaposScrl1)
ON_NOTIFY(UDN_DELTAPOS, IDC_SCRL2, OnDeltaposScrl2)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CDlgSine, CDialog)
//{{AFX_DISPATCH_MAP(CDlgSine)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgSine message handlers
BOOL CDlgSine::OnInitDialog()
{
m_cFreq.Subclass( this, IDC_FREQ, IDC_SCRL1);
m_cFreq.SetLimits( 1.0f, 20000.0f);
m_cPhase.Subclass( this, IDC_PHASE, IDC_SCRL2);
m_cPhase.SetLimits( -180.0f, 360.0f);
CPropertyPage::OnInitDialog();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDlgSine::OnDeltaposScrl1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
m_cFreq.ProcessDelta( pNMUpDown->iDelta); // that's it....
*pResult = 0;
}
void CDlgSine::OnDeltaposScrl2(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
m_cPhase.ProcessDelta( pNMUpDown->iDelta); // that's it....
*pResult = 0;
}
| 22.153846
| 77
| 0.684462
|
RDamman
|
e7223fbe5999705582cc48031e4be3ffac9a09ac
| 1,834
|
cc
|
C++
|
tensorflow/contrib/persona/kernels/agd-format/fastq_chunker.cc
|
epfl-vlsc/persona-system
|
2aad40d908ae63239f5d546a56264922a55b99fc
|
[
"Apache-2.0"
] | 6
|
2017-08-07T14:05:41.000Z
|
2020-02-28T03:57:56.000Z
|
tensorflow/contrib/persona/kernels/agd-format/fastq_chunker.cc
|
epfl-vlsc/persona-system
|
2aad40d908ae63239f5d546a56264922a55b99fc
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/contrib/persona/kernels/agd-format/fastq_chunker.cc
|
epfl-vlsc/persona-system
|
2aad40d908ae63239f5d546a56264922a55b99fc
|
[
"Apache-2.0"
] | null | null | null |
#include "fastq_chunker.h"
namespace tensorflow {
using namespace std;
// note: copies the shared ptr and any custom deleter (which we'll use)
FastqChunker::FastqChunker(shared_ptr<FastqResource::FileResource> &data, const size_t chunk_size) :
data_(data), chunk_size_(chunk_size) {
auto *file_data = data->get();
current_ptr_ = file_data->data();
end_ptr_ = current_ptr_ + file_data->size();
file_use_count_ = make_shared<atomic<unsigned int>>(0);
done_flag_ = make_shared<volatile bool>(false);
*done_flag_ = false;
}
bool FastqChunker::next_chunk(FastqResource &resource) {
const char *record_base = current_ptr_;
size_t record_count = 0;
while (record_count < chunk_size_ && advance_record()) {
record_count++;
}
// happens if the underlying pointer arithmetic detectse that this is already exhausted
if (record_count == 0) {
*done_flag_ = true;
return false;
}
//create a fastq resource
resource = FastqResource(data_, file_use_count_, done_flag_, record_base, current_ptr_, record_count);
return true;
}
// just assume the basic 4-line format for now
bool FastqChunker::advance_record() {
for (int i = 0; i < 4; ++i) {
if (!advance_line()) {
return false;
}
}
return true;
}
bool FastqChunker::advance_line() {
if (current_ptr_ == end_ptr_) {
return false;
} else {
while (current_ptr_ < end_ptr_ && *current_ptr_ != '\n') {
current_ptr_++; // yes, you can put this in the 2nd clause expression, but that is confusing
}
// in this case, we want to advance OVER the '\n', as that is what caused us to exit the loop
if (current_ptr_ < end_ptr_) {
current_ptr_++;
}
return true;
}
}
} // namespace tensorflow {
| 29.111111
| 106
| 0.650491
|
epfl-vlsc
|
e7233b1f3f597976f7a05aa974c24e2cdc0102c9
| 1,819
|
cpp
|
C++
|
examples/controller/src/LogWindowGUI.cpp
|
RichardTea/RDMnet
|
fb48866be0396beb7875ba515ad966f19aa46350
|
[
"Apache-2.0"
] | null | null | null |
examples/controller/src/LogWindowGUI.cpp
|
RichardTea/RDMnet
|
fb48866be0396beb7875ba515ad966f19aa46350
|
[
"Apache-2.0"
] | null | null | null |
examples/controller/src/LogWindowGUI.cpp
|
RichardTea/RDMnet
|
fb48866be0396beb7875ba515ad966f19aa46350
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* Copyright 2019 ETC Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************
* This file is a part of RDMnet. For more information, go to:
* https://github.com/ETCLabs/RDMnet
*****************************************************************************/
#include "LogWindowGUI.h"
#include <sstream>
LogWindowGUI::LogWindowGUI(QWidget* parent) : QDialog(parent)
{
ui.setupUi(this);
connect(this, SIGNAL(appendText(const QString&)), this, SLOT(processAppendText(const QString&)), Qt::AutoConnection);
connect(this, SIGNAL(clearText()), this, SLOT(processClearText()), Qt::AutoConnection);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
}
LogOutputStream& LogWindowGUI::operator<<(const std::string& str)
{
QString qstr(str.data());
emit appendText(qstr);
return (*this);
}
void LogWindowGUI::clear()
{
emit clearText();
}
void LogWindowGUI::processAppendText(const QString& text)
{
ui.outputTextEdit->moveCursor(QTextCursor::End);
ui.outputTextEdit->insertPlainText(text);
ui.outputTextEdit->moveCursor(QTextCursor::End);
}
void LogWindowGUI::processClearText()
{
ui.outputTextEdit->setText("");
}
| 31.362069
| 119
| 0.641561
|
RichardTea
|
e7243d030658f9cc9b1e9f66f18f3c6bb920e37b
| 109
|
cpp
|
C++
|
modules/features/src/local_estimator.cpp
|
byiii/clone_v4r_j
|
628359c7ba19389004618defd6a8d8ab5af35967
|
[
"MIT"
] | null | null | null |
modules/features/src/local_estimator.cpp
|
byiii/clone_v4r_j
|
628359c7ba19389004618defd6a8d8ab5af35967
|
[
"MIT"
] | null | null | null |
modules/features/src/local_estimator.cpp
|
byiii/clone_v4r_j
|
628359c7ba19389004618defd6a8d8ab5af35967
|
[
"MIT"
] | null | null | null |
#include <v4r/features/local_estimator.h>
template class V4R_EXPORTS v4r::LocalEstimator<pcl::PointXYZ>;
| 27.25
| 63
| 0.788991
|
byiii
|
e7260fdb6792992dc5ddb223f1032f469c155c23
| 15,580
|
cxx
|
C++
|
src/extern/dcmtk-3.5.4/dcmpstat/libsrc/dvpsspl.cxx
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 2
|
2020-05-21T07:06:07.000Z
|
2021-06-28T02:14:34.000Z
|
src/extern/dcmtk-3.5.4/dcmpstat/libsrc/dvpsspl.cxx
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | null | null | null |
src/extern/dcmtk-3.5.4/dcmpstat/libsrc/dvpsspl.cxx
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 6
|
2016-03-21T19:53:18.000Z
|
2021-06-08T18:06:03.000Z
|
/*
*
* Copyright (C) 1998-2005, OFFIS
*
* This software and supporting documentation were developed by
*
* Kuratorium OFFIS e.V.
* Healthcare Information and Communication Systems
* Escherweg 2
* D-26121 Oldenburg, Germany
*
* THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND OFFIS MAKES NO WARRANTY
* REGARDING THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR
* FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR
* ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND
* PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
*
* Module: dcmpstat
*
* Author: Marco Eichelberg
*
* Purpose:
* classes: DVPSStoredPrint_PList
*
* Last Update: $Author: meichel $
* Update Date: $Date: 2005/12/08 15:46:48 $
* CVS/RCS Revision: $Revision: 1.11 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmpstat/dvpsspl.h"
#include "dcmtk/dcmpstat/dvpssp.h" /* for DVPSStoredPrint */
#include "dcmtk/dcmpstat/dvpsib.h" /* for DVPSImageBoxContent */
#include "dcmtk/dcmpstat/dviface.h"
#include "dcmtk/dcmpstat/dvpsdef.h"
#include "dcmtk/dcmpstat/dvpsov.h" /* for DVPSOverlay, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsgl.h" /* for DVPSGraphicLayer, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsrs.h" /* for DVPSReferencedSeries, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsal.h" /* for DVPSOverlayCurveActivationLayer, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsga.h" /* for DVPSGraphicAnnotation, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpscu.h" /* for DVPSCurve, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsvl.h" /* for DVPSVOILUT, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsvw.h" /* for DVPSVOIWindow, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsda.h" /* for DVPSDisplayedArea, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpssv.h" /* for DVPSSoftcopyVOI, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsab.h" /* for DVPSAnnotationContent, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpstx.h" /* for DVPSTextObject, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsgr.h" /* for DVPSGraphicObject, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsri.h" /* for DVPSReferencedImage, needed by MSVC5 with STL */
DVPSStoredPrint_PList::DVPSStoredPrint_PList()
: list_()
, logstream(&ofConsole)
, verboseMode(OFFalse)
, debugMode(OFFalse)
{
}
DVPSStoredPrint_PList::DVPSStoredPrint_PList(const DVPSStoredPrint_PList &arg)
: list_()
, logstream(arg.logstream)
, verboseMode(arg.verboseMode)
, debugMode(arg.debugMode)
{
OFListConstIterator(DVPSStoredPrint *) first = arg.list_.begin();
OFListConstIterator(DVPSStoredPrint *) last = arg.list_.end();
while (first != last)
{
list_.push_back((*first)->clone());
++first;
}
}
DVPSStoredPrint_PList::~DVPSStoredPrint_PList()
{
clear();
}
void DVPSStoredPrint_PList::clear()
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
delete (*first);
first = list_.erase(first);
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmBoxSet(
DVConfiguration& cfg,
const char *cfgname,
T_DIMSE_Message& rq,
DcmDataset *rqDataset,
T_DIMSE_Message& rsp,
DcmDataset *& rspDataset,
OFBool presentationLUTnegotiated,
DVPSPresentationLUT_PList& globalPresentationLUTList)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
OFBool found = OFFalse;
while ((first != last) && (!found))
{
if ((*first)->isFilmBoxInstance(rq.msg.NSetRQ.RequestedSOPInstanceUID)) found = OFTrue;
else ++first;
}
if (found)
{
DVPSStoredPrint *newSP = new DVPSStoredPrint(*(*first));
if (newSP)
{
if (newSP->printSCPSet(cfg, cfgname, rqDataset, rsp, rspDataset, presentationLUTnegotiated, globalPresentationLUTList))
{
// N-SET successful, replace entry in list
delete (*first);
list_.erase(first);
list_.push_back(newSP);
} else delete newSP;
} else {
if (verboseMode)
{
logstream->lockCerr() << "error: cannot update film box, out of memory." << endl;
logstream->unlockCerr();
}
rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
} else {
// film box does not exist or wrong instance UID
if (verboseMode)
{
logstream->lockCerr() << "error: cannot update film box, object not found." << endl;
logstream->unlockCerr();
}
rsp.msg.NSetRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
void DVPSStoredPrint_PList::printSCPBasicGrayscaleImageBoxSet(
DVInterface& cfg,
const char *cfgname,
T_DIMSE_Message& rq,
DcmDataset *rqDataset,
T_DIMSE_Message& rsp,
DcmDataset *& rspDataset,
OFBool presentationLUTnegotiated)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
DVPSStoredPrint *sp = NULL;
DVPSImageBoxContent *newib = NULL;
while ((first != last) && (sp == NULL))
{
newib = (*first)->duplicateImageBox(rq.msg.NSetRQ.RequestedSOPInstanceUID);
if (newib) sp = *first; else ++first;
}
if (newib && sp)
{
DcmFileFormat imageFile;
DcmDataset *imageDataset = imageFile.getDataset();
if (newib->printSCPSet(cfg, cfgname, rqDataset, rsp, rspDataset, *imageDataset,
sp->getReferencedPresentationLUTAlignment(), presentationLUTnegotiated))
{
if (EC_Normal == sp->writeHardcopyImageAttributes(*imageDataset))
{
// check for image position clash
if (sp->haveImagePositionClash(rq.msg.NSetRQ.RequestedSOPInstanceUID, newib->getImageBoxPosition()))
{
delete rspDataset;
rspDataset = NULL;
if (verboseMode)
{
logstream->lockCerr() << "error: cannot update basic grayscale image box, image position collision." << endl;
logstream->unlockCerr();
}
rsp.msg.NSetRSP.DimseStatus = STATUS_N_InvalidAttributeValue;
} else {
if (EC_Normal == cfg.saveFileFormatToDB(imageFile))
{
sp->replaceImageBox(newib);
} else {
delete rspDataset;
rspDataset = NULL;
rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
} else {
delete rspDataset;
rspDataset = NULL;
if (verboseMode)
{
logstream->lockCerr() << "error: cannot update basic grayscale image box, out of memory." << endl;
logstream->unlockCerr();
}
rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
} else {
// image box does not exist or wrong instance UID
if (verboseMode)
{
logstream->lockCerr() << "error: cannot update basic grayscale image box, object not found." << endl;
logstream->unlockCerr();
}
rsp.msg.NSetRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmBoxAction(
DVInterface& cfg,
const char *cfgname,
T_DIMSE_Message& rq,
T_DIMSE_Message& rsp,
DVPSPresentationLUT_PList& globalPresentationLUTList)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
OFBool found = OFFalse;
while ((first != last) && (!found))
{
if ((*first)->isFilmBoxInstance(rq.msg.NActionRQ.RequestedSOPInstanceUID)) found = OFTrue;
else ++first;
}
if (found)
{
DcmFileFormat spFile;
DcmDataset *spDataset = spFile.getDataset();
DVPSStoredPrint *sp = *first;
OFBool writeRequestedImageSize = cfg.getTargetPrinterSupportsRequestedImageSize(cfgname);
sp->updatePresentationLUTList(globalPresentationLUTList);
sp->clearInstanceUID();
if ((*first)->emptyPageWarning())
{
if (verboseMode)
{
logstream->lockCerr() << "warning: empty page, will not be stored in database" << endl;
logstream->unlockCerr();
}
if (STATUS_Success == rsp.msg.NActionRSP.DimseStatus) rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFB_Warn_EmptyPage;
} else {
if (EC_Normal == sp->write(*spDataset, writeRequestedImageSize, OFFalse, OFFalse, OFTrue))
{
if (EC_Normal == cfg.saveFileFormatToDB(spFile))
{
// N-ACTION successful.
} else {
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
} else {
if (verboseMode)
{
logstream->lockCerr() << "error: cannot print basic film box, out of memory." << endl;
logstream->unlockCerr();
}
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
} else {
// film box does not exist or wrong instance UID
if (verboseMode)
{
logstream->lockCerr() << "error: cannot print film box, object not found." << endl;
logstream->unlockCerr();
}
rsp.msg.NActionRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmSessionAction(
DVInterface& cfg,
const char *cfgname,
T_DIMSE_Message& rsp,
DVPSPresentationLUT_PList& globalPresentationLUTList)
{
if (size() > 0)
{
OFBool writeRequestedImageSize = cfg.getTargetPrinterSupportsRequestedImageSize(cfgname);
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
DcmFileFormat spFile;
DcmDataset *spDataset = spFile.getDataset();
(*first)->updatePresentationLUTList(globalPresentationLUTList);
(*first)->clearInstanceUID();
if ((*first)->emptyPageWarning())
{
if (verboseMode)
{
logstream->lockCerr() << "warning: empty page, will not be stored in database" << endl;
logstream->unlockCerr();
}
if (STATUS_Success == rsp.msg.NActionRSP.DimseStatus) rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFS_Warn_EmptyPage;
} else {
if (EC_Normal == (*first)->write(*spDataset, writeRequestedImageSize, OFFalse, OFFalse, OFTrue))
{
if (EC_Normal == cfg.saveFileFormatToDB(spFile))
{
// success for this film box
} else {
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
} else {
if (verboseMode)
{
logstream->lockCerr() << "error: cannot print basic film session, out of memory." << endl;
logstream->unlockCerr();
}
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
++first;
}
} else {
// no film boxes to print
if (verboseMode)
{
logstream->lockCerr() << "error: cannot print film session, no film box." << endl;
logstream->unlockCerr();
}
rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFS_Fail_NoFilmBox;
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmBoxDelete(T_DIMSE_Message& rq, T_DIMSE_Message& rsp)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
OFBool found = OFFalse;
while ((first != last) && (!found))
{
if ((*first)->isFilmBoxInstance(rq.msg.NDeleteRQ.RequestedSOPInstanceUID)) found = OFTrue;
else ++first;
}
if (found)
{
delete (*first);
list_.erase(first);
} else {
// film box does not exist or wrong instance UID
if (verboseMode)
{
logstream->lockCerr() << "error: cannot delete film box with instance UID '" << rq.msg.NDeleteRQ.RequestedSOPInstanceUID << "': object does not exist." << endl;
logstream->unlockCerr();
}
rsp.msg.NDeleteRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
OFBool DVPSStoredPrint_PList::haveFilmBoxInstance(const char *uid)
{
if (uid==NULL) return OFFalse;
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
if ((*first)->isFilmBoxInstance(uid)) return OFTrue;
else ++first;
}
return OFFalse;
}
OFBool DVPSStoredPrint_PList::usesPresentationLUT(const char *uid)
{
if (uid==NULL) return OFFalse;
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
if ((*first)->usesPresentationLUT(uid)) return OFTrue;
else ++first;
}
return OFFalse;
}
void DVPSStoredPrint_PList::setLog(OFConsole *stream, OFBool verbMode, OFBool dbgMode)
{
if (stream) logstream = stream; else logstream = &ofConsole;
verboseMode = verbMode;
debugMode = dbgMode;
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
(*first)->setLog(logstream, verbMode, dbgMode);
++first;
}
}
OFBool DVPSStoredPrint_PList::matchesPresentationLUT(DVPSPrintPresentationLUTAlignment align) const
{
OFBool result = OFTrue;
OFListConstIterator(DVPSStoredPrint *) first = list_.begin();
OFListConstIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
result = result && (*first)->matchesPresentationLUT(align);
++first;
}
return result;
}
void DVPSStoredPrint_PList::overridePresentationLUTSettings(
DcmUnsignedShort& newIllumination,
DcmUnsignedShort& newReflectedAmbientLight,
DcmUniqueIdentifier& newReferencedPLUT,
DVPSPrintPresentationLUTAlignment newAlignment)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
(*first)->overridePresentationLUTSettings(newIllumination, newReflectedAmbientLight, newReferencedPLUT, newAlignment);
++first;
}
}
/*
* $Log: dvpsspl.cc,v $
* Revision 1.11 2005/12/08 15:46:48 meichel
* Changed include path schema for all DCMTK header files
*
* Revision 1.10 2004/02/04 15:57:49 joergr
* Removed acknowledgements with e-mail addresses from CVS log.
*
* Revision 1.9 2003/06/12 18:23:11 joergr
* Modified code to use const_iterators where appropriate (required for STL).
*
* Revision 1.8 2003/06/04 12:30:29 meichel
* Added various includes needed by MSVC5 with STL
*
* Revision 1.7 2003/06/04 10:18:07 meichel
* Replaced private inheritance from template with aggregation
*
* Revision 1.6 2001/06/01 15:50:38 meichel
* Updated copyright header
*
* Revision 1.5 2001/05/25 10:07:59 meichel
* Corrected some DIMSE error status codes for Print SCP
*
* Revision 1.4 2000/06/08 10:44:38 meichel
* Implemented Referenced Presentation LUT Sequence on Basic Film Session level.
* Empty film boxes (pages) are not written to file anymore.
*
* Revision 1.3 2000/06/07 13:17:09 meichel
* now using DIMSE status constants and log facilities defined in dcmnet
*
* Revision 1.2 2000/06/02 16:01:07 meichel
* Adapted all dcmpstat classes to use OFConsole for log and error output
*
* Revision 1.1 2000/05/31 12:58:12 meichel
* Added initial Print SCP support
*
*
*/
| 32.869198
| 166
| 0.670924
|
OpenXIP
|
e729445ee0c175f4bb6c3f16b971109baa550fcc
| 464
|
cpp
|
C++
|
Jubin/week1/boj-10818.cpp
|
lee20h/ALPS_2020_Summer_Study
|
3656d5c6ab44f7f43c1f8c691e75352495c76adc
|
[
"Apache-2.0"
] | 1
|
2020-08-02T14:30:03.000Z
|
2020-08-02T14:30:03.000Z
|
Jubin/week1/boj-10818.cpp
|
alps-jbnu/ALPS_2020_Summer_Study
|
3656d5c6ab44f7f43c1f8c691e75352495c76adc
|
[
"Apache-2.0"
] | null | null | null |
Jubin/week1/boj-10818.cpp
|
alps-jbnu/ALPS_2020_Summer_Study
|
3656d5c6ab44f7f43c1f8c691e75352495c76adc
|
[
"Apache-2.0"
] | 2
|
2020-07-09T14:53:29.000Z
|
2020-07-17T10:39:00.000Z
|
#include <stack>
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
stack<int> nums;
stack<int> mins;
stack<int> maxs;
int N;
cin >> N;
while (N--)
{
int x;
cin >> x;
nums.push(x);
if (mins.empty() || x < mins.top())
{
mins.push(x);
}
if (maxs.empty() || x > maxs.top())
{
maxs.push(x);
}
}
cout << mins.top() << ' ' << maxs.top();
}
| 12.888889
| 42
| 0.484914
|
lee20h
|
e72a949288cd328f3d49ae73cb19126ecc1c38c3
| 1,125
|
hpp
|
C++
|
include/systems/DebugSystem.hpp
|
zanshi/transcension3d
|
304374e83d709d73358d225567676ad7048509e6
|
[
"MIT"
] | 7
|
2015-05-30T13:56:34.000Z
|
2017-11-04T17:58:26.000Z
|
include/systems/DebugSystem.hpp
|
zanshi/transcension3d
|
304374e83d709d73358d225567676ad7048509e6
|
[
"MIT"
] | null | null | null |
include/systems/DebugSystem.hpp
|
zanshi/transcension3d
|
304374e83d709d73358d225567676ad7048509e6
|
[
"MIT"
] | null | null | null |
//
// Created by Benjamin Wiberg on 2015-04-10.
//
#pragma once
#include <entityx/entityx.h>
#include "glm/glm.hpp"
#include "events/RenderEvent.hpp"
#include "events/MovementEvent.hpp"
#include "events/ViewChangedEvent.hpp"
namespace ex = entityx;
namespace sw {
class DebugSystem : public ex::System<DebugSystem>, public ex::Receiver<DebugSystem> {
public:
DebugSystem(std::ostream &debug_stream);
void configure(ex::EventManager &events) override;
void update(ex::EntityManager &es, ex::EventManager &events, ex::TimeDelta dt);
void receive(const RenderEvent &render_event);
void debugRenderEvents();
void receive(const MovementEvent &movement_event);
void debugMovementEvents();
void receive(const ViewChangedEvent &view_changed_event);
void debugViewChangedEvents();
std::ostream &debug_ostream_;
//* std::vector<ex::Entity> entities_to_debug_;
std::vector<RenderEvent> render_events_;
std::vector<MovementEvent> movement_events_;
std::vector<ViewChangedEvent> view_events_;
};
}
| 24.456522
| 90
| 0.689778
|
zanshi
|
e72b0765a34962ae1510529cc48700131d8d6242
| 7,934
|
hpp
|
C++
|
mdal/frmts/mdal_dynamic_driver.hpp
|
jmkerloch/MDAL
|
e3d9dc666fe84e0f71384c9e6c1cbabd9115fffc
|
[
"MIT"
] | 112
|
2018-04-10T09:15:35.000Z
|
2022-03-23T17:03:23.000Z
|
mdal/frmts/mdal_dynamic_driver.hpp
|
jmkerloch/MDAL
|
e3d9dc666fe84e0f71384c9e6c1cbabd9115fffc
|
[
"MIT"
] | 277
|
2018-04-10T11:40:53.000Z
|
2022-03-13T06:23:15.000Z
|
mdal/frmts/mdal_dynamic_driver.hpp
|
jmkerloch/MDAL
|
e3d9dc666fe84e0f71384c9e6c1cbabd9115fffc
|
[
"MIT"
] | 43
|
2018-04-26T00:03:22.000Z
|
2022-03-25T06:36:17.000Z
|
/*
MDAL - Mesh Data Abstraction Library (MIT License)
Copyright (C) 2020 Vincent Cloarec (vcloarec at gmail dot com)
*/
#ifndef MDAL_DYNAMIC_DRIVER_H
#define MDAL_DYNAMIC_DRIVER_H
#include "mdal_driver.hpp"
#include "mdal_utils.hpp"
#include "mdal.h"
#include <functional>
#include <set>
namespace MDAL
{
class DriverDynamic: public Driver
{
public:
~DriverDynamic() = default;
Driver *create() override;
bool canReadMesh( const std::string &uri ) override;
std::unique_ptr<Mesh> load( const std::string &uri, const std::string &meshName ) override;
//! Creates a dynamic driver from a library file
static Driver *create( const std::string &libFile );
private:
DriverDynamic( const std::string &name,
const std::string &longName,
const std::string &filters,
int capabilityFlags,
int maxVertexPerFace,
const Library &lib );
bool loadSymbols();
Library mLibrary;
int mCapabilityFlags = 0;
int mMaxVertexPerFace = std::numeric_limits<int>::max();
std::set<int> mMeshIds;
//************************************
std::function<bool ( const char * )> mCanReadMeshFunction;
std::function<int ( const char *, const char * )> mOpenMeshFunction;
};
class MeshDynamicDriver;
class MeshVertexIteratorDynamicDriver: public MeshVertexIterator
{
public:
MeshVertexIteratorDynamicDriver( const Library &library, int meshId );
size_t next( size_t vertexCount, double *coordinates ) override;
private:
Library mLibrary;
int mMeshId;
int mPosition = 0;
//************************************
std::function<int ( int, int, int, double * )> mVerticesFunction;
};
class MeshFaceIteratorDynamicDriver: public MeshFaceIterator
{
public:
MeshFaceIteratorDynamicDriver( const Library &library, int meshId );
size_t next( size_t faceOffsetsBufferLen,
int *faceOffsetsBuffer,
size_t vertexIndicesBufferLen,
int *vertexIndicesBuffer ) override;
private:
Library mLibrary;
int mMeshId;
int mPosition = 0;
//************************************
std::function<int ( int, int, int, int *, int, int * )> mFacesFunction;
};
class MeshEdgeIteratorDynamicDriver: public MeshEdgeIterator
{
public:
MeshEdgeIteratorDynamicDriver( const Library &library, int meshId );
size_t next( size_t edgeCount,
int *startVertexIndices,
int *endVertexIndices );
private:
Library mLibrary;
int mMeshId;
int mPosition = 0;
//************************************
std::function<int ( int, int, int, int *, int * )> mEdgesFunction;
};
class DatasetDynamicDriver
{
public:
DatasetDynamicDriver( int meshId,
int groupIndex,
int datasetIndex,
const Library &library );
virtual ~DatasetDynamicDriver();
virtual bool loadSymbol();
//! Removes stored data in memory (for drivers that support lazy loading)
void unloadData();
protected:
int mMeshId = -1;
int mGroupIndex = -1;
int mDatasetIndex = -1;
Library mLibrary;
//************************************
std::function<int ( int, int, int, int, int, double * )> mDataFunction;
std::function<void( int, int, int )> mUnloadFunction;
};
class DatasetDynamicDriver2D: public Dataset2D, public DatasetDynamicDriver
{
public:
DatasetDynamicDriver2D( DatasetGroup *parentGroup,
int meshId,
int groupIndex,
int datasetIndex,
const Library &library );
~DatasetDynamicDriver2D() override;
bool loadSymbol() override;
size_t scalarData( size_t indexStart, size_t count, double *buffer ) override;
size_t vectorData( size_t indexStart, size_t count, double *buffer ) override;
size_t activeData( size_t indexStart, size_t count, int *buffer ) override;
private:
std::function<int ( int, int, int, int, int, int * )> mActiveFlagsFunction;
};
class DatasetDynamicDriver3D: public Dataset3D, public DatasetDynamicDriver
{
public:
DatasetDynamicDriver3D( DatasetGroup *parentGroup,
int meshId,
int groupIndex,
int datasetIndex,
size_t volumes,
size_t maxVerticalLevelCount,
const Library &library );
~DatasetDynamicDriver3D() override;
bool loadSymbol() override;
size_t verticalLevelCountData( size_t indexStart, size_t count, int *buffer ) override;
size_t verticalLevelData( size_t indexStart, size_t count, double *buffer ) override;
size_t faceToVolumeData( size_t indexStart, size_t count, int *buffer ) override;
size_t scalarVolumesData( size_t indexStart, size_t count, double *buffer ) override;
size_t vectorVolumesData( size_t indexStart, size_t count, double *buffer ) override;
private:
std::function<int ( int, int, int, int, int, int * )> mVerticalLevelCountDataFunction;
std::function<int ( int, int, int, int, int, double * )> mVerticalLevelDataFunction;
std::function<int ( int, int, int, int, int, int * )> mFaceToVolumeDataFunction;
};
class MeshDynamicDriver: public Mesh
{
public:
MeshDynamicDriver( const std::string &driverName,
size_t faceVerticesMaximumCount,
const std::string &uri,
const Library &library,
int meshId );
~MeshDynamicDriver();
std::unique_ptr<MeshVertexIterator> readVertices() override;
std::unique_ptr<MeshEdgeIterator> readEdges() override;
std::unique_ptr<MeshFaceIterator> readFaces() override;
size_t verticesCount() const override;
size_t edgesCount() const override;
size_t facesCount() const override;
BBox extent() const override;
//! Set the projection from the source
void setProjection();
bool populateDatasetGroups();
//! Returns whether all the symbols have been loaded
bool loadSymbol();
private:
Library mLibrary;
int mId = -1;
//************************************
std::function<int ( int )> mMeshVertexCountFunction;
std::function<int ( int )> mMeshFaceCountFunction;
std::function<int ( int )> mMeshEdgeCountFunction;
std::function<void ( int, double *, double *, double *, double * )> mMeshExtentFunction;
std::function<const char *( int )> mMeshProjectionFunction;
std::function<int ( int )> mMeshDatasetGroupsCountFunction;
std::function<const char *( int, int )> mDatasetgroupNameFunction;
std::function<const char *( int, int )> mDatasetGroupReferencetimeFunction;
std::function<int ( int, int )> mDatasetGroupMetadataCountFunction;
std::function<const char *( int, int, int )> mDatasetGroupMetadataKeyFunction;
std::function<const char *( int, int, int )> mDatasetGroupMetadataValueFunction;
std::function < bool ( int, int, bool *, int *, int * )> mDatasetDescriptionFunction;
std::function < double( int, int, int, bool * )> mDatasetTimeFunction;
std::function<bool ( int, int, int )> mDatasetSupportActiveFlagFunction;
std::function<int ( int, int, int )> mDataset3DMaximumVerticalLevelCount;
std::function<int ( int, int, int )> mDataset3DVolumeCount;
std::function<void ( int )> mCloseMeshFunction;
};
}
#endif // MDAL_DYNAMIC_DRIVER_H
| 33.905983
| 97
| 0.610915
|
jmkerloch
|
e73309104094daf9e308f1ce9fd27ca9c322f3d7
| 704
|
hpp
|
C++
|
Libraries/Macaronlib/include/Macaronlib/ABI/Signals.hpp
|
Plunkerusr/podsOS
|
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
|
[
"MIT"
] | 21
|
2021-08-22T19:06:54.000Z
|
2022-03-31T12:44:30.000Z
|
Libraries/Macaronlib/include/Macaronlib/ABI/Signals.hpp
|
Plunkerusr/podsOS
|
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
|
[
"MIT"
] | 1
|
2021-09-01T22:55:59.000Z
|
2021-09-08T20:52:09.000Z
|
Libraries/Macaronlib/include/Macaronlib/ABI/Signals.hpp
|
Plunkerusr/podsOS
|
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
|
[
"MIT"
] | null | null | null |
#pragma once
#define SIGINVAL 0
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGILL 4
#define SIGTRAP 5
#define SIGABRT 6
#define SIGBUS 7
#define SIGFPE 8
#define SIGKILL 9
#define SIGUSR1 10
#define SIGSEGV 11
#define SIGUSR2 12
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM 15
#define SIGSTKFLT 16
#define SIGCHLD 17
#define SIGCONT 18
#define SIGSTOP 19
#define SIGTSTP 20
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGURG 23
#define SIGXCPU 24
#define SIGXFSZ 25
#define SIGVTALRM 26
#define SIGPROF 27
#define SIGWINCH 28
#define SIGIO 29
#define SIGINFO 30
#define SIGSYS 31
#define NSIG 32
// SIGPROCMASK
#define SIG_BLOCK 0
#define SIG_UNBLOCK 1
#define SIG_SETMASK 2
| 17.6
| 21
| 0.784091
|
Plunkerusr
|
e733a3bd9e622dc8bdf27512b9264c62710d8c31
| 3,342
|
cpp
|
C++
|
src/+cv/private/ExposureCompensator_.cpp
|
1123852253/mexopencv
|
17db690133299f561924a45e9092673a4df66c5b
|
[
"BSD-3-Clause"
] | 571
|
2015-01-04T06:23:19.000Z
|
2022-03-31T07:37:19.000Z
|
src/+cv/private/ExposureCompensator_.cpp
|
1123852253/mexopencv
|
17db690133299f561924a45e9092673a4df66c5b
|
[
"BSD-3-Clause"
] | 362
|
2015-01-06T14:20:46.000Z
|
2022-01-20T08:10:46.000Z
|
src/+cv/private/ExposureCompensator_.cpp
|
1123852253/mexopencv
|
17db690133299f561924a45e9092673a4df66c5b
|
[
"BSD-3-Clause"
] | 300
|
2015-01-20T03:21:27.000Z
|
2022-03-31T07:36:37.000Z
|
/**
* @file ExposureCompensator_.cpp
* @brief mex interface for cv::detail::ExposureCompensator
* @ingroup stitching
* @author Amro
* @date 2016
*/
#include "mexopencv.hpp"
#include "mexopencv_stitching.hpp"
#include "opencv2/stitching.hpp"
#include <typeinfo>
using namespace std;
using namespace cv;
using namespace cv::detail;
// Persistent objects
namespace {
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,Ptr<ExposureCompensator> > obj_;
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=2 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor is called. Create a new object from argument
if (method == "new") {
nargchk(nrhs>=3 && nlhs<=1);
obj_[++last_id] = createExposureCompensator(
rhs[2].toString(), rhs.begin() + 3, rhs.end());
plhs[0] = MxArray(last_id);
mexLock();
return;
}
// Big operation switch
Ptr<ExposureCompensator> obj = obj_[id];
if (obj.empty())
mexErrMsgIdAndTxt("mexopencv:error", "Object not found id=%d", id);
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
mexUnlock();
}
else if (method == "typeid") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(string(typeid(*obj).name()));
}
else if (method == "feed") {
nargchk(nrhs==5 && nlhs==0);
vector<Point> corners(rhs[2].toVector<Point>());
vector<UMat> images, masks;
{
vector<MxArray> arr(rhs[3].toVector<MxArray>());
images.reserve(arr.size());
for (vector<MxArray>::const_iterator it = arr.begin(); it != arr.end(); ++it)
images.push_back(it->toMat(CV_8U).getUMat(ACCESS_READ).clone());
}
{
vector<MxArray> arr(rhs[4].toVector<MxArray>());
masks.reserve(arr.size());
for (vector<MxArray>::const_iterator it = arr.begin(); it != arr.end(); ++it)
masks.push_back(it->toMat(CV_8U).getUMat(ACCESS_READ).clone());
}
obj->feed(corners, images, masks);
}
else if (method == "apply") {
nargchk(nrhs==6 && nlhs<=1);
int index = rhs[2].toInt();
Point corner(rhs[3].toPoint());
Mat image(rhs[4].toMat()); // CV_8U
Mat mask(rhs[5].toMat(CV_8U));
obj->apply(index, corner, image, mask);
plhs[0] = MxArray(image);
}
else if (method == "gains") {
nargchk(nrhs==2 && nlhs<=1);
Ptr<GainCompensator> p = obj.dynamicCast<GainCompensator>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Method only supported for GainCompensator");
vector<double> g(p->gains());
plhs[0] = MxArray(g);
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized operation %s", method.c_str());
}
| 32.134615
| 89
| 0.587672
|
1123852253
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.