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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f3db8aea81d9a96c8a550530e5560543ee84cc16 | 4,899 | hpp | C++ | source/exec/global_executor.hpp | stryku/cmakesl | e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326 | [
"BSD-3-Clause"
] | 51 | 2019-05-06T01:33:34.000Z | 2021-11-17T11:44:54.000Z | source/exec/global_executor.hpp | stryku/cmakesl | e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326 | [
"BSD-3-Clause"
] | 191 | 2019-05-06T18:31:24.000Z | 2020-06-19T06:48:06.000Z | source/exec/global_executor.hpp | stryku/cmakesl | e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326 | [
"BSD-3-Clause"
] | 3 | 2019-10-12T21:03:29.000Z | 2020-06-19T06:22:25.000Z | #pragma once
#include "common/strings_container_impl.hpp"
#include "decl_sema/declarative_import_handler.hpp"
#include "errors/errors_observer.hpp"
#include "exec/builtin_identifiers_observer.hpp"
#include "exec/cross_translation_unit_static_variables.hpp"
#include "exec/module_sema_tree_provider.hpp"
#include "sema/add_declarative_file_semantic_handler.hpp"
#include "sema/add_subdirectory_semantic_handler.hpp"
#include "sema/factories.hpp"
#include "sema/factories_provider.hpp"
#include "sema/import_handler.hpp"
#include "sema/qualified_contextes.hpp"
#include <memory>
#include <vector>
namespace cmsl {
namespace decl_sema {
class builtin_decl_namespace_context;
}
namespace facade {
class cmake_facade;
}
namespace sema {
class builtin_sema_context;
}
namespace exec {
class compiled_declarative_source;
class compiled_source;
class declarative_source_compiler;
class execution;
class source_compiler;
class global_executor
: public sema::add_subdirectory_semantic_handler
, public sema::add_declarative_file_semantic_handler
, public sema::import_handler
, public decl_sema::declarative_import_handler
, public module_sema_tree_provider
{
public:
explicit global_executor(const std::string& root_path,
facade::cmake_facade& cmake_facade,
errors::errors_observer& errors_observer);
~global_executor();
int execute(std::string source);
int execute_based_on_root_path();
add_subdirectory_result_t handle_add_subdirectory(
cmsl::string_view name,
const std::vector<std::unique_ptr<sema::expression_node>>& params)
override;
add_declarative_file_result_t handle_add_declarative_file(
cmsl::string_view name) override;
std::unique_ptr<sema::qualified_contextes> handle_import(
cmsl::string_view path) override;
std::optional<decl_sema::declarative_import_handler::result>
handle_declarative_import(cmsl::string_view path) override;
const sema::sema_node& get_sema_tree(
cmsl::string_view import_path) const override;
private:
void raise_no_main_function_error(const cmsl::string_view& path);
void raise_unsuccessful_compilation_error(const cmsl::string_view& path);
sema::qualified_contextes create_qualified_contextes() const;
std::unique_ptr<sema::builtin_sema_context> create_builtin_context();
std::unique_ptr<decl_sema::builtin_decl_namespace_context>
create_decl_namespace_context();
std::string build_full_import_path(cmsl::string_view import_path) const;
source_compiler create_compiler(sema::qualified_contextes& ctxs);
declarative_source_compiler create_declarative_compiler(
sema::qualified_contextes& ctxs);
std::optional<source_view> load_source(std::string path);
cmsl::string_view store_source(std::string path);
cmsl::string_view store_path(std::string path);
bool file_exists(const std::string& path) const;
const compiled_source* compile_file(std::string path);
const compiled_declarative_source* compile_declarative_file(
std::string path);
const compiled_source* compile_source(std::string source, std::string path);
std::unique_ptr<inst::instance> execute(const compiled_source& compiled);
std::unique_ptr<inst::instance> execute(const sema::sema_function& function);
void initialize_execution_if_need();
private:
class directory_guard
{
public:
explicit directory_guard(facade::cmake_facade& cmake_facade,
const std::string& dir);
~directory_guard();
private:
facade::cmake_facade& m_cmake_facade;
};
std::string m_root_path;
facade::cmake_facade& m_cmake_facade;
errors::errors_observer& m_errors_observer;
strings_container_impl m_strings_container;
// Contextes are going to be initialized with builtin stuff at builtin
// context creation.
sema::qualified_contextes m_builtin_qualified_contexts;
builtin_identifiers_observer m_builtin_identifiers_observer;
sema::factories_provider m_factories;
std::unique_ptr<sema::builtin_token_provider> m_builtin_tokens;
std::unique_ptr<sema::builtin_sema_context> m_builtin_context;
std::unique_ptr<decl_sema::builtin_decl_namespace_context>
m_decl_namespace_context;
cross_translation_unit_static_variables m_static_variables;
std::vector<std::string> m_sources;
std::vector<std::string> m_paths;
std::unordered_map<cmsl::string_view, std::unique_ptr<compiled_source>>
m_compiled_sources;
std::unordered_map<cmsl::string_view,
std::unique_ptr<compiled_declarative_source>>
m_compiled_declarative_sources;
std::unordered_map<cmsl::string_view,
std::reference_wrapper<const sema::sema_node>>
m_sema_trees;
std::unordered_map<cmsl::string_view, sema::qualified_contextes>
m_exported_qualified_contextes;
std::unique_ptr<execution> m_execution;
std::vector<std::string> m_directories;
};
}
}
| 32.230263 | 79 | 0.782609 | stryku |
f3de13873c49699a7ae1ca5db0f98bc74488c409 | 355 | cpp | C++ | Program's_Contributed_By_Contributors/Dynamic Programming/ClimbingStairs.cpp | shreyukashid/Hacktoberfest2k21 | 2aecacacc4719bbde253b35361a4bd5956d48ab2 | [
"MIT"
] | 1 | 2021-10-02T05:59:49.000Z | 2021-10-02T05:59:49.000Z | Program's_Contributed_By_Contributors/Dynamic Programming/ClimbingStairs.cpp | shreyukashid/Hacktoberfest2k21 | 2aecacacc4719bbde253b35361a4bd5956d48ab2 | [
"MIT"
] | null | null | null | Program's_Contributed_By_Contributors/Dynamic Programming/ClimbingStairs.cpp | shreyukashid/Hacktoberfest2k21 | 2aecacacc4719bbde253b35361a4bd5956d48ab2 | [
"MIT"
] | 1 | 2021-10-06T12:27:26.000Z | 2021-10-06T12:27:26.000Z | #include<iostream>
using namespace std;
int climbStairs(int n)
{
int dp[n + 2];
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++)
{
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
int main(int n)
{
int n;
//Enter Number of Stairs
cin>>n;
int ans=climbStairs(n);
cout<<ans<<endl;
} | 14.791667 | 38 | 0.470423 | shreyukashid |
f3e05c2f925333d6d2e5b6775536f789737f798d | 512 | hpp | C++ | spec/headers/namespaces.hpp | floomby/rbgccxml | f7085e2ae1847452c137c7b9ce6686111a7e6960 | [
"MIT"
] | 6 | 2015-11-05T05:13:49.000Z | 2020-01-07T14:06:19.000Z | spec/headers/namespaces.hpp | floomby/rbgccxml | f7085e2ae1847452c137c7b9ce6686111a7e6960 | [
"MIT"
] | 4 | 2017-03-29T21:56:58.000Z | 2020-10-29T13:33:38.000Z | spec/headers/namespaces.hpp | floomby/rbgccxml | f7085e2ae1847452c137c7b9ce6686111a7e6960 | [
"MIT"
] | 3 | 2017-10-11T07:34:57.000Z | 2022-03-03T20:50:06.000Z | /**
* File for testing the ability to find namespaces
*/
namespace upper {
void method1() { }
namespace inner1 {
void method2() { }
}
namespace inner2 {
void method3() { }
namespace nested {
void method4() { }
}
class NamespacedClass {
};
}
}
// Namespace Aliases
namespace superInner = upper::inner2;
void takes_class(superInner::NamespacedClass obj) {
}
/* Include the ability to look into the default namespace */
int not_in_namespace() {
return -1;
}
| 14.628571 | 60 | 0.632813 | floomby |
f3e15a8a436acd9de0d08c5f292d6a69b82a1158 | 2,452 | hpp | C++ | src/ReconnectTimer.hpp | cs-software-gmbh/mq-cph | 74210fcc7dd8f0c89a99d769bfa0ef1f12336d02 | [
"Apache-2.0"
] | 10 | 2017-09-05T08:47:11.000Z | 2021-08-02T15:41:54.000Z | src/ReconnectTimer.hpp | cs-software-gmbh/mq-cph | 74210fcc7dd8f0c89a99d769bfa0ef1f12336d02 | [
"Apache-2.0"
] | 5 | 2018-08-22T13:14:28.000Z | 2022-02-22T08:30:53.000Z | src/ReconnectTimer.hpp | cs-software-gmbh/mq-cph | 74210fcc7dd8f0c89a99d769bfa0ef1f12336d02 | [
"Apache-2.0"
] | 3 | 2017-02-13T16:23:48.000Z | 2021-11-09T10:47:08.000Z | /*<copyright notice="lm-source" pids="" years="2014,2020">*/
/*******************************************************************************
* Copyright (c) 2014,2020 IBM Corp.
*
* 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.
*/
/*
* Contributors:
* Rowan Lonsdale - Initial implementation
* Various members of the WebSphere MQ Performance Team at IBM Hursley UK
*******************************************************************************/
/*</copyright>*/
/*******************************************************************************/
/* */
/* Performance Harness for IBM MQ C-MQI interface */
/* */
/*******************************************************************************/
#ifndef RECONNECTTIMER_HPP_
#define RECONNECTTIMER_HPP_
#include "Lock.hpp"
#include "MQIWorkerThread.hpp"
#include <stdint.h>
#include <cmqc.h>
namespace cph {
/*
* Class: PutGet
* -------------
*
* Extends: MQIWorkerThread
*
* Puts a message to a queue, then gets it back again.
*/
MQWTCLASSDEF(ReconnectTimer,
static bool useCorrelId;
static bool useSelector, useCustomSelector, usingPrimaryQM;
static char customSelector[MQ_SELECTOR_LENGTH];
static long maxReconnectTime_ms;
static long minReconnectTime_ms;
static int numThreadsReconnected;
static int totalThreads;
static char secondaryHostName[80]; //Name of machine hosting queue manager
static unsigned int secondaryPortNumber; //Port to connect to machine on
static Lock rtGate;
/*The queue to put/get to/from.*/
MQIQueue * pQueue;
/*The correlId to associate with messages.*/
MQBYTE24 correlId;
CPH_TIME reconnectStart;
long reconnectTime_ms;
char messageString[512];
void reconnect();
)
}
#endif /* RECONNECTTIMER_HPP_ */
| 32.693333 | 89 | 0.573002 | cs-software-gmbh |
f3e244359a4ee1455ed9f802b6f3a56e34f1ac98 | 532 | cpp | C++ | cppp/src/15-oop/text-query-again.cpp | ahxxm/cpp-exercise | abbe530770d49843ceaf706fb55b91ef100b1162 | [
"WTFPL"
] | 2 | 2016-12-06T00:49:35.000Z | 2017-01-15T07:00:24.000Z | cppp/src/15-oop/text-query-again.cpp | ahxxm/cpp-exercise | abbe530770d49843ceaf706fb55b91ef100b1162 | [
"WTFPL"
] | 5 | 2016-05-02T13:52:52.000Z | 2016-09-28T07:57:09.000Z | cppp/src/15-oop/text-query-again.cpp | ahxxm/cpp-exercise | abbe530770d49843ceaf706fb55b91ef100b1162 | [
"WTFPL"
] | null | null | null | #include <string>
#include <vector>
#include "gtest/gtest.h"
class QueryResult;
class TextQuery;
class Query_base {
friend class Query;
protected:
using line_no = std::vector<std::string>::size_type;
virtual ~Query_base() = default;
private:
virtual QueryResult eval(const TextQuery &) const = 0;
virtual std::string rep() const = 0;
};
TEST(MoreTextQueryTest, SomeTest) {
EXPECT_EQ(1, 1);
}
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
}
| 18.344828 | 56 | 0.695489 | ahxxm |
f3e5b53d846e86130e5be7ed68d6923fcd7bb93d | 192 | hpp | C++ | callback.hpp | serpapi/serpapi-search-cpp | fc1cafc05d3e2c2b1661789d96f916441d33ecd3 | [
"MIT"
] | null | null | null | callback.hpp | serpapi/serpapi-search-cpp | fc1cafc05d3e2c2b1661789d96f916441d33ecd3 | [
"MIT"
] | null | null | null | callback.hpp | serpapi/serpapi-search-cpp | fc1cafc05d3e2c2b1661789d96f916441d33ecd3 | [
"MIT"
] | null | null | null | #include <cstdint>
#include <iostream>
#include <memory>
#include <string>
using namespace std;
namespace serpapi
{
size_t callback(const char* in, size_t size, size_t num, string* out);
}
| 16 | 71 | 0.734375 | serpapi |
f3e8402b4b8c5a223e1965dabfa934344fbcbc72 | 152 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/ext/gui.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/ext/gui.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/ext/gui.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | #ifndef SVL_EXT_GUI_HPP
#define SVL_EXT_GUI_HPP
#include <svl/ext/phase_diagram.hpp>
#include <svl/ext/phase_diagram3d.hpp>
#endif // SVL_EXT_GUI_HPP
| 19 | 38 | 0.802632 | yklishevich |
f3e8ffec313c08389b7d7496bb7b9922e406f5ae | 1,897 | cpp | C++ | eventHandle.cpp | EnoshWang/ADFServer | bcffbbad45d4b5ca149e81eee2d4c0bd3c8a4a09 | [
"MIT"
] | null | null | null | eventHandle.cpp | EnoshWang/ADFServer | bcffbbad45d4b5ca149e81eee2d4c0bd3c8a4a09 | [
"MIT"
] | null | null | null | eventHandle.cpp | EnoshWang/ADFServer | bcffbbad45d4b5ca149e81eee2d4c0bd3c8a4a09 | [
"MIT"
] | null | null | null | /*
* @Author: enosh.wang
* @Date: 2021-06-27 16:08:39
* @Last Modified by: enosh.wang
* @Last Modified time: 2021-06-27 16:12:01
*/
#ifdef __linux__
#include "eventHandle.hpp"
#include "reactor.hpp"
#define MAX_BUF_LEN 1024
void EventHandle::handAccept(int fd, int events, void *arg) noexcept
{
auto reactor = (Reactor *)arg;
if (nullptr == reactor)
return;
struct sockaddr_in sock_client;
socklen_t len = sizeof(sock_client);
int clientfd = accept(fd, (struct sockaddr *)&sock_client, &len);
if (-1 == clientfd)
return;
do
{
int flag = fcntl(clientfd, F_SETFL, O_NONBLOCK);
if (flag < 0)
{
std::cout << "set non block failed." << std::endl;
break;
}
EventHandle *evHanlde = new EventHandle(clientfd);
if (nullptr == evHanlde)
return;
reactor->registerEventHandle(evHanlde, Event_Recv);
} while (0);
}
void EventHandle::handSend(int fd, int events, void *arg) noexcept
{
auto reactor = (Reactor *)arg;
if (nullptr == reactor)
return;
}
void EventHandle::handRecv(int fd, int events, void *arg) noexcept
{
auto reactor = (Reactor *)arg;
if (nullptr == reactor)
return;
char buff[MAX_BUF_LEN];
memset(buff, 0, MAX_BUF_LEN);
int len = recv(fd, buff, MAX_BUF_LEN, 0);
if (len > 0)
{
std::cout << "Recv buff: " << buff << std::endl;
auto retWrite = write(fd, buff, len);
std::cout << "Write " << retWrite << " bytes to client." << std::endl;
}
else if (len == 0) // client close
{
auto handle = reactor->getEventHandle(fd);
reactor->removeEventHandle(handle);
close(fd);
}
else
{
close(fd);
}
return;
}
#endif | 22.05814 | 79 | 0.549815 | EnoshWang |
f3ef260da0aecfc9b12b30e98f9e2687560e6461 | 857 | cpp | C++ | Problemas Resolvidos/Code Forces/cforces1236C.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | 2 | 2019-09-09T00:34:40.000Z | 2019-09-09T17:35:19.000Z | lucas/codeforces/1236/cforces1236C.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | lucas/codeforces/1236/cforces1236C.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | /*
* author: lucas_medeiros - github.com/medeiroslucas
* team: Lo and Behold ++
* created: 17-10-2019 11:58:55
* contest: 1236
* problem: C
* solved: True
*/
#include <bits/stdc++.h>
#define DEBUG false
#define coutd if(DEBUG) cout
#define debugf if(DEBUG) printf
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
#define sz size()
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
const double PI = acos(-1);
const double EPS = 1e-9;
int main(){
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vi gps[n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
int y;
if(i % 2 == 0){
y = i*n+j+1;
}else{
y = (i+1)*n-j;
}
gps[j].pb(y);
}
}
for(auto p:gps){
for(auto n:p){
cout << n << " ";
}
cout << endl;
}
return 0;
}
| 14.525424 | 53 | 0.586931 | medeiroslucas |
f3efb435e25a1d46b7dd48d33d6b8a6a965e5f48 | 24,366 | cpp | C++ | src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp | Arkania/ArkCORE | 2484554a7b54be0b652f9dc3c5a8beba79df9fbf | [
"OpenSSL"
] | 42 | 2015-01-05T10:00:07.000Z | 2022-02-18T14:51:33.000Z | src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp | superllout/WOW | 3d0eeb940cccf8ab7854259172c6d75a85ee4f7d | [
"OpenSSL"
] | null | null | null | src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp | superllout/WOW | 3d0eeb940cccf8ab7854259172c6d75a85ee4f7d | [
"OpenSSL"
] | 31 | 2015-01-09T02:04:29.000Z | 2021-09-01T13:20:20.000Z | /*
* Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.com/>
*
* Copyright (C) 2010 - 2013 ProjectSkyfire <http://www.projectskyfire.org/>
*
* Copyright (C) 2011 - 2013 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
*/
/* ScriptData
SDName: Boss_High_King_Maulgar
SD%Complete: 90
SDComment: Correct timers, after whirlwind melee attack bug, prayer of healing
SDCategory: Gruul's Lair
EndScriptData */
#include "ScriptPCH.h"
#include "gruuls_lair.h"
#define SAY_AGGRO -1565000
#define SAY_ENRAGE -1565001
#define SAY_OGRE_DEATH1 -1565002
#define SAY_OGRE_DEATH2 -1565003
#define SAY_OGRE_DEATH3 -1565004
#define SAY_OGRE_DEATH4 -1565005
#define SAY_SLAY1 -1565006
#define SAY_SLAY2 -1565007
#define SAY_SLAY3 -1565008
#define SAY_DEATH -1565009
// High King Maulgar
#define SPELL_ARCING_SMASH 39144
#define SPELL_MIGHTY_BLOW 33230
#define SPELL_WHIRLWIND 33238
#define SPELL_BERSERKER_C 26561
#define SPELL_ROAR 16508
#define SPELL_FLURRY 33232
#define SPELL_DUAL_WIELD 29651 //used in phase
// Olm the Summoner
#define SPELL_DARK_DECAY 33129
#define SPELL_DEATH_COIL 33130
#define SPELL_SUMMON_WFH 33131
//Kiggler the Craed
#define SPELL_GREATER_POLYMORPH 33173
#define SPELL_LIGHTNING_BOLT 36152
#define SPELL_ARCANE_SHOCK 33175
#define SPELL_ARCANE_EXPLOSION 33237
//Blindeye the Seer
#define SPELL_GREATER_PW_SHIELD 33147
#define SPELL_HEAL 33144
#define SPELL_PRAYER_OH 33152
//Krosh Firehand
#define SPELL_GREATER_FIREBALL 33051
#define SPELL_SPELLSHIELD 33054
#define SPELL_BLAST_WAVE 33061
bool CheckAllBossDied(InstanceScript* pInstance, Creature* me)
{
if (!pInstance || !me)
return false;
uint64 MaulgarGUID = 0;
uint64 KigglerGUID = 0;
uint64 BlindeyeGUID = 0;
uint64 OlmGUID = 0;
uint64 KroshGUID = 0;
Creature* Maulgar = NULL;
Creature* Kiggler = NULL;
Creature* Blindeye = NULL;
Creature* Olm = NULL;
Creature* Krosh = NULL;
MaulgarGUID = pInstance->GetData64(DATA_MAULGAR);
KigglerGUID = pInstance->GetData64(DATA_KIGGLERTHECRAZED);
BlindeyeGUID = pInstance->GetData64(DATA_BLINDEYETHESEER);
OlmGUID = pInstance->GetData64(DATA_OLMTHESUMMONER);
KroshGUID = pInstance->GetData64(DATA_KROSHFIREHAND);
Maulgar = (Unit::GetCreature((*me), MaulgarGUID));
Kiggler = (Unit::GetCreature((*me), KigglerGUID));
Blindeye = (Unit::GetCreature((*me), BlindeyeGUID));
Olm = (Unit::GetCreature((*me), OlmGUID));
Krosh = (Unit::GetCreature((*me), KroshGUID));
if (!Maulgar || !Kiggler || !Blindeye || !Olm || !Krosh)
return false;
if (!Maulgar->isAlive() && !Kiggler->isAlive() && !Blindeye->isAlive() && !Olm->isAlive() && !Krosh->isAlive())
return true;
return false;
}
//High King Maulgar AI
class boss_high_king_maulgar : public CreatureScript
{
public:
boss_high_king_maulgar() : CreatureScript("boss_high_king_maulgar") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_high_king_maulgarAI (pCreature);
}
struct boss_high_king_maulgarAI : public ScriptedAI
{
boss_high_king_maulgarAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
for (uint8 i = 0; i < 4; ++i)
Council[i] = 0;
}
InstanceScript* pInstance;
uint32 ArcingSmash_Timer;
uint32 MightyBlow_Timer;
uint32 Whirlwind_Timer;
uint32 Charging_Timer;
uint32 Roar_Timer;
bool Phase2;
uint64 Council[4];
void Reset()
{
ArcingSmash_Timer = 10000;
MightyBlow_Timer = 40000;
Whirlwind_Timer = 30000;
Charging_Timer = 0;
Roar_Timer = 0;
DoCast(me, SPELL_DUAL_WIELD, false);
Phase2 = false;
Creature *pCreature = NULL;
for (uint8 i = 0; i < 4; ++i)
{
if (Council[i])
{
pCreature = (Unit::GetCreature((*me), Council[i]));
if (pCreature && !pCreature->isAlive())
{
pCreature->Respawn();
pCreature->AI()->EnterEvadeMode();
}
}
}
//reset encounter
if (pInstance)
pInstance->SetData(DATA_MAULGAREVENT, NOT_STARTED);
}
void KilledUnit()
{
DoScriptText(RAND(SAY_SLAY1, SAY_SLAY2, SAY_SLAY3), me);
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(SAY_DEATH, me);
if (CheckAllBossDied(pInstance, me))
pInstance->SetData(DATA_MAULGAREVENT, DONE);
}
void AddDeath()
{
DoScriptText(RAND(SAY_OGRE_DEATH1, SAY_OGRE_DEATH2, SAY_OGRE_DEATH3, SAY_OGRE_DEATH4), me);
}
void EnterCombat(Unit *who)
{
StartEvent(who);
}
void GetCouncil()
{
if (pInstance)
{
//get council member's guid to respawn them if needed
Council[0] = pInstance->GetData64(DATA_KIGGLERTHECRAZED);
Council[1] = pInstance->GetData64(DATA_BLINDEYETHESEER);
Council[2] = pInstance->GetData64(DATA_OLMTHESUMMONER);
Council[3] = pInstance->GetData64(DATA_KROSHFIREHAND);
}
}
void StartEvent(Unit *who)
{
if (!pInstance)
return;
GetCouncil();
DoScriptText(SAY_AGGRO, me);
pInstance->SetData64(DATA_MAULGAREVENT_TANK, who->GetGUID());
pInstance->SetData(DATA_MAULGAREVENT, IN_PROGRESS);
DoZoneInCombat();
}
void UpdateAI(const uint32 diff)
{
//Only if not incombat check if the event is started
if (!me->isInCombat() && pInstance && pInstance->GetData(DATA_MAULGAREVENT))
{
Unit *pTarget = Unit::GetUnit((*me), pInstance->GetData64(DATA_MAULGAREVENT_TANK));
if (pTarget)
{
AttackStart(pTarget);
GetCouncil();
}
}
//Return since we have no target
if (!UpdateVictim())
return;
//someone evaded!
if (pInstance && !pInstance->GetData(DATA_MAULGAREVENT))
{
EnterEvadeMode();
return;
}
//ArcingSmash_Timer
if (ArcingSmash_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_ARCING_SMASH);
ArcingSmash_Timer = 10000;
} else ArcingSmash_Timer -= diff;
//Whirlwind_Timer
if (Whirlwind_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_WHIRLWIND);
Whirlwind_Timer = 55000;
} else Whirlwind_Timer -= diff;
//MightyBlow_Timer
if (MightyBlow_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_MIGHTY_BLOW);
MightyBlow_Timer = 30000+rand()%10000;
} else MightyBlow_Timer -= diff;
//Entering Phase 2
if (!Phase2 && HealthBelowPct(50))
{
Phase2 = true;
DoScriptText(SAY_ENRAGE, me);
DoCast(me, SPELL_DUAL_WIELD, true);
me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, 0);
me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID+1, 0);
}
if (Phase2)
{
//Charging_Timer
if (Charging_Timer <= diff)
{
Unit *pTarget = NULL;
pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0);
if (pTarget)
{
AttackStart(pTarget);
DoCast(pTarget, SPELL_BERSERKER_C);
}
Charging_Timer = 20000;
} else Charging_Timer -= diff;
//Intimidating Roar
if (Roar_Timer <= diff)
{
DoCast(me, SPELL_ROAR);
Roar_Timer = 40000+(rand()%10000);
} else Roar_Timer -= diff;
}
DoMeleeAttackIfReady();
}
};
};
//Olm The Summoner AI
class boss_olm_the_summoner : public CreatureScript
{
public:
boss_olm_the_summoner() : CreatureScript("boss_olm_the_summoner") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_olm_the_summonerAI (pCreature);
}
struct boss_olm_the_summonerAI : public ScriptedAI
{
boss_olm_the_summonerAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
}
uint32 DarkDecay_Timer;
uint32 Summon_Timer;
uint32 DeathCoil_Timer;
InstanceScript* pInstance;
void Reset()
{
DarkDecay_Timer = 10000;
Summon_Timer = 15000;
DeathCoil_Timer = 20000;
//reset encounter
if (pInstance)
pInstance->SetData(DATA_MAULGAREVENT, NOT_STARTED);
}
void AttackStart(Unit* pWho)
{
if (!pWho)
return;
if (me->Attack(pWho, true))
{
me->AddThreat(pWho, 0.0f);
me->SetInCombatWith(pWho);
pWho->SetInCombatWith(me);
me->GetMotionMaster()->MoveChase(pWho, 30.0f);
}
}
void EnterCombat(Unit *who)
{
if (pInstance)
{
pInstance->SetData64(DATA_MAULGAREVENT_TANK, who->GetGUID());
pInstance->SetData(DATA_MAULGAREVENT, IN_PROGRESS);
}
}
void JustDied(Unit* /*Killer*/)
{
if (pInstance)
{
Creature *Maulgar = NULL;
Maulgar = (Unit::GetCreature((*me), pInstance->GetData64(DATA_MAULGAR)));
if (Maulgar)
CAST_AI(boss_high_king_maulgar::boss_high_king_maulgarAI, Maulgar->AI())->AddDeath();
if (CheckAllBossDied(pInstance, me))
pInstance->SetData(DATA_MAULGAREVENT, DONE);
}
}
void UpdateAI(const uint32 diff)
{
//Only if not incombat check if the event is started
if (!me->isInCombat() && pInstance && pInstance->GetData(DATA_MAULGAREVENT))
{
Unit *pTarget = Unit::GetUnit((*me), pInstance->GetData64(DATA_MAULGAREVENT_TANK));
if (pTarget)
{
AttackStart(pTarget);
}
}
//Return since we have no target
if (!UpdateVictim())
return;
//someone evaded!
if (pInstance && !pInstance->GetData(DATA_MAULGAREVENT))
{
EnterEvadeMode();
return;
}
//DarkDecay_Timer
if (DarkDecay_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_DARK_DECAY);
DarkDecay_Timer = 20000;
} else DarkDecay_Timer -= diff;
//Summon_Timer
if (Summon_Timer <= diff)
{
DoCast(me, SPELL_SUMMON_WFH);
Summon_Timer = 30000;
} else Summon_Timer -= diff;
//DeathCoil Timer /need correct timer
if (DeathCoil_Timer <= diff)
{
Unit *pTarget = NULL;
pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0);
if (pTarget)
DoCast(pTarget, SPELL_DEATH_COIL);
DeathCoil_Timer = 20000;
} else DeathCoil_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
//Kiggler The Crazed AI
class boss_kiggler_the_crazed : public CreatureScript
{
public:
boss_kiggler_the_crazed() : CreatureScript("boss_kiggler_the_crazed") { }
CreatureAI *GetAI(Creature* pCreature) const
{
return new boss_kiggler_the_crazedAI (pCreature);
}
struct boss_kiggler_the_crazedAI : public ScriptedAI
{
boss_kiggler_the_crazedAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
}
uint32 GreaterPolymorph_Timer;
uint32 LightningBolt_Timer;
uint32 ArcaneShock_Timer;
uint32 ArcaneExplosion_Timer;
InstanceScript* pInstance;
void Reset()
{
GreaterPolymorph_Timer = 5000;
LightningBolt_Timer = 10000;
ArcaneShock_Timer = 20000;
ArcaneExplosion_Timer = 30000;
//reset encounter
if (pInstance)
pInstance->SetData(DATA_MAULGAREVENT, NOT_STARTED);
}
void EnterCombat(Unit* who)
{
if (pInstance)
{
pInstance->SetData64(DATA_MAULGAREVENT_TANK, who->GetGUID());
pInstance->SetData(DATA_MAULGAREVENT, IN_PROGRESS);
}
}
void JustDied(Unit* /*Killer*/)
{
if (pInstance)
{
Creature *Maulgar = NULL;
Maulgar = (Unit::GetCreature((*me), pInstance->GetData64(DATA_MAULGAR)));
if (Maulgar)
CAST_AI(boss_high_king_maulgar::boss_high_king_maulgarAI, Maulgar->AI())->AddDeath();
if (CheckAllBossDied(pInstance, me))
pInstance->SetData(DATA_MAULGAREVENT, DONE);
}
}
void UpdateAI(const uint32 diff)
{
//Only if not incombat check if the event is started
if (!me->isInCombat() && pInstance && pInstance->GetData(DATA_MAULGAREVENT))
{
Unit *pTarget = Unit::GetUnit((*me), pInstance->GetData64(DATA_MAULGAREVENT_TANK));
if (pTarget)
{
AttackStart(pTarget);
}
}
//Return since we have no target
if (!UpdateVictim())
return;
//someone evaded!
if (pInstance && !pInstance->GetData(DATA_MAULGAREVENT))
{
EnterEvadeMode();
return;
}
//GreaterPolymorph_Timer
if (GreaterPolymorph_Timer <= diff)
{
Unit *pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0);
if (pTarget)
DoCast(pTarget, SPELL_GREATER_POLYMORPH);
GreaterPolymorph_Timer = 15000 + rand()%5000;
} else GreaterPolymorph_Timer -= diff;
//LightningBolt_Timer
if (LightningBolt_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_LIGHTNING_BOLT);
LightningBolt_Timer = 15000;
} else LightningBolt_Timer -= diff;
//ArcaneShock_Timer
if (ArcaneShock_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_ARCANE_SHOCK);
ArcaneShock_Timer = 20000;
} else ArcaneShock_Timer -= diff;
//ArcaneExplosion_Timer
if (ArcaneExplosion_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_ARCANE_EXPLOSION);
ArcaneExplosion_Timer = 30000;
} else ArcaneExplosion_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
//Blindeye The Seer AI
class boss_blindeye_the_seer : public CreatureScript
{
public:
boss_blindeye_the_seer() : CreatureScript("boss_blindeye_the_seer") { }
CreatureAI *GetAI(Creature* pCreature) const
{
return new boss_blindeye_the_seerAI (pCreature);
}
struct boss_blindeye_the_seerAI : public ScriptedAI
{
boss_blindeye_the_seerAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
}
uint32 GreaterPowerWordShield_Timer;
uint32 Heal_Timer;
uint32 PrayerofHealing_Timer;
InstanceScript* pInstance;
void Reset()
{
GreaterPowerWordShield_Timer = 5000;
Heal_Timer = 25000 + rand()%15000;
PrayerofHealing_Timer = 45000 + rand()%10000;
//reset encounter
if (pInstance)
pInstance->SetData(DATA_MAULGAREVENT, NOT_STARTED);
}
void EnterCombat(Unit * who)
{
if (pInstance)
{
pInstance->SetData64(DATA_MAULGAREVENT_TANK, who->GetGUID());
pInstance->SetData(DATA_MAULGAREVENT, IN_PROGRESS);
}
}
void JustDied(Unit* /*Killer*/)
{
if (pInstance)
{
Creature *Maulgar = NULL;
Maulgar = (Unit::GetCreature((*me), pInstance->GetData64(DATA_MAULGAR)));
if (Maulgar)
CAST_AI(boss_high_king_maulgar::boss_high_king_maulgarAI, Maulgar->AI())->AddDeath();
if (CheckAllBossDied(pInstance, me))
pInstance->SetData(DATA_MAULGAREVENT, DONE);
}
}
void UpdateAI(const uint32 diff)
{
//Only if not incombat check if the event is started
if (!me->isInCombat() && pInstance && pInstance->GetData(DATA_MAULGAREVENT))
{
Unit *pTarget = Unit::GetUnit((*me), pInstance->GetData64(DATA_MAULGAREVENT_TANK));
if (pTarget)
{
AttackStart(pTarget);
}
}
//Return since we have no target
if (!UpdateVictim())
return;
//someone evaded!
if (pInstance && !pInstance->GetData(DATA_MAULGAREVENT))
{
EnterEvadeMode();
return;
}
//GreaterPowerWordShield_Timer
if (GreaterPowerWordShield_Timer <= diff)
{
DoCast(me, SPELL_GREATER_PW_SHIELD);
GreaterPowerWordShield_Timer = 40000;
} else GreaterPowerWordShield_Timer -= diff;
//Heal_Timer
if (Heal_Timer <= diff)
{
DoCast(me, SPELL_HEAL);
Heal_Timer = 15000 + rand()%25000;
} else Heal_Timer -= diff;
//PrayerofHealing_Timer
if (PrayerofHealing_Timer <= diff)
{
DoCast(me, SPELL_PRAYER_OH);
PrayerofHealing_Timer = 35000 + rand()%15000;
} else PrayerofHealing_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
//Krosh Firehand AI
class boss_krosh_firehand : public CreatureScript
{
public:
boss_krosh_firehand() : CreatureScript("boss_krosh_firehand") { }
CreatureAI *GetAI(Creature* pCreature) const
{
return new boss_krosh_firehandAI (pCreature);
}
struct boss_krosh_firehandAI : public ScriptedAI
{
boss_krosh_firehandAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
}
uint32 GreaterFireball_Timer;
uint32 SpellShield_Timer;
uint32 BlastWave_Timer;
InstanceScript* pInstance;
void Reset()
{
GreaterFireball_Timer = 1000;
SpellShield_Timer = 5000;
BlastWave_Timer = 20000;
//reset encounter
if (pInstance)
pInstance->SetData(DATA_MAULGAREVENT, NOT_STARTED);
}
void EnterCombat(Unit * who)
{
if (pInstance)
{
pInstance->SetData64(DATA_MAULGAREVENT_TANK, who->GetGUID());
pInstance->SetData(DATA_MAULGAREVENT, IN_PROGRESS);
}
}
void JustDied(Unit* /*Killer*/)
{
if (pInstance)
{
Creature *Maulgar = NULL;
Maulgar = (Unit::GetCreature((*me), pInstance->GetData64(DATA_MAULGAR)));
if (Maulgar)
CAST_AI(boss_high_king_maulgar::boss_high_king_maulgarAI, Maulgar->AI())->AddDeath();
if (CheckAllBossDied(pInstance, me))
pInstance->SetData(DATA_MAULGAREVENT, DONE);
}
}
void UpdateAI(const uint32 diff)
{
//Only if not incombat check if the event is started
if (!me->isInCombat() && pInstance && pInstance->GetData(DATA_MAULGAREVENT))
{
Unit *pTarget = Unit::GetUnit((*me), pInstance->GetData64(DATA_MAULGAREVENT_TANK));
if (pTarget)
{
AttackStart(pTarget);
}
}
//Return since we have no target
if (!UpdateVictim())
return;
//someone evaded!
if (pInstance && !pInstance->GetData(DATA_MAULGAREVENT))
{
EnterEvadeMode();
return;
}
//GreaterFireball_Timer
if (GreaterFireball_Timer < diff || me->IsWithinDist(me->getVictim(), 30))
{
DoCast(me->getVictim(), SPELL_GREATER_FIREBALL);
GreaterFireball_Timer = 2000;
} else GreaterFireball_Timer -= diff;
//SpellShield_Timer
if (SpellShield_Timer <= diff)
{
me->InterruptNonMeleeSpells(false);
DoCast(me->getVictim(), SPELL_SPELLSHIELD);
SpellShield_Timer = 30000;
} else SpellShield_Timer -= diff;
//BlastWave_Timer
if (BlastWave_Timer <= diff)
{
Unit *pTarget = NULL;
std::list<HostileReference *> t_list = me->getThreatManager().getThreatList();
std::vector<Unit *> target_list;
for (std::list<HostileReference *>::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr)
{
pTarget = Unit::GetUnit(*me, (*itr)->getUnitGuid());
//15 yard radius minimum
if (pTarget && pTarget->IsWithinDist(me, 15, false))
target_list.push_back(pTarget);
pTarget = NULL;
}
if (target_list.size())
pTarget = *(target_list.begin()+rand()%target_list.size());
me->InterruptNonMeleeSpells(false);
DoCast(pTarget, SPELL_BLAST_WAVE);
BlastWave_Timer = 60000;
} else BlastWave_Timer -= diff;
}
};
};
void AddSC_boss_high_king_maulgar()
{
new boss_high_king_maulgar();
new boss_kiggler_the_crazed();
new boss_blindeye_the_seer();
new boss_olm_the_summoner();
new boss_krosh_firehand();
} | 30.419476 | 115 | 0.537388 | Arkania |
f3f0e64285ed75254eb1fc8077b454b871140bc2 | 4,573 | cxx | C++ | Devices/igtlioTransformDevice.cxx | adamrankin/OpenIGTLinkIO | 9d0b1010be7b92947dbd461dc5298c320dfc00e4 | [
"Apache-2.0"
] | 7 | 2016-02-02T19:03:33.000Z | 2021-07-31T19:12:03.000Z | Devices/igtlioTransformDevice.cxx | adamrankin/OpenIGTLinkIO | 9d0b1010be7b92947dbd461dc5298c320dfc00e4 | [
"Apache-2.0"
] | 61 | 2016-02-01T21:47:49.000Z | 2022-03-15T16:12:31.000Z | Devices/igtlioTransformDevice.cxx | adamrankin/OpenIGTLinkIO | 9d0b1010be7b92947dbd461dc5298c320dfc00e4 | [
"Apache-2.0"
] | 20 | 2016-02-01T22:24:52.000Z | 2021-07-31T19:12:04.000Z | /*==========================================================================
Portions (c) Copyright 2008-2009 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $HeadURL: http://svn.slicer.org/Slicer3/trunk/Modules/OpenIGTLinkIF/vtkIGTLIOTransformDevice.cxx $
Date: $Date: 2010-12-07 21:39:19 -0500 (Tue, 07 Dec 2010) $
Version: $Revision: 15621 $
==========================================================================*/
#include "igtlioTransformDevice.h"
#include <vtkObjectFactory.h>
#include "vtkMatrix4x4.h"
//---------------------------------------------------------------------------
igtlioDevicePointer igtlioTransformDeviceCreator::Create(std::string device_name)
{
igtlioTransformDevicePointer retval = igtlioTransformDevicePointer::New();
retval->SetDeviceName(device_name);
return retval;
}
//---------------------------------------------------------------------------
std::string igtlioTransformDeviceCreator::GetDeviceType() const
{
return igtlioTransformConverter::GetIGTLTypeName();
}
//---------------------------------------------------------------------------
vtkStandardNewMacro(igtlioTransformDeviceCreator);
//---------------------------------------------------------------------------
vtkStandardNewMacro(igtlioTransformDevice);
//---------------------------------------------------------------------------
igtlioTransformDevice::igtlioTransformDevice()
{
}
//---------------------------------------------------------------------------
igtlioTransformDevice::~igtlioTransformDevice()
{
}
//---------------------------------------------------------------------------
unsigned int igtlioTransformDevice::GetDeviceContentModifiedEvent() const
{
return TransformModifiedEvent;
}
//---------------------------------------------------------------------------
std::string igtlioTransformDevice::GetDeviceType() const
{
return igtlioTransformConverter::GetIGTLTypeName();
}
void igtlioTransformDevice::SetContent(igtlioTransformConverter::ContentData content)
{
Content = content;
this->Modified();
this->InvokeEvent(TransformModifiedEvent, this);
}
igtlioTransformConverter::ContentData igtlioTransformDevice::GetContent()
{
return Content;
}
//---------------------------------------------------------------------------
int igtlioTransformDevice::ReceiveIGTLMessage(igtl::MessageBase::Pointer buffer, bool checkCRC)
{
int success = igtlioTransformConverter::fromIGTL(buffer, &HeaderData, &Content, checkCRC, this->metaInfo);
if (success)
{
this->Modified();
this->InvokeEvent(TransformModifiedEvent, this);
}
return success;
}
//---------------------------------------------------------------------------
igtl::MessageBase::Pointer igtlioTransformDevice::GetIGTLMessage()
{
// cannot send a non-existent image
if (!Content.transform)
{
return 0;
}
if (!igtlioTransformConverter::toIGTL(HeaderData, Content, &this->OutTransformMessage, this->metaInfo))
{
return 0;
}
return dynamic_pointer_cast<igtl::MessageBase>(this->OutTransformMessage);
}
//---------------------------------------------------------------------------
igtl::MessageBase::Pointer igtlioTransformDevice::GetIGTLMessage(MESSAGE_PREFIX prefix)
{
/*
if (prefix==MESSAGE_PREFIX_GET)
{
if (this->GetTransformMessage.IsNull())
{
this->GetTransformMessage = igtl::GetTransformMessage::New();
}
this->GetTransformMessage->SetDeviceName(HeaderData.deviceName.c_str());
this->GetTransformMessage->Pack();
return dynamic_pointer_cast<igtl::MessageBase>(this->GetTransformMessage);
}
*/
if (prefix==MESSAGE_PREFIX_NOT_DEFINED)
{
return this->GetIGTLMessage();
}
return igtl::MessageBase::Pointer();
}
//---------------------------------------------------------------------------
std::set<igtlioDevice::MESSAGE_PREFIX> igtlioTransformDevice::GetSupportedMessagePrefixes() const
{
std::set<MESSAGE_PREFIX> retval;
retval.insert(MESSAGE_PREFIX_NOT_DEFINED);
return retval;
}
//---------------------------------------------------------------------------
void igtlioTransformDevice::PrintSelf(ostream& os, vtkIndent indent)
{
igtlioDevice::PrintSelf(os, indent);
// not sure what to do here.
//os << indent << "CommandID:\t" <<"\n";
//Content.transform->PrintSelf(os, indent.GetNextIndent());
//os << indent << "CommandName:\t" << "\n";
//Content.transform->PrintSelf(os, indent.GetNextIndent());
}
| 30.898649 | 111 | 0.561338 | adamrankin |
f3f36f403063127d626f7a8c031a9e6a989b8174 | 1,519 | cpp | C++ | Character/StrongEnemy.cpp | Ricecrackie/Fantasy-Battle | 058dc323101d405e222e9c8f135500044ce6e180 | [
"Apache-2.0"
] | null | null | null | Character/StrongEnemy.cpp | Ricecrackie/Fantasy-Battle | 058dc323101d405e222e9c8f135500044ce6e180 | [
"Apache-2.0"
] | null | null | null | Character/StrongEnemy.cpp | Ricecrackie/Fantasy-Battle | 058dc323101d405e222e9c8f135500044ce6e180 | [
"Apache-2.0"
] | null | null | null | #include "StrongEnemy.h"
#include "../Skill/Regular_attack.h"
#include "../Skill/Defence.h"
#include "../Skill/Strengthen.h"
#include "../Skill/Sharp_attack.h"
// call constructor to create a StrongEnemy Object using default values
StrongEnemy::StrongEnemy() : Enemy(StrongEnemyHPmax, StrongEnemyHPmax,
StrongEnemyMPmax, StrongEnemyMPmax, StrongEnemyAPmax, StrongEnemyAPmax, StrongEnemyATK, StrongEnemyDEF
, StrongEnemyMoney, StrongEnemyEXP) {
Skill** learned_skill = new Skill*[4];
learned_skill[0] = new Regular_attack();
learned_skill[1] = new Defence(this);
learned_skill[2] = new Strengthen(this);
learned_skill[3] = new Sharp_attack;
this->Character::learned_skill = learned_skill;
}
// call constructor to create a StrongEnemy Object by passing HP and MP values to the constructor
StrongEnemy::StrongEnemy(const int& HP, const int& MP) : Enemy(HP, StrongEnemyHPmax, MP, StrongEnemyMPmax,
StrongEnemyAPmax, StrongEnemyAPmax, StrongEnemyATK, StrongEnemyDEF, StrongEnemyMoney, StrongEnemyEXP) {
Skill** learned_skill = new Skill*[4];
learned_skill[0] = new Regular_attack();
learned_skill[1] = new Defence(this);
learned_skill[2] = new Strengthen(this);
learned_skill[3] = new Sharp_attack;
this->Character::learned_skill = learned_skill;
}
// return the type of the StrongEnemy
Enemy::enemy_type StrongEnemy::get_type() {return Enemy::enemy_type::StrongEnemy;}
// return the name of the StrongEnemy
std::string StrongEnemy::get_name() {return StrongEnemyName;}
| 42.194444 | 106 | 0.756419 | Ricecrackie |
f3f642385fc8483881e9771772314d888b30d767 | 8,476 | cc | C++ | QedisCore/QSet.cc | Myicefrog/Qedis | 692f0584dad8f5d80c55ec19b217f0777156f719 | [
"MIT"
] | 1 | 2019-12-26T07:03:34.000Z | 2019-12-26T07:03:34.000Z | QedisCore/QSet.cc | Myicefrog/Qedis | 692f0584dad8f5d80c55ec19b217f0777156f719 | [
"MIT"
] | null | null | null | QedisCore/QSet.cc | Myicefrog/Qedis | 692f0584dad8f5d80c55ec19b217f0777156f719 | [
"MIT"
] | null | null | null | #include "QSet.h"
#include "QStore.h"
#include "QClient.h"
#include <cassert>
namespace qedis
{
QObject QObject::CreateSet()
{
QObject set(QType_set);
set.Reset(new QSet);
return set;
}
#define GET_SET(setname) \
QObject* value; \
QError err = QSTORE.GetValueByType(setname, value, QType_set); \
if (err != QError_ok) { \
if (err == QError_notExist) \
FormatNull(reply); \
else \
ReplyError(err, reply); \
return err; \
}
#define GET_OR_SET_SET(setname) \
QObject* value; \
QError err = QSTORE.GetValueByType(setname, value, QType_set); \
if (err != QError_ok && err != QError_notExist) { \
ReplyError(err, reply); \
return err; \
} \
if (err == QError_notExist) { \
value = QSTORE.SetValue(setname, QObject::CreateSet()); \
}
static bool RandomMember(const QSet& set, QString& res)
{
QSet::const_local_iterator it = RandomHashMember(set);
if (it != QSet::const_local_iterator())
{
res = *it;
return true;
}
return false;
}
QError spop(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
QString res;
if (RandomMember(*set, res))
{
FormatBulk(res, reply);
set->erase(res);
if (set->empty())
QSTORE.DeleteKey(params[1]);
std::vector<QString> translated;
translated.push_back("srem");
translated.push_back(params[1]);
translated.push_back(res);
QClient::Current()->RewriteCmd(translated);
}
else
{
FormatNull(reply);
return QError_notExist;
}
return QError_ok;
}
QError srandmember(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
QString res;
if (RandomMember(*set, res))
{
FormatBulk(res, reply);
}
else
{
FormatNull(reply);
}
return QError_ok;
}
QError sadd(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_OR_SET_SET(params[1]);
int res = 0;
auto set = value->CastSet();
for (size_t i = 2; i < params.size(); ++ i)
{
if (set->insert(params[i]).second)
++ res;
}
FormatInt(res, reply);
return QError_ok;
}
QError scard(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
long size = static_cast<long>(set->size());
FormatInt(size, reply);
return QError_ok;
}
QError srem(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
int res = 0;
for (size_t i = 2; i < params.size(); ++ i)
{
if (set->erase(params[i]) != 0)
++ res;
}
if (set->empty())
QSTORE.DeleteKey(params[1]);
FormatInt(res, reply);
return QError_ok;
}
QError sismember(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
long res = static_cast<long>(set->count(params[2]));
FormatInt(res, reply);
return QError_ok;
}
QError smembers(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
PreFormatMultiBulk(set->size(), reply);
for (const auto& member : *set)
FormatBulk(member, reply);
return QError_ok;
}
QError smove(const std::vector<QString>& params, UnboundedBuffer* reply)
{
GET_SET(params[1]);
auto set = value->CastSet();
int ret = static_cast<int>(set->erase(params[3]));
if (ret != 0)
{
QObject* dst;
err = QSTORE.GetValueByType(params[2], dst, QType_set);
if (err == QError_notExist)
{
err = QError_ok;
QObject val(QObject::CreateSet());
dst = QSTORE.SetValue(params[2], std::move(val));
}
if (err == QError_ok)
{
auto dset = dst->CastSet();
dset->insert(params[3]);
}
}
FormatInt(ret, reply);
return err;
}
QSet& QSet_diff(const QSet& l, const QSet& r, QSet& result)
{
for (const auto& le : l)
{
if (r.count(le) == 0)
{
result.insert(le);
}
}
return result;
}
QSet& QSet_inter(const QSet& l, const QSet& r, QSet& result)
{
for (const auto& le : l)
{
if (r.count(le) != 0)
{
result.insert(le);
}
}
return result;
}
QSet& QSet_union(const QSet& l, const QSet& r, QSet& result)
{
for (const auto& re : r)
{
result.insert(re);
}
for (const auto& le : l)
{
result.insert(le);
}
return result;
}
enum SetOperation
{
SetOperation_diff,
SetOperation_inter,
SetOperation_union,
};
static void _set_operation(const std::vector<QString>& params,
size_t offset,
QSet& res,
SetOperation oper)
{
QObject* value;
QError err = QSTORE.GetValueByType(params[offset], value, QType_set);
if (err != QError_ok && oper != SetOperation_union)
return;
auto set = value->CastSet();
if (set)
res = *set;
for (size_t i = offset + 1; i < params.size(); ++ i)
{
QObject* val;
QError err = QSTORE.GetValueByType(params[i], val, QType_set);
if (err != QError_ok)
{
if (oper == SetOperation_inter)
{
res.clear();
return;
}
continue;
}
QSet tmp;
auto r = val->CastSet();
if (oper == SetOperation_diff)
QSet_diff(res, *r, tmp);
else if (oper == SetOperation_inter)
QSet_inter(res, *r, tmp);
else if (oper == SetOperation_union)
QSet_union(res, *r, tmp);
res.swap(tmp);
if (oper != SetOperation_union && res.empty())
return;
}
}
QError sdiffstore(const std::vector<QString>& params, UnboundedBuffer* reply)
{
QObject obj(QObject::CreateSet());
auto res = obj.CastSet();
QSTORE.SetValue(params[1], std::move(obj));
_set_operation(params, 2, *res, SetOperation_diff);
FormatInt(static_cast<long>(res->size()), reply);
return QError_ok;
}
QError sdiff(const std::vector<QString>& params, UnboundedBuffer* reply)
{
QSet res;
_set_operation(params, 1, res, SetOperation_diff);
PreFormatMultiBulk(res.size(), reply);
for (const auto& elem : res)
FormatBulk(elem, reply);
return QError_ok;
}
QError sinter(const std::vector<QString>& params, UnboundedBuffer* reply)
{
QSet res;
_set_operation(params, 1, res, SetOperation_inter);
PreFormatMultiBulk(res.size(), reply);
for (const auto& elem : res)
FormatBulk(elem, reply);
return QError_ok;
}
QError sinterstore(const std::vector<QString>& params, UnboundedBuffer* reply)
{
QObject obj(QObject::CreateSet());
auto res = obj.CastSet();
QSTORE.SetValue(params[1], std::move(obj));
_set_operation(params, 2, *res, SetOperation_inter);
FormatInt(static_cast<long>(res->size()), reply);
return QError_ok;
}
QError sunion(const std::vector<QString>& params, UnboundedBuffer* reply)
{
QSet res;
_set_operation(params, 1, res, SetOperation_union);
PreFormatMultiBulk(res.size(), reply);
for (const auto& elem : res)
FormatBulk(elem, reply);
return QError_ok;
}
QError sunionstore(const std::vector<QString>& params, UnboundedBuffer* reply)
{
QObject obj(QObject::CreateSet());
auto res = obj.CastSet();
QSTORE.SetValue(params[1], std::move(obj));
_set_operation(params, 2, *res, SetOperation_union);
FormatInt(static_cast<long>(res->size()), reply);
return QError_ok;
}
size_t SScanKey(const QSet& qset, size_t cursor, size_t count, std::vector<QString>& res)
{
if (qset.empty())
return 0;
std::vector<QSet::const_local_iterator> iters;
size_t newCursor = ScanHashMember(qset, cursor, count, iters);
res.reserve(iters.size());
for (auto it : iters)
res.push_back(*it);
return newCursor;
}
}
| 22.246719 | 89 | 0.575743 | Myicefrog |
f3fcf5da364b4c84111901aa038c841a0649c138 | 4,248 | hpp | C++ | libs/core/serialization/include/hpx/serialization/tuple.hpp | sithhell/hpx | fa6e4df704bf5f81ddc0f4e09716bd11ff8724c8 | [
"BSL-1.0"
] | null | null | null | libs/core/serialization/include/hpx/serialization/tuple.hpp | sithhell/hpx | fa6e4df704bf5f81ddc0f4e09716bd11ff8724c8 | [
"BSL-1.0"
] | null | null | null | libs/core/serialization/include/hpx/serialization/tuple.hpp | sithhell/hpx | fa6e4df704bf5f81ddc0f4e09716bd11ff8724c8 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2011-2013 Thomas Heller
// Copyright (c) 2011-2013 Hartmut Kaiser
// Copyright (c) 2013-2015 Agustin Berge
// Copyright (c) 2019 Mikael Simberg
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <hpx/datastructures/tuple.hpp>
#include <hpx/serialization/detail/non_default_constructible.hpp>
#include <hpx/serialization/serialization_fwd.hpp>
#include <hpx/serialization/traits/is_bitwise_serializable.hpp>
#include <hpx/serialization/traits/is_not_bitwise_serializable.hpp>
#include <hpx/type_support/pack.hpp>
#include <cstddef>
#include <type_traits>
namespace hpx { namespace traits {
template <typename... Ts>
struct is_bitwise_serializable<::hpx::tuple<Ts...>>
: ::hpx::util::all_of<hpx::traits::is_bitwise_serializable<
typename std::remove_const<Ts>::type>...>
{
};
template <typename... Ts>
struct is_not_bitwise_serializable<::hpx::tuple<Ts...>>
: std::integral_constant<bool,
!is_bitwise_serializable_v<::hpx::tuple<Ts...>>>
{
};
}} // namespace hpx::traits
namespace hpx { namespace util { namespace detail {
template <typename Archive, typename Is, typename... Ts>
struct serialize_with_index_pack;
template <typename Archive, typename Is, typename... Ts>
struct load_construct_data_with_index_pack;
template <typename Archive, typename Is, typename... Ts>
struct save_construct_data_with_index_pack;
template <typename Archive, std::size_t... Is, typename... Ts>
struct serialize_with_index_pack<Archive, hpx::util::index_pack<Is...>,
Ts...>
{
static void call(Archive& ar, hpx::tuple<Ts...>& t, unsigned int)
{
int const _sequencer[] = {((ar & hpx::get<Is>(t)), 0)...};
(void) _sequencer;
}
};
template <typename Archive, std::size_t... Is, typename... Ts>
struct load_construct_data_with_index_pack<Archive,
hpx::util::index_pack<Is...>, Ts...>
{
static void call(
Archive& ar, hpx::tuple<Ts...>& t, unsigned int version)
{
using serialization::detail::load_construct_data;
int const _sequencer[] = {
(load_construct_data(ar, &hpx::get<Is>(t), version), 0)...};
(void) _sequencer;
}
};
template <typename Archive, std::size_t... Is, typename... Ts>
struct save_construct_data_with_index_pack<Archive,
hpx::util::index_pack<Is...>, Ts...>
{
static void call(
Archive& ar, hpx::tuple<Ts...> const& t, unsigned int version)
{
using serialization::detail::save_construct_data;
int const _sequencer[] = {
(save_construct_data(ar, &hpx::get<Is>(t), version), 0)...};
(void) _sequencer;
}
};
}}} // namespace hpx::util::detail
namespace hpx { namespace serialization {
template <typename Archive, typename... Ts>
void serialize(Archive& ar, hpx::tuple<Ts...>& t, unsigned int version)
{
using Is = typename hpx::util::make_index_pack<sizeof...(Ts)>::type;
hpx::util::detail::serialize_with_index_pack<Archive, Is, Ts...>::call(
ar, t, version);
}
template <typename Archive>
void serialize(Archive&, hpx::tuple<>&, unsigned)
{
}
template <typename Archive, typename... Ts>
void load_construct_data(
Archive& ar, hpx::tuple<Ts...>* t, unsigned int version)
{
using Is = typename hpx::util::make_index_pack<sizeof...(Ts)>::type;
hpx::util::detail::load_construct_data_with_index_pack<Archive, Is,
Ts...>::call(ar, *t, version);
}
template <typename Archive, typename... Ts>
void save_construct_data(
Archive& ar, hpx::tuple<Ts...> const* t, unsigned int version)
{
using Is = typename hpx::util::make_index_pack<sizeof...(Ts)>::type;
hpx::util::detail::save_construct_data_with_index_pack<Archive, Is,
Ts...>::call(ar, *t, version);
}
}} // namespace hpx::serialization
| 34.536585 | 80 | 0.631591 | sithhell |
6d0102336eda88378dbcb0e4d8452f213d6a579d | 239 | cpp | C++ | WinLib/WinTest/AccelTable.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | 67 | 2018-03-02T10:50:02.000Z | 2022-03-23T18:20:29.000Z | WinLib/WinTest/AccelTable.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | null | null | null | WinLib/WinTest/AccelTable.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | 9 | 2018-03-01T16:38:28.000Z | 2021-03-02T16:17:09.000Z | //----------------------------
// (c) Reliable Software, 2004
//----------------------------
#include "precompiled.h"
#include "AccelTable.h"
#include <Win/Keyboard.h>
namespace Accel
{
const Accel::Item Keys [] =
{
{ 0, 0, 0 }
};
} | 15.933333 | 30 | 0.468619 | BartoszMilewski |
6d03211e6106e170972ac9f1bc24d0a39504c4f0 | 961 | cc | C++ | src/find_the_distance_value_between_two_arrays/find_the_distance_value_between_two_arrays.cc | cuprumz/LeetCode | 5c57b0ab45e691e8d7750f531b29a25a19472d23 | [
"MIT"
] | null | null | null | src/find_the_distance_value_between_two_arrays/find_the_distance_value_between_two_arrays.cc | cuprumz/LeetCode | 5c57b0ab45e691e8d7750f531b29a25a19472d23 | [
"MIT"
] | null | null | null | src/find_the_distance_value_between_two_arrays/find_the_distance_value_between_two_arrays.cc | cuprumz/LeetCode | 5c57b0ab45e691e8d7750f531b29a25a19472d23 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int findTheDistanceValue(vector<int> &arr1, vector<int> &arr2, int d);
};
int main(int argc, char **argv) {
Solution s;
vector<int> arr1 = {4, 5, 8},
arr2 = {10, 9, 1, 8};
int d = 2;
cout << s.findTheDistanceValue(arr1, arr2, d) << endl;
arr1 = {1, 4, 2, 3};
arr2 = {-4, -3, 6, 10, 20, 30};
d = 3;
cout << s.findTheDistanceValue(arr1, arr2, d) << endl;
arr1 = {2, 1, 100, 3};
arr2 = {-5, -2, 10, -3, 7};
d = 6;
cout << s.findTheDistanceValue(arr1, arr2, d) << endl;
return 0;
}
int Solution::findTheDistanceValue(vector<int> &arr1, vector<int> &arr2, int d) {
sort(begin(arr2), end(arr2));
int ans = 0;
for (int n : arr1) {
if (upper_bound(begin(arr2), end(arr2), n + d) == lower_bound(begin(arr2), end(arr2), n - d))
++ans;
}
return ans;
} | 23.439024 | 101 | 0.552549 | cuprumz |
6d03c83c39a77193b5e1697c2d220eec19833cd4 | 785 | hpp | C++ | include/ReversingSpace/GameFileSystem.hpp | awstanley/cpp-gamefilesystem | fc06cf5f2b4f873846677f45fa5480a69cdd91df | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1 | 2021-07-12T19:25:29.000Z | 2021-07-12T19:25:29.000Z | include/ReversingSpace/GameFileSystem.hpp | awstanley/cpp-gamefilesystem | fc06cf5f2b4f873846677f45fa5480a69cdd91df | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 6 | 2017-10-16T19:30:25.000Z | 2018-10-06T23:55:19.000Z | include/ReversingSpace/GameFileSystem.hpp | awstanley/cpp-gamefilesystem | fc06cf5f2b4f873846677f45fa5480a69cdd91df | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 3 | 2017-10-14T10:21:44.000Z | 2021-07-12T19:25:39.000Z | /*
* Copyright 2017-2018 ReversingSpace. See the COPYRIGHT file at the
* top-level directory of this distribution and in the repository:
* https://github.com/ReversingSpace/cpp-gamefilesystem
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
**/
#ifndef REVERSINGSPACE_GAMEFILESYSTEM_HPP
#define REVERSINGSPACE_GAMEFILESYSTEM_HPP
// This is incomplete as it only provides storage access code.
#include <ReversingSpace/Storage/File.hpp>
#include <ReversingSpace/Storage/Directory.hpp>
#endif//REVERSINGSPACE_GAMEFILESYSTEM_HPP | 37.380952 | 68 | 0.784713 | awstanley |
6d069d2ab7cae05a38b678fe17508190feedbb0f | 1,547 | cpp | C++ | src/kriti/math/ViewGenerator.cpp | etherealvisage/kriti | 6397c4d20331d9f5ce07460df08bbac9653ffa8b | [
"BSD-3-Clause"
] | 2 | 2015-10-05T19:33:19.000Z | 2015-12-08T08:39:17.000Z | src/kriti/math/ViewGenerator.cpp | etherealvisage/kriti | 6397c4d20331d9f5ce07460df08bbac9653ffa8b | [
"BSD-3-Clause"
] | 1 | 2017-04-30T16:26:08.000Z | 2017-05-01T03:00:42.000Z | src/kriti/math/ViewGenerator.cpp | etherealvisage/kriti | 6397c4d20331d9f5ce07460df08bbac9653ffa8b | [
"BSD-3-Clause"
] | null | null | null | #include <cmath>
#include "ViewGenerator.h"
namespace Kriti {
namespace Math {
Matrix ViewGenerator::frustum(double left, double right, double top,
double bottom, double near, double far) {
Matrix result;
result(3,3) = 0.0;
result(0,0) = (2 * near) / (right - left);
result(1,1) = (2 * near) / (top - bottom);
result(0,2) = (right + left) / (right - left);
result(1,2) = (top + bottom) / (top - bottom);
result(2,2) = -((far + near)/(far - near));
result(3,2) = -1.0;
result(2,3) = -((2*far*near)/(far - near));
return result;
}
Matrix ViewGenerator::perspective(double fov, double ratio, double near,
double far) {
fov /= 2;
double range = std::tan(fov) * near;
double left = -range*ratio;
double right = range*ratio;
double top = range;
double bottom = -range;
return frustum(left, right, top, bottom, near, far);
}
Matrix ViewGenerator::orthogonal(double width, double height, double near,
double far) {
return orthogonal(-width/2, width/2, -height/2, height/2, near, far);
}
Matrix ViewGenerator::orthogonal(double left, double right, double top,
double bottom, double near, double far) {
Matrix result;
result(0,0) = 2/(right-left);
result(0,3) = -(right+left)/(right-left);
result(1,1) = 2/(top-bottom);
result(1,3) = -(top+bottom)/(top-bottom);
result(2,2) = -2/(far-near);
result(3,2) = -(far+near)/(far-near);
result(3,3) = 1.0;
return result;
}
} // namespace Math
} // namespace Kriti
| 24.555556 | 74 | 0.605042 | etherealvisage |
6d0b8412da7c93f9c10836aa99f9736e894e4cef | 8,512 | cc | C++ | src/MainActivity.cc | ilariom/wildcat | 814f054e0cf3ef0def1f6481005ffd3f0ac42d1b | [
"MIT"
] | 11 | 2018-11-07T08:54:21.000Z | 2022-02-20T22:40:47.000Z | src/MainActivity.cc | ilariom/wildcat | 814f054e0cf3ef0def1f6481005ffd3f0ac42d1b | [
"MIT"
] | null | null | null | src/MainActivity.cc | ilariom/wildcat | 814f054e0cf3ef0def1f6481005ffd3f0ac42d1b | [
"MIT"
] | 1 | 2020-07-24T09:18:48.000Z | 2020-07-24T09:18:48.000Z | #include "MainActivity.h"
#include <s2x/basics.h>
#include <globals/Scene.h>
#include <globals/SceneGraph.h>
#include <ecs/Entity.h>
#include <components/Node.h>
#include <components/Sprite.h>
#include <components/Transform.h>
#include <components/Script.h>
#include <components/KeyboardEventReceiver.h>
#include <systems/KeyboardReceiverSystem.h>
#include <systems/ScriptSystem.h>
#include <systems/MessageSystem.h>
#include <components/Dictionary.h>
#include <components/Table.h>
#include <components/MouseReceiver.h>
#include <systems/MouseReceiverSystem.h>
#include <components/ActionReceiver.h>
#include <systems/ActionReceiverSystem.h>
#include <input/InputManager.h>
#include <pixmanip/pixmanip.h>
#include <components/JSON.h>
#include <components/Crowd.h>
#include <components/Text.h>
#include <graphics/Flipbook.h>
#include <graphics/Atlas.h>
#include <components/ScriptInterface.h>
#include <utils/search_path.h>
#include <scripts/Animator.h>
#include <components/Body.h>
#include <memory>
#include <iostream>
using namespace wkt::components;
using namespace wkt::events;
using namespace wkt::gph;
using namespace wkt::math;
class Mover : public Script
{
public:
void init() override
{
s2x::log("INIT!");
auto& entity = *getEntity();
auto sprite = *entity.query<Sprite>();
// sprite->shade(wkt::pixmanip::blackAndWhite(.3f, .3f, .4f));
auto mouseRecv = std::make_shared<MouseReceiver>();
mouseRecv->onButton = [this, sprite] (const wkt::events::MouseButtonEvent& ev) {
if(ev.event == wkt::events::ButtonEvent::UP)
sprite->shade(wkt::pixmanip::darken(.9f));
};
Atlas atlas;
Atlas::Card card;
Atlas::atlas_iterator it = atlas.end();
// auto anim = *getEntity()->query<scripts::FlipbookAnimator>();
// anim->start();
// wkt::math::Rect r;
// r.origin.x = 0;
// r.origin.y = 0;
// r.size.width = 20;
// r.size.height = 20;
// wkt::math::Rect s;
// s.origin.x = 30;
// r.origin.y = 0;
// r.size.width = 200;
// r.size.height = 200;
// this->fc.addChannel(Flipbook {
// {
// { r, 100 },
// { s, 30 }
// }
// });
// this->fc.setChannel(0);
entity += mouseRecv;
scheduleUpdate();
}
void onMessage(const std::string& msg, const wkt::ecs::Entity& sender) override { s2x::log(msg); }
void update(duration dt) override
{
// if (fc.hasNext())
// {
// auto ninja = *getEntity()->query<Sprite>();
// ninja->crop(fc.next().rect);
// }
}
private:
FlipbookChannels fc;
};
namespace wkt {
namespace components
{
REGISTER_SCRIPT(Mover);
}}
namespace wkt
{
void MainActivity::onCreate(StartupConfig& conf)
{
conf.appName = "Wildcat Test App";
conf.orgName = "Wildcat Developer";
conf.windowWidth = 640;
conf.windowHeight = 480;
conf.isFullscreen = false;
conf.hardwareAccelerated = true;
conf.fps = 60;
s2x::log("CREATE!");
wkt::path::add("../res");
}
void MainActivity::onStart()
{
auto scene = std::make_shared<wkt::scene::Scene>();
auto& entity = scene->getDefaultSceneGraph().entityManager().make();
auto node = std::make_shared<Node>();
auto mt = std::make_shared<Transform>();
entity += node;
entity += mt;
// entity += std::make_shared<JSON>();
auto s = std::make_shared<Sprite>("ninja.png");
entity += s;
// mt->setScale(.5f);
// mt->setRotation(45);
// mt->setRotationAnchor({
// .5f, .5f
// });
mt->setPosition({
200, 0
});
Body::Config bodyConf;
bodyConf.mass = 2;
bodyConf.torque = 1;
auto body = std::make_shared<wkt::components::Body>(
*mt,
bodyConf
);
body->getBoxes().push_back({
mt->getPosition().x,
mt->getPosition().y,
s->size().width,
s->size().height
});
// body->push({
// 600,
// 0
// });
// body->torque(90);
scene->getDefaultSceneGraph().setRoot(node);
auto& ninja = scene->getDefaultSceneGraph().entityManager().make();
auto ninjat = std::make_shared<Transform>();
auto ninjan = std::make_shared<Node>();
auto ninjas = std::make_shared<Sprite>("ninja.png");
node->appendChild(ninjan);
// ninjat->setScale(.5f);
ninjat->setPosition({
-200,
0
});
ninja += ninjan;
ninja += ninjat;
ninja += ninjas;
ninjat->setScale(.5f);
std::cout << body->hit(ninjat->getPosition()) << std::endl;
// ninjat->setPosition({
// 100,
// 480 - ninjat->getScale() * ninjas->size().height
// });
// ninjat->setRotationAnchor({
// .5f, .5f
// });
// ninjat->setRotation(90);
// scene->getDefaultSceneGraph().camera().setRotation(-20);
// scene->getDefaultSceneGraph().camera().setPosition({ 50, 0 });
// ninja += std::make_shared<Mover>();
// wkt::math::Rect r;
// r.origin.x = 0;
// r.origin.y = 0;
// r.size.width = 20;
// r.size.height = 20;
// wkt::math::Rect r2;
// r2.origin.x = 30;
// r2.origin.y = 0;
// r2.size.width = 200;
// r2.size.height = 200;
// FlipbookChannels fc;
// fc.addChannel(Flipbook {
// {
// { r, 100 },
// { r2, 30 }
// }
// });
// auto anim = std::make_shared<scripts::FlipbookAnimator>(
// *ninjas,
// std::move(fc)
// );
// // ninja += anim;
// anim->getFlipbookChannels().setChannel(0, true);
// // anim->start();
// auto kan = std::make_shared<scripts::Animator>(
// *ninjat,
// true
// );
// Coords A;
// A.position = { 500.f, 0 };
// A.scaleX = A.scaleY = .5f;
// kan->getKeyframes().emplace_back(
// 2,
// A,
// "Event 1!"
// );
// A.position = { 200.f, 0 };
// kan->getKeyframes().emplace_back(
// 2,
// A,
// "Event 2!"
// );
// kan->eventListener = [] (const std::string& event) {
// std::cout << event << std::endl;
// };
// kan->completeListener = [] {
// std::cout << "Complete!" << std::endl;
// };
// ninja += kan;
// kan->start();
// std::cout << ninja.query<Script>().size() << std::endl;
// auto& txten = scene->getDefaultSceneGraph().entityManager().make();
// auto txtent = std::make_shared<Transform>();
// auto txtenn = std::make_shared<Node>();
// node->appendChild(txtenn);
// auto t1 = std::make_shared<Transform>();
// auto t2 = std::make_shared<Transform>();
// // t1->setPosition({200, 100});
// t1->setScale(1);
// t2->setScale(.5f);
// auto crowd = std::make_shared<Crowd>();
// auto id1 = crowd->emplace("ninja.png", *t1);
// auto id2 = crowd->emplace("ninja.png", *t2);
// auto kan = std::make_shared<scripts::CrowdAnimator>(
// *crowd,
// false
// );
// ninja += crowd;
// Coords A;
// A.position = { 500.f, 0 };
// A.scaleX = A.scaleY = .5f;
// kan->getKeyframes(id1).emplace_back(
// 4,
// A,
// "Event 1!"
// );
// A.position = { 200.f, 0 };
// kan->getKeyframes(id2).emplace_back(
// 4,
// A,
// "Event 2!"
// );
// kan->eventListener = [] (const std::string& event) {
// std::cout << event << std::endl;
// };
// kan->completeListener = [] {
// std::cout << "Complete!" << std::endl;
// };
// ninja += kan;
// kan->start();
// auto& e2 = scene->getDefaultSceneGraph().entityManager().make();
// auto e2node = std::make_shared<Node>();
// auto e2tr = std::make_shared<Transform>();
// // node->appendChild(e2node);
// e2tr->setPosition({640, 480});
// e2 += crowd;
// e2 += e2node;
// e2 += e2tr;
scene->getDefaultSceneGraph().systemsManager() += std::make_unique<wkt::systems::ScriptSystem>();
scene->getDefaultSceneGraph().systemsManager() += std::make_unique<wkt::systems::MouseReceiverSystem>();
wkt::scene::runScene(scene);
s2x::log("START!");
}
void MainActivity::onResume()
{
}
void MainActivity::onPause()
{
}
void MainActivity::onStop()
{
s2x::log("STOP!");
}
void MainActivity::onDestroy()
{
s2x::log("DESTROY!");
}
}
| 23.513812 | 108 | 0.549695 | ilariom |
6d0bd7ffc12c222a787490b1fafba9d3352f0a6b | 1,334 | cpp | C++ | MyGame/Main.cpp | codeart1st/EDEN3D | b39b0fbf3220320b58843990155ffd8173d8f4ef | [
"MIT"
] | null | null | null | MyGame/Main.cpp | codeart1st/EDEN3D | b39b0fbf3220320b58843990155ffd8173d8f4ef | [
"MIT"
] | null | null | null | MyGame/Main.cpp | codeart1st/EDEN3D | b39b0fbf3220320b58843990155ffd8173d8f4ef | [
"MIT"
] | null | null | null | #include <GameApplication.hpp>
#include <PerspectiveCamera.hpp>
#include <DefaultRenderer.hpp>
#include <WavefrontLoader.hpp>
#include <MouseControls.hpp>
#include <thread>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
EDEN3D::GameApplication game(hInstance, L"favicon.ico");
EDEN3D::GameWindow window(game, L"EDEN3D - MyGameWindow");
EDEN3D::PerspectiveCamera camera(XMConvertToRadians(45), window.getWidth() / (float)window.getHeight(), 0.01f, 100.0f);
camera.position(0.0f, 0.0f, -10.0f);
EDEN3D::DefaultRenderer renderer(window, {
EDEN3D::Color(0.15f, 0.15f, 0.15f, 1.0f)
});
EDEN3D::Mesh* mesh = NULL;
thread load([&] {
// load the model asynchronous
EDEN3D::WavefrontLoader::load(L"Bunny.obj", &mesh);
});
const float WIDTH_2 = window.getWidth() * 0.5;
const float HEIGHT_2 = window.getHeight() * 0.5;
const float ANGLE_RANGE = 45;
EDEN3D::MouseControls controls(game, window, [&] (long x, long y, wstring button) {
float xRot, yRot;
xRot = (y - HEIGHT_2) / HEIGHT_2 * ANGLE_RANGE;
yRot = (x - WIDTH_2) / WIDTH_2 * ANGLE_RANGE;
camera.rotation(XMConvertToRadians(xRot), XMConvertToRadians(yRot), 0);
});
int exit = game.run([&] {
// game loop
renderer.render(camera, mesh);
});
load.join();
delete mesh;
return exit;
}
| 25.653846 | 120 | 0.7009 | codeart1st |
6d11ec583e000373a68b73b63781bca01eb134f1 | 1,503 | cpp | C++ | hr/easy/string_reduction.cpp | gnom1gnom/cpp-algorithms | e460c0d1720acf0e0548452dfba05651e4868120 | [
"Unlicense"
] | null | null | null | hr/easy/string_reduction.cpp | gnom1gnom/cpp-algorithms | e460c0d1720acf0e0548452dfba05651e4868120 | [
"Unlicense"
] | null | null | null | hr/easy/string_reduction.cpp | gnom1gnom/cpp-algorithms | e460c0d1720acf0e0548452dfba05651e4868120 | [
"Unlicense"
] | null | null | null | /*
Given a string, reduce it in such a way that all of its substrings are distinct. To do so, you may delete any characters at any index. What is the minimum number of deletions needed?Note: A substring is a contiguous group of 1 or more characters within a string.
Example
s = "abab"
Substrings in s are { 'a', 'b', 'a', 'b', 'ab', 'ba', 'ab', 'aba', 'bab', 'abab'}. By deleting one "a" and one "b", the string becomes "ab" or "ba" and all of its substrings are distinct. This required 2 deletions.
Function Description
Complete the function getMinDeletions in the editor below.
getMinDeletions has the following parameter(s):
string s: the given string
Returns:
int: the minimum number of deletions required
*/
#include <bits/stdc++.h>
using namespace std;
/*
* Complete the 'getMinDeletions' function below.
*
* The function is expected to return an INTEGER.
* The function accepts STRING s as parameter.
*/
int getMinDeletions(string s)
{
unordered_set<char> letterSet;
int deletions = 0;
for (int i = 0; i < s.length(); i++)
{
// pozostawiamy w stringu unikalne litery
auto search = letterSet.find(s[i]);
if (search != letterSet.end())
deletions++; // za kazdym razem kiedy znajdujemy powtorzenie, doliczamy deletion
else
letterSet.insert(s[i]);
}
return deletions;
}
int main()
{
string s = "ffcccdndha";
int result = getMinDeletions(s);
cout << result << "\n";
return 0;
} | 25.913793 | 262 | 0.666001 | gnom1gnom |
6d1b649a073bbae366441c25eb39767fb3e2f9f6 | 1,015 | cpp | C++ | Memory_Management_Algorithms/Best_fit.cpp | Siddhartha-Dhar/Operating_System_Programs | 5bbfa8f82e270bef1e0511e82b3678de6b42d713 | [
"MIT"
] | 1 | 2021-07-21T07:04:08.000Z | 2021-07-21T07:04:08.000Z | Memory_Management_Algorithms/Best_fit.cpp | Siddhartha-Dhar/Operating_System_Programs | 5bbfa8f82e270bef1e0511e82b3678de6b42d713 | [
"MIT"
] | 1 | 2021-08-07T12:46:32.000Z | 2021-08-15T13:19:33.000Z | Memory_Management_Algorithms/Best_fit.cpp | Siddhartha-Dhar/Operating_System_Programs | 5bbfa8f82e270bef1e0511e82b3678de6b42d713 | [
"MIT"
] | 1 | 2021-08-07T13:05:33.000Z | 2021-08-07T13:05:33.000Z | #include<iostream>
#include"Query.cpp"
#include<cstdlib>
using namespace std;
//................................................Input Array
void inut_arr(int n, int *A, string s){
for(int i=0; i<n; i++){
cout << "\n" << s;
cin >> A[i];
getchar();
}
return;
}
//................................................Main Function
int main(void){
Query q;
int m, p, *mem, *procs;
cout << "\n\tEntering Blocks";
cout << "\n\t===============\n";
cout << "\n Enter the total number of memory Blocks ==> ";
cin >> m;
getchar();
mem = new int[m];
inut_arr(m, mem, "Enter the Block Capacity in KB ==> ");
cout << "\n\tEntering Processes";
cout << "\n\t==================\n";
cout << "\n Enter the total number of processes ==> ";
cin >> p;
getchar();
procs = new int[p];
inut_arr(p, procs, "Enter the process size in KB ==> ");
q.Best_fit(mem, procs, m, p);
return(0);
} | 24.756098 | 64 | 0.442365 | Siddhartha-Dhar |
6d22021288a99674246cd819e33aace0150e3182 | 1,324 | cpp | C++ | C or C++/rock_lever.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-11-01T05:48:04.000Z | 2021-04-25T05:33:47.000Z | C or C++/rock_lever.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | null | null | null | C or C++/rock_lever.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-10-31T05:29:55.000Z | 2021-06-19T09:33:53.000Z | #include <bits/stdc++.h>
#define lli long long int
#define ull unsigned long long
#define MX 100000
using std::cin;
using std::cout;
using std::cerr;
using std::floor;
using std::ceil;
using std::vector;
using std::ios_base;
using std::unordered_map;
using std::map;
using std::endl;
using std::stack;
using std::queue;
using std::max;
using std::min;
using std::deque;
using std::bitset;
using std::set;
using std::sort;
using std::hash;
using std::pair;
using std::make_pair;
using std::string;
using std::swap;
using std::hash;
int n,cnt;
long long a[MX];
void MergeAndCalc(int low, int high, int mid)
{
long long i=low,j=mid+1;
while(i <= mid && j <= high)
{
if(i < j && (a[i]&a[j]) >= (a[i]^a[j]))
cnt++;
else
j++;
}
while(i <= mid)
{
if(i < j && (a[i]&a[j]) >= (a[i]^a[j]))
cnt++;
else
i++;
}
}
void SplitHead(int s, int e)
{
int mid = (s+e)/2;
SplitHead(s,mid);
SplitHead(mid+1,e);
MergeAndCalc(e,s,mid);
}
void solve()
{
cnt = 0;
cin >> n;
for(int i=0;i<n;i++)
cin >> a[i];
cout << cnt << endl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
for(int i=0;i<t;i++)
solve();
return 0;
}
| 15.951807 | 47 | 0.539275 | amitShindeGit |
6d2525c07aa7bfcd5c277a2547fbbaa952e666d4 | 5,859 | cpp | C++ | vpc/src/v2/model/SecurityGroup.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | vpc/src/v2/model/SecurityGroup.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | vpc/src/v2/model/SecurityGroup.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/vpc/v2/model/SecurityGroup.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Vpc {
namespace V2 {
namespace Model {
SecurityGroup::SecurityGroup()
{
name_ = "";
nameIsSet_ = false;
description_ = "";
descriptionIsSet_ = false;
id_ = "";
idIsSet_ = false;
vpcId_ = "";
vpcIdIsSet_ = false;
enterpriseProjectId_ = "";
enterpriseProjectIdIsSet_ = false;
securityGroupRulesIsSet_ = false;
}
SecurityGroup::~SecurityGroup() = default;
void SecurityGroup::validate()
{
}
web::json::value SecurityGroup::toJson() const
{
web::json::value val = web::json::value::object();
if(nameIsSet_) {
val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_);
}
if(descriptionIsSet_) {
val[utility::conversions::to_string_t("description")] = ModelBase::toJson(description_);
}
if(idIsSet_) {
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_);
}
if(vpcIdIsSet_) {
val[utility::conversions::to_string_t("vpc_id")] = ModelBase::toJson(vpcId_);
}
if(enterpriseProjectIdIsSet_) {
val[utility::conversions::to_string_t("enterprise_project_id")] = ModelBase::toJson(enterpriseProjectId_);
}
if(securityGroupRulesIsSet_) {
val[utility::conversions::to_string_t("security_group_rules")] = ModelBase::toJson(securityGroupRules_);
}
return val;
}
bool SecurityGroup::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("name"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setName(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("description"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("description"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setDescription(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("vpc_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("vpc_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setVpcId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("enterprise_project_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("enterprise_project_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setEnterpriseProjectId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("security_group_rules"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("security_group_rules"));
if(!fieldValue.is_null())
{
std::vector<SecurityGroupRule> refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setSecurityGroupRules(refVal);
}
}
return ok;
}
std::string SecurityGroup::getName() const
{
return name_;
}
void SecurityGroup::setName(const std::string& value)
{
name_ = value;
nameIsSet_ = true;
}
bool SecurityGroup::nameIsSet() const
{
return nameIsSet_;
}
void SecurityGroup::unsetname()
{
nameIsSet_ = false;
}
std::string SecurityGroup::getDescription() const
{
return description_;
}
void SecurityGroup::setDescription(const std::string& value)
{
description_ = value;
descriptionIsSet_ = true;
}
bool SecurityGroup::descriptionIsSet() const
{
return descriptionIsSet_;
}
void SecurityGroup::unsetdescription()
{
descriptionIsSet_ = false;
}
std::string SecurityGroup::getId() const
{
return id_;
}
void SecurityGroup::setId(const std::string& value)
{
id_ = value;
idIsSet_ = true;
}
bool SecurityGroup::idIsSet() const
{
return idIsSet_;
}
void SecurityGroup::unsetid()
{
idIsSet_ = false;
}
std::string SecurityGroup::getVpcId() const
{
return vpcId_;
}
void SecurityGroup::setVpcId(const std::string& value)
{
vpcId_ = value;
vpcIdIsSet_ = true;
}
bool SecurityGroup::vpcIdIsSet() const
{
return vpcIdIsSet_;
}
void SecurityGroup::unsetvpcId()
{
vpcIdIsSet_ = false;
}
std::string SecurityGroup::getEnterpriseProjectId() const
{
return enterpriseProjectId_;
}
void SecurityGroup::setEnterpriseProjectId(const std::string& value)
{
enterpriseProjectId_ = value;
enterpriseProjectIdIsSet_ = true;
}
bool SecurityGroup::enterpriseProjectIdIsSet() const
{
return enterpriseProjectIdIsSet_;
}
void SecurityGroup::unsetenterpriseProjectId()
{
enterpriseProjectIdIsSet_ = false;
}
std::vector<SecurityGroupRule>& SecurityGroup::getSecurityGroupRules()
{
return securityGroupRules_;
}
void SecurityGroup::setSecurityGroupRules(const std::vector<SecurityGroupRule>& value)
{
securityGroupRules_ = value;
securityGroupRulesIsSet_ = true;
}
bool SecurityGroup::securityGroupRulesIsSet() const
{
return securityGroupRulesIsSet_;
}
void SecurityGroup::unsetsecurityGroupRules()
{
securityGroupRulesIsSet_ = false;
}
}
}
}
}
}
| 22.886719 | 114 | 0.659669 | yangzhaofeng |
6d26c8fc1fc99738bc73b07105a53d111b13b756 | 7,266 | cpp | C++ | Test.cpp | EylonNaamat/SS_b_Ex2_b | a5c00142f74b734d5deff4fa11eec0afb6885241 | [
"MIT"
] | null | null | null | Test.cpp | EylonNaamat/SS_b_Ex2_b | a5c00142f74b734d5deff4fa11eec0afb6885241 | [
"MIT"
] | null | null | null | Test.cpp | EylonNaamat/SS_b_Ex2_b | a5c00142f74b734d5deff4fa11eec0afb6885241 | [
"MIT"
] | null | null | null | // #include "doctest.h"
// #include "Notebook.hpp"
// #include "Direction.hpp"
// #include <string>
// using namespace std;
// TEST_CASE("Good input"){
// ariel::Notebook book;
// book.write(3, 5, 5, ariel::Direction::Horizontal, "my name is eylon");
// CHECK(book.read(3, 5, 5, ariel::Direction::Horizontal, 16) == "my name is eylon");
// book.erase(3,5,5,ariel::Direction::Horizontal,16);
// CHECK(book.read(3, 5, 5, ariel::Direction::Horizontal, 16) == "~~~~~~~~~~~~~~~~");
// book.write(1,5,5,ariel::Direction::Vertical, "eylon");
// CHECK(book.read(1, 5, 5, ariel::Direction::Vertical, 5) == "eylon");
// book.erase(1,5,5,ariel::Direction::Vertical,5);
// CHECK(book.read(1, 5, 5, ariel::Direction::Vertical, 5) == "~~~~~");
// book.write(2,5,5,ariel::Direction::Vertical, "naamat");
// CHECK(book.read(2, 5, 5, ariel::Direction::Vertical, 6) == "naamat");
// book.erase(2,5,5,ariel::Direction::Vertical,6);
// CHECK(book.read(2, 5, 5, ariel::Direction::Vertical, 6) == "~~~~~~");
// book.write(4, 5, 5, ariel::Direction::Horizontal, "cpp");
// CHECK(book.read(4, 5, 5, ariel::Direction::Horizontal, 3) == "cpp");
// book.erase(4,5,5,ariel::Direction::Horizontal,3);
// CHECK(book.read(4, 5, 5, ariel::Direction::Horizontal, 3) == "~~~");
// book.write(102,5,5,ariel::Direction::Vertical, "computer science");
// CHECK(book.read(102, 5, 5, ariel::Direction::Vertical, 16) == "computer science");
// book.erase(102,5,5,ariel::Direction::Vertical,16);
// CHECK(book.read(102, 5, 5, ariel::Direction::Vertical, 16) == "~~~~~~~~~~~~~~~~");
// CHECK(book.read(100,0,0,ariel::Direction::Vertical, 5) == "_____");
// CHECK(book.read(101,0,0,ariel::Direction::Horizontal, 6) == "______");
// book.write(101, 0,0,ariel::Direction::Horizontal, "");
// CHECK(book.read(101,0,0,ariel::Direction::Vertical, 1) == "_");
// }
// TEST_CASE("Bad input"){
// ariel::Notebook book;
// book.write(1, 0, 0, ariel::Direction::Horizontal, "my name is eylon");
// CHECK_THROWS(book.write(1,0,0,ariel::Direction::Horizontal, "my name is"));
// book.erase(1, 0, 0, ariel::Direction::Horizontal, 16);
// CHECK_THROWS(book.write(1,0,0,ariel::Direction::Horizontal, "my name is"));
// // CHECK_THROWS(book.erase(2,0,0,ariel::Direction::Horizontal, 5));
// // book.erase(1,0,0,ariel::Direction::Horizontal, 16);
// // CHECK_THROWS(book.erase(1,0,0,ariel::Direction::Horizontal, 5));
// CHECK_THROWS(book.write(2,0,99,ariel::Direction::Horizontal, "eylon"));
// CHECK_THROWS(book.read(3,0,99,ariel::Direction::Horizontal, 8));
// book.write(5,0,0,ariel::Direction::Horizontal, "naamat");
// CHECK_THROWS(book.write(5,0,0,ariel::Direction::Vertical, "naamat"));
// CHECK_THROWS(book.write(6,0,101,ariel::Direction::Horizontal, "cpp"));
// book.write(7,1,0,ariel::Direction::Horizontal, "eylon");
// CHECK_THROWS(book.write(7,0,0,ariel::Direction::Vertical, "cpp"));
// book.write(8,0,0,ariel::Direction::Horizontal, "computer science");
// CHECK_THROWS(book.write(8,0,3, ariel::Direction::Vertical, "cpp"));
// CHECK_THROWS(book.read(9,0,101, ariel::Direction::Horizontal, 5));
// // CHECK_THROWS(book.write(-1,0,0,ariel::Direction::Horizontal,"cpp"));
// // CHECK_THROWS(book.write(1,-1,0,ariel::Direction::Horizontal,"cpp"));
// // CHECK_THROWS(book.write(1,0,-1,ariel::Direction::Horizontal,"cpp"));
// // CHECK_THROWS(book.read(1,0,0,ariel::Direction::Horizontal,-1));
// }
//
// Created by Amit Melamed on 21/03/2022.
//
#include "doctest.h"
#include "Notebook.hpp"
#include <string>
using namespace ariel;
TEST_CASE ("bad input") {
SUBCASE("out of bounds") {
Notebook notebook;
CHECK_THROWS(notebook.write(50, 90, 105, ariel::Direction::Horizontal, "out of bound"));
CHECK_THROWS(notebook.write(50, 90, 200, ariel::Direction::Vertical, "out of bound"));
CHECK_THROWS(notebook.read(10, 10, 105, Direction::Vertical, 30));
CHECK_THROWS(notebook.read(10, 10, 105, Direction::Horizontal, 30));
CHECK_THROWS(notebook.erase(50, 20, 10, ariel::Direction::Horizontal, 105));
CHECK_THROWS(notebook.erase(50, 20, 60, ariel::Direction::Horizontal, 46));
CHECK_THROWS(notebook.write(101, 90, 105, ariel::Direction::Horizontal, "out of bound"));
CHECK_THROWS(notebook.write(102, 90, 200, ariel::Direction::Vertical, "out of bound"));
CHECK_THROWS(notebook.read(103, 10, 105, Direction::Vertical, 30));
CHECK_THROWS(notebook.read(104, 102, 1205, Direction::Horizontal, 30));
CHECK_THROWS(notebook.erase(50, 20, 150, ariel::Direction::Horizontal, 105));
CHECK_THROWS(notebook.erase(50, 220, 610, ariel::Direction::Horizontal, 46));
}
SUBCASE("negative input") {
Notebook notebook;
CHECK_THROWS(notebook.write(-10, 10, 10, Direction::Horizontal, "123"));
CHECK_THROWS(notebook.write(10, -10, 10, Direction::Horizontal, "123"));
CHECK_THROWS(notebook.write(10, 10, -10, Direction::Horizontal, "123"));
CHECK_THROWS(notebook.read(-10, 10, 10, Direction::Horizontal, 10));
CHECK_THROWS(notebook.read(10, -10, 10, Direction::Horizontal, 10));
CHECK_THROWS(notebook.read(10, 10, -10, Direction::Horizontal, 10));
CHECK_THROWS(notebook.read(10, 10, 10, Direction::Horizontal, -10));
CHECK_THROWS(notebook.erase(-10, 10, 10, Direction::Horizontal, 10));
CHECK_THROWS(notebook.erase(10, -10, 10, Direction::Horizontal, 10));
CHECK_THROWS(notebook.erase(10, 10, -10, Direction::Horizontal, 10));
CHECK_THROWS(notebook.erase(10, 10, 10, Direction::Horizontal, -10));
}
}
/**
* In this test case we will if the basic input is actually write down in the notebook.
* we are testing here:
* 1.write and read.
* 2.write erase and read.
* 3.erase and read.
* 4.read an empty page that have never been visited.
*/
TEST_CASE ("good input") {
Notebook notebook;
CHECK_NOTHROW(notebook.write(10, 10, 10, ariel::Direction::Horizontal, "best test"));
CHECK_NOTHROW(notebook.write(20, 20, 20, ariel::Direction::Vertical, "int the world"));
CHECK_NOTHROW(notebook.write(30, 30, 30, ariel::Direction::Horizontal, "give me 100"));
CHECK_NOTHROW(notebook.write(40, 40, 40, ariel::Direction::Vertical, "I LOVE C+++"));
CHECK_NOTHROW(notebook.erase(40, 40, 40, ariel::Direction::Vertical, 6));
CHECK_NOTHROW(notebook.read(10, 10, 10, ariel::Direction::Horizontal, 9));
CHECK_NOTHROW(notebook.read(20, 20, 20, ariel::Direction::Horizontal, 13));
CHECK_NOTHROW(notebook.read(30, 30, 30, ariel::Direction::Horizontal, 11));
CHECK_EQ(notebook.read(10, 10, 10, ariel::Direction::Horizontal, 9), "best test");
CHECK_EQ(notebook.read(20, 20, 20, ariel::Direction::Vertical, 13), "int the world");
CHECK_EQ(notebook.read(30, 30, 30, ariel::Direction::Horizontal, 11), "give me 100");
CHECK_EQ(notebook.read(40, 40, 40, ariel::Direction::Vertical, 11), "~~~~~~ C+++");
CHECK_EQ(notebook.read(50, 50, 50, ariel::Direction::Horizontal, 10), "__________");
CHECK_EQ(notebook.read(60, 60, 60, ariel::Direction::Vertical, 10), "__________");
}
| 49.428571 | 97 | 0.64561 | EylonNaamat |
6d272867cecbf019f6866a501ee198f710c21e31 | 12,082 | cpp | C++ | src/modules/mpd/mpd.cpp | mazunki/Waybar | 2301788a810b64be9361b15fbd8f510002c74cc4 | [
"MIT"
] | null | null | null | src/modules/mpd/mpd.cpp | mazunki/Waybar | 2301788a810b64be9361b15fbd8f510002c74cc4 | [
"MIT"
] | null | null | null | src/modules/mpd/mpd.cpp | mazunki/Waybar | 2301788a810b64be9361b15fbd8f510002c74cc4 | [
"MIT"
] | null | null | null | #include "modules/mpd/mpd.hpp"
#include <fmt/chrono.h>
#include <spdlog/spdlog.h>
#include <glibmm/ustring.h>
#include "modules/mpd/state.hpp"
#if defined(MPD_NOINLINE)
namespace waybar::modules {
#include "modules/mpd/state.inl.hpp"
} // namespace waybar::modules
#endif
waybar::modules::MPD::MPD(const std::string& id, const Json::Value& config)
: ALabel(config, "mpd", id, "{album} - {artist} - {title}", 5),
module_name_(id.empty() ? "mpd" : "mpd#" + id),
server_(nullptr),
port_(config_["port"].isUInt() ? config["port"].asUInt() : 0),
password_(config_["password"].empty() ? "" : config_["password"].asString()),
timeout_(config_["timeout"].isUInt() ? config_["timeout"].asUInt() * 1'000 : 30'000),
connection_(nullptr, &mpd_connection_free),
status_(nullptr, &mpd_status_free),
song_(nullptr, &mpd_song_free) {
if (!config_["port"].isNull() && !config_["port"].isUInt()) {
spdlog::warn("{}: `port` configuration should be an unsigned int", module_name_);
}
if (!config_["timeout"].isNull() && !config_["timeout"].isUInt()) {
spdlog::warn("{}: `timeout` configuration should be an unsigned int", module_name_);
}
if (!config["server"].isNull()) {
if (!config_["server"].isString()) {
spdlog::warn("{}:`server` configuration should be a string", module_name_);
}
server_ = config["server"].asCString();
}
event_box_.add_events(Gdk::BUTTON_PRESS_MASK);
event_box_.signal_button_press_event().connect(sigc::mem_fun(*this, &MPD::handlePlayPause));
}
auto waybar::modules::MPD::update() -> void {
context_.update();
// Call parent update
ALabel::update();
}
void waybar::modules::MPD::queryMPD() {
if (connection_ != nullptr) {
spdlog::debug("{}: fetching state information", module_name_);
try {
fetchState();
spdlog::debug("{}: fetch complete", module_name_);
} catch (std::exception const& e) {
spdlog::error("{}: {}", module_name_, e.what());
state_ = MPD_STATE_UNKNOWN;
}
dp.emit();
}
}
std::string waybar::modules::MPD::getTag(mpd_tag_type type, unsigned idx) const {
std::string result =
config_["unknown-tag"].isString() ? config_["unknown-tag"].asString() : "N/A";
const char* tag = mpd_song_get_tag(song_.get(), type, idx);
// mpd_song_get_tag can return NULL, so make sure it's valid before setting
if (tag) result = tag;
return result;
}
void waybar::modules::MPD::setLabel() {
if (connection_ == nullptr) {
label_.get_style_context()->add_class("disconnected");
label_.get_style_context()->remove_class("stopped");
label_.get_style_context()->remove_class("playing");
label_.get_style_context()->remove_class("paused");
auto format = config_["format-disconnected"].isString()
? config_["format-disconnected"].asString()
: "disconnected";
label_.set_markup(format);
if (tooltipEnabled()) {
std::string tooltip_format;
tooltip_format = config_["tooltip-format-disconnected"].isString()
? config_["tooltip-format-disconnected"].asString()
: "MPD (disconnected)";
// Nothing to format
label_.set_tooltip_text(tooltip_format);
}
return;
} else {
label_.get_style_context()->remove_class("disconnected");
}
auto format = format_;
Glib::ustring artist, album_artist, album, title;
std::string date;
int song_pos = 0, queue_length = 0, volume = 0;
std::chrono::seconds elapsedTime, totalTime;
std::string stateIcon = "";
if (stopped()) {
format =
config_["format-stopped"].isString() ? config_["format-stopped"].asString() : "stopped";
label_.get_style_context()->add_class("stopped");
label_.get_style_context()->remove_class("playing");
label_.get_style_context()->remove_class("paused");
} else {
label_.get_style_context()->remove_class("stopped");
if (playing()) {
label_.get_style_context()->add_class("playing");
label_.get_style_context()->remove_class("paused");
} else if (paused()) {
format = config_["format-paused"].isString() ? config_["format-paused"].asString()
: config_["format"].asString();
label_.get_style_context()->add_class("paused");
label_.get_style_context()->remove_class("playing");
}
stateIcon = getStateIcon();
artist = getTag(MPD_TAG_ARTIST);
album_artist = getTag(MPD_TAG_ALBUM_ARTIST);
album = getTag(MPD_TAG_ALBUM);
title = getTag(MPD_TAG_TITLE);
date = getTag(MPD_TAG_DATE);
song_pos = mpd_status_get_song_pos(status_.get());
volume = mpd_status_get_volume(status_.get());
if (volume < 0) {
volume = 0;
}
queue_length = mpd_status_get_queue_length(status_.get());
elapsedTime = std::chrono::seconds(mpd_status_get_elapsed_time(status_.get()));
totalTime = std::chrono::seconds(mpd_status_get_total_time(status_.get()));
}
bool consumeActivated = mpd_status_get_consume(status_.get());
std::string consumeIcon = getOptionIcon("consume", consumeActivated);
bool randomActivated = mpd_status_get_random(status_.get());
std::string randomIcon = getOptionIcon("random", randomActivated);
bool repeatActivated = mpd_status_get_repeat(status_.get());
std::string repeatIcon = getOptionIcon("repeat", repeatActivated);
bool singleActivated = mpd_status_get_single(status_.get());
std::string singleIcon = getOptionIcon("single", singleActivated);
if (config_["artist-len"].isInt()) artist = artist.substr(0, config_["artist-len"].asInt());
if (config_["album-artist-len"].isInt()) album_artist = album_artist.substr(0, config_["album-artist-len"].asInt());
if (config_["album-len"].isInt()) album = album.substr(0, config_["album-len"].asInt());
if (config_["title-len"].isInt()) title = title.substr(0,config_["title-len"].asInt());
try {
label_.set_markup(
fmt::format(format,
fmt::arg("artist", Glib::Markup::escape_text(artist).raw()),
fmt::arg("albumArtist", Glib::Markup::escape_text(album_artist).raw()),
fmt::arg("album", Glib::Markup::escape_text(album).raw()),
fmt::arg("title", Glib::Markup::escape_text(title).raw()),
fmt::arg("date", Glib::Markup::escape_text(date).raw()),
fmt::arg("volume", volume),
fmt::arg("elapsedTime", elapsedTime),
fmt::arg("totalTime", totalTime),
fmt::arg("songPosition", song_pos),
fmt::arg("queueLength", queue_length),
fmt::arg("stateIcon", stateIcon),
fmt::arg("consumeIcon", consumeIcon),
fmt::arg("randomIcon", randomIcon),
fmt::arg("repeatIcon", repeatIcon),
fmt::arg("singleIcon", singleIcon)));
} catch (fmt::format_error const& e) {
spdlog::warn("mpd: format error: {}", e.what());
}
if (tooltipEnabled()) {
std::string tooltip_format;
tooltip_format = config_["tooltip-format"].isString() ? config_["tooltip-format"].asString()
: "MPD (connected)";
try {
auto tooltip_text = fmt::format(tooltip_format,
fmt::arg("artist", artist.raw()),
fmt::arg("albumArtist", album_artist.raw()),
fmt::arg("album", album.raw()),
fmt::arg("title", title.raw()),
fmt::arg("date", date),
fmt::arg("volume", volume),
fmt::arg("elapsedTime", elapsedTime),
fmt::arg("totalTime", totalTime),
fmt::arg("songPosition", song_pos),
fmt::arg("queueLength", queue_length),
fmt::arg("stateIcon", stateIcon),
fmt::arg("consumeIcon", consumeIcon),
fmt::arg("randomIcon", randomIcon),
fmt::arg("repeatIcon", repeatIcon),
fmt::arg("singleIcon", singleIcon));
label_.set_tooltip_text(tooltip_text);
} catch (fmt::format_error const& e) {
spdlog::warn("mpd: format error (tooltip): {}", e.what());
}
}
}
std::string waybar::modules::MPD::getStateIcon() const {
if (!config_["state-icons"].isObject()) {
return "";
}
if (connection_ == nullptr) {
spdlog::warn("{}: Trying to fetch state icon while disconnected", module_name_);
return "";
}
if (stopped()) {
spdlog::warn("{}: Trying to fetch state icon while stopped", module_name_);
return "";
}
if (playing()) {
return config_["state-icons"]["playing"].asString();
} else {
return config_["state-icons"]["paused"].asString();
}
}
std::string waybar::modules::MPD::getOptionIcon(std::string optionName, bool activated) const {
if (!config_[optionName + "-icons"].isObject()) {
return "";
}
if (connection_ == nullptr) {
spdlog::warn("{}: Trying to fetch option icon while disconnected", module_name_);
return "";
}
if (activated) {
return config_[optionName + "-icons"]["on"].asString();
} else {
return config_[optionName + "-icons"]["off"].asString();
}
}
void waybar::modules::MPD::tryConnect() {
if (connection_ != nullptr) {
return;
}
connection_ =
detail::unique_connection(mpd_connection_new(server_, port_, timeout_), &mpd_connection_free);
if (connection_ == nullptr) {
spdlog::error("{}: Failed to connect to MPD", module_name_);
connection_.reset();
return;
}
try {
checkErrors(connection_.get());
spdlog::debug("{}: Connected to MPD", module_name_);
if (!password_.empty()) {
bool res = mpd_run_password(connection_.get(), password_.c_str());
if (!res) {
spdlog::error("{}: Wrong MPD password", module_name_);
connection_.reset();
return;
}
checkErrors(connection_.get());
}
} catch (std::runtime_error& e) {
spdlog::error("{}: Failed to connect to MPD: {}", module_name_, e.what());
connection_.reset();
}
}
void waybar::modules::MPD::checkErrors(mpd_connection* conn) {
switch (mpd_connection_get_error(conn)) {
case MPD_ERROR_SUCCESS:
mpd_connection_clear_error(conn);
return;
case MPD_ERROR_TIMEOUT:
case MPD_ERROR_CLOSED:
mpd_connection_clear_error(conn);
connection_.reset();
state_ = MPD_STATE_UNKNOWN;
throw std::runtime_error("Connection to MPD closed");
default:
if (conn) {
auto error_message = mpd_connection_get_error_message(conn);
std::string error(error_message);
mpd_connection_clear_error(conn);
throw std::runtime_error(error);
}
throw std::runtime_error("Invalid connection");
}
}
void waybar::modules::MPD::fetchState() {
if (connection_ == nullptr) {
spdlog::error("{}: Not connected to MPD", module_name_);
return;
}
auto conn = connection_.get();
status_ = detail::unique_status(mpd_run_status(conn), &mpd_status_free);
checkErrors(conn);
state_ = mpd_status_get_state(status_.get());
checkErrors(conn);
song_ = detail::unique_song(mpd_run_current_song(conn), &mpd_song_free);
checkErrors(conn);
}
bool waybar::modules::MPD::handlePlayPause(GdkEventButton* const& e) {
if (e->type == GDK_2BUTTON_PRESS || e->type == GDK_3BUTTON_PRESS || connection_ == nullptr) {
return false;
}
if (e->button == 1) {
if (state_ == MPD_STATE_PLAY)
context_.pause();
else
context_.play();
} else if (e->button == 3) {
context_.stop();
}
return true;
}
| 36.282282 | 118 | 0.602218 | mazunki |
6d2a3daaea0cbdf5a139f2bbf8619593245f5b49 | 847 | hpp | C++ | experimental/Pomdog.Experimental/Rendering/RenderCommandProcessor.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Rendering/RenderCommandProcessor.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Rendering/RenderCommandProcessor.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include "Pomdog.Experimental/Rendering/RenderCommand.hpp"
#include "Pomdog/Graphics/detail/ForwardDeclarations.hpp"
#include "Pomdog/Math/Matrix4x4.hpp"
#include <typeindex>
namespace Pomdog {
class RenderCommandProcessor {
public:
virtual ~RenderCommandProcessor() = default;
virtual void Begin(
const std::shared_ptr<GraphicsCommandList>& commandList,
const Matrix4x4& viewProjection) = 0;
virtual void Draw(
const std::shared_ptr<GraphicsCommandList>& commandList,
RenderCommand & command) = 0;
virtual void FlushBatch() = 0;
virtual void End() = 0;
virtual int GetDrawCallCount() const noexcept = 0;
virtual std::type_index GetCommandType() const noexcept = 0;
};
} // namespace Pomdog
| 24.911765 | 71 | 0.720189 | ValtoForks |
6d2da2ff2e845b520516b038e9dd2c2c4dcedb7e | 23,627 | cpp | C++ | src/modules/processes/contrib/gviehoever/GradientDomain/GradientsHdrCompositionInterface.cpp | kkretzschmar/PCL | 6354627260482afcb278a3f3a2bf30c26210d4fa | [
"JasPer-2.0"
] | null | null | null | src/modules/processes/contrib/gviehoever/GradientDomain/GradientsHdrCompositionInterface.cpp | kkretzschmar/PCL | 6354627260482afcb278a3f3a2bf30c26210d4fa | [
"JasPer-2.0"
] | null | null | null | src/modules/processes/contrib/gviehoever/GradientDomain/GradientsHdrCompositionInterface.cpp | kkretzschmar/PCL | 6354627260482afcb278a3f3a2bf30c26210d4fa | [
"JasPer-2.0"
] | null | null | null | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.11.0938
// ----------------------------------------------------------------------------
// Standard GradientDomain Process Module Version 00.06.04.0240
// ----------------------------------------------------------------------------
// GradientsHdrCompositionInterface.cpp - Released 2019-01-21T12:06:42Z
// ----------------------------------------------------------------------------
// This file is part of the standard GradientDomain PixInsight module.
//
// Copyright (c) Georg Viehoever, 2011-2018. Licensed under LGPL 2.1
// Copyright (c) 2003-2018 Pleiades Astrophoto S.L.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
// ----------------------------------------------------------------------------
#include "GradientsHdrCompositionInterface.h"
#include "GradientsHdrCompositionProcess.h"
#include <pcl/Dialog.h>
#include <pcl/ErrorHandler.h>
#include <pcl/FileDialog.h>
#include <pcl/FileFormat.h>
#include <pcl/GlobalSettings.h>
#include <pcl/ViewList.h>
#define IMAGELIST_MINHEIGHT( fnt ) RoundInt( 8.125*fnt.Height() )
namespace pcl
{
// ----------------------------------------------------------------------------
GradientsHdrCompositionInterface* TheGradientsHdrCompositionInterface = nullptr;
// ----------------------------------------------------------------------------
//FIXME
//#include "GradientsHdrCompositionIcon.xpm"
// ----------------------------------------------------------------------------
GradientsHdrCompositionInterface::GradientsHdrCompositionInterface() :
instance( TheGradientsHdrCompositionProcess )
{
TheGradientsHdrCompositionInterface = this;
/*
* The auto save geometry feature is of no good to interfaces that include
* both auto-expanding controls (e.g. TreeBox) and collapsible sections
* (e.g. SectionBar).
*/
DisableAutoSaveGeometry();
}
GradientsHdrCompositionInterface::~GradientsHdrCompositionInterface()
{
if ( GUI != nullptr )
delete GUI, GUI = nullptr;
}
IsoString GradientsHdrCompositionInterface::Id() const
{
return "GradientHDRComposition";
}
IsoString GradientsHdrCompositionInterface::Aliases() const
{
return "GradientsHdrComposition";
}
MetaProcess* GradientsHdrCompositionInterface::Process() const
{
return TheGradientsHdrCompositionProcess;
}
const char** GradientsHdrCompositionInterface::IconImageXPM() const
{
return nullptr;
// FIXME
// return GradientsHdrCompositionIcon_XPM;
}
InterfaceFeatures GradientsHdrCompositionInterface::Features() const
{
return InterfaceFeature::DefaultGlobal;
}
void GradientsHdrCompositionInterface::ApplyInstance() const
{
instance.LaunchOnCurrentView();
}
void GradientsHdrCompositionInterface::ResetInstance()
{
GradientsHdrCompositionInstance defaultInstance( TheGradientsHdrCompositionProcess );
ImportProcess( defaultInstance );
}
bool GradientsHdrCompositionInterface::Launch( const MetaProcess& P, const ProcessImplementation*, bool& dynamic, unsigned& /*flags*/ )
{
if ( GUI == nullptr )
{
GUI = new GUIData( *this );
SetWindowTitle( "GradientHDRComposition" );
UpdateControls();
// Restore position only
if ( !RestoreGeometry() )
SetDefaultPosition();
AdjustToContents();
}
dynamic = false;
return &P == TheGradientsHdrCompositionProcess;
}
ProcessImplementation* GradientsHdrCompositionInterface::NewProcess() const
{
return new GradientsHdrCompositionInstance( instance );
}
bool GradientsHdrCompositionInterface::ValidateProcess( const ProcessImplementation& p, pcl::String& whyNot ) const
{
if ( dynamic_cast<const GradientsHdrCompositionInstance*>( &p ) != nullptr )
return true;
whyNot = "Not a GradientHDRComposition instance.";
return false;
}
bool GradientsHdrCompositionInterface::RequiresInstanceValidation() const
{
return true;
}
bool GradientsHdrCompositionInterface::ImportProcess( const ProcessImplementation& p )
{
instance.Assign( p );
UpdateControls();
return true;
}
void GradientsHdrCompositionInterface::SaveSettings() const
{
SaveGeometry();
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
void GradientsHdrCompositionInterface::UpdateControls()
{
UpdateTargetImagesList();
UpdateImageSelectionButtons();
UpdateParameters();
}
void GradientsHdrCompositionInterface::UpdateTargetImageItem( size_type i )
{
TreeBox::Node* node = GUI->TargetImages_TreeBox[i];
if ( node == nullptr )
return;
const GradientsHdrCompositionInstance::ImageItem& item = instance.targetFrames[i];
node->SetText( 0, String( i+1 ) );
node->SetAlignment( 0, TextAlign::Right );
node->SetIcon( 1, Bitmap( ScaledResource( item.enabled ? ":/icons/enabled.png" : ":/icons/disabled.png" ) ) );
node->SetAlignment( 1, TextAlign::Left );
node->SetIcon( 2, Bitmap( ScaledResource( ":/icons/document.png" ) ) );
if ( GUI->FullPaths_CheckBox.IsChecked() )
node->SetText( 2, item.path );
else
{
String fileName = File::ExtractName( item.path ) + File::ExtractExtension( item.path );
node->SetText( 2, fileName );
node->SetToolTip( 2, item.path );
}
node->SetAlignment( 2, TextAlign::Left );
}
void GradientsHdrCompositionInterface::UpdateTargetImagesList()
{
int currentIdx = GUI->TargetImages_TreeBox.ChildIndex( GUI->TargetImages_TreeBox.CurrentNode() );
GUI->TargetImages_TreeBox.DisableUpdates();
GUI->TargetImages_TreeBox.Clear();
for ( size_type i = 0; i < instance.targetFrames.Length(); ++i )
{
new TreeBox::Node( GUI->TargetImages_TreeBox );
UpdateTargetImageItem( i );
}
GUI->TargetImages_TreeBox.AdjustColumnWidthToContents( 0 );
GUI->TargetImages_TreeBox.AdjustColumnWidthToContents( 1 );
GUI->TargetImages_TreeBox.AdjustColumnWidthToContents( 2 );
if ( !instance.targetFrames.IsEmpty() )
if ( currentIdx >= 0 && currentIdx < GUI->TargetImages_TreeBox.NumberOfChildren() )
GUI->TargetImages_TreeBox.SetCurrentNode( GUI->TargetImages_TreeBox[currentIdx] );
GUI->TargetImages_TreeBox.EnableUpdates();
}
void GradientsHdrCompositionInterface::UpdateImageSelectionButtons()
{
bool hasItems = GUI->TargetImages_TreeBox.NumberOfChildren() > 0;
bool hasSelection = hasItems && GUI->TargetImages_TreeBox.HasSelectedTopLevelNodes();
GUI->SelectAll_PushButton.Enable( hasItems );
GUI->InvertSelection_PushButton.Enable( hasItems );
GUI->ToggleSelected_PushButton.Enable( hasSelection );
GUI->RemoveSelected_PushButton.Enable( hasSelection );
GUI->Clear_PushButton.Enable( hasItems );
//GUI->FullPaths_CheckBox.Enable( hasItems ); // always enabled
}
void GradientsHdrCompositionInterface::UpdateParameters()
{
GUI->LogBias_NumericControl.SetValue(instance.dLogBias);
GUI->KeepLog_CheckBox.SetChecked(instance.bKeepLog);
GUI->NegativeBias_CheckBox.SetChecked(instance.bNegativeBias);
GUI->GenerateMask_CheckBox.SetChecked(instance.generateMask);
}
// ----------------------------------------------------------------------------
void GradientsHdrCompositionInterface::__TargetImages_CurrentNodeUpdated( TreeBox& sender,
TreeBox::Node& current, TreeBox::Node& oldCurrent )
{
// Actually do nothing (placeholder). Just perform a sanity check.
int index = sender.ChildIndex( ¤t );
if ( index < 0 || size_type( index ) >= instance.targetFrames.Length() )
throw Error( "GradientsHdrCompositionInterface: *Warning* Corrupted interface structures" );
// ### If there's something else that depends on which image is selected in the list, do it here.
}
void GradientsHdrCompositionInterface::__TargetImages_NodeActivated( TreeBox& sender, TreeBox::Node& node, int col )
{
int index = sender.ChildIndex( &node );
if ( index < 0 || size_type( index ) >= instance.targetFrames.Length() )
throw Error( "GradientsHdrCompositionInterface: *Warning* Corrupted interface structures" );
GradientsHdrCompositionInstance::ImageItem& item = instance.targetFrames[index];
switch ( col )
{
case 0:
// Activate the item's index number: ignore.
break;
case 1:
// Activate the item's checkmark: toggle item's enabled state.
item.enabled = !item.enabled;
UpdateTargetImageItem( index );
break;
case 2:
{
// Activate the item's path: open the image.
Array<ImageWindow> w = ImageWindow::Open( item.path );
for ( Array<ImageWindow>::iterator i = w.Begin(); i != w.End(); ++i )
i->Show();
}
break;
}
}
void GradientsHdrCompositionInterface::__TargetImages_NodeSelectionUpdated( TreeBox& sender )
{
UpdateImageSelectionButtons();
}
static size_type TreeInsertionIndex( const TreeBox& tree )
{
const TreeBox::Node* n = tree.CurrentNode();
return (n != nullptr) ? tree.ChildIndex( n ) + 1 : tree.NumberOfChildren();
}
void GradientsHdrCompositionInterface::__TargetImages_Click( Button& sender, bool checked )
{
if ( sender == GUI->AddFiles_PushButton )
{
OpenFileDialog d;
d.EnableMultipleSelections();
d.LoadImageFilters();
d.SetCaption( "GradientsHdrComposition: Select Target Frames" );
if ( d.Execute() )
{
size_type i0 = TreeInsertionIndex( GUI->TargetImages_TreeBox );
for ( StringList::const_iterator i = d.FileNames().Begin(); i != d.FileNames().End(); ++i )
instance.targetFrames.Insert( instance.targetFrames.At( i0++ ), GradientsHdrCompositionInstance::ImageItem( *i ) );
UpdateTargetImagesList();
UpdateImageSelectionButtons();
}
}
else if ( sender == GUI->SelectAll_PushButton )
{
GUI->TargetImages_TreeBox.SelectAllNodes();
UpdateImageSelectionButtons();
}
else if ( sender == GUI->InvertSelection_PushButton )
{
for ( int i = 0, n = GUI->TargetImages_TreeBox.NumberOfChildren(); i < n; ++i )
GUI->TargetImages_TreeBox[i]->Select( !GUI->TargetImages_TreeBox[i]->IsSelected() );
UpdateImageSelectionButtons();
}
else if ( sender == GUI->ToggleSelected_PushButton )
{
for ( int i = 0, n = GUI->TargetImages_TreeBox.NumberOfChildren(); i < n; ++i )
if ( GUI->TargetImages_TreeBox[i]->IsSelected() )
instance.targetFrames[i].enabled = !instance.targetFrames[i].enabled;
UpdateTargetImagesList();
UpdateImageSelectionButtons();
}
else if ( sender == GUI->RemoveSelected_PushButton )
{
GradientsHdrCompositionInstance::image_list newTargets;
for ( int i = 0, n = GUI->TargetImages_TreeBox.NumberOfChildren(); i < n; ++i )
if ( !GUI->TargetImages_TreeBox[i]->IsSelected() )
newTargets.Add( instance.targetFrames[i] );
instance.targetFrames = newTargets;
UpdateTargetImagesList();
UpdateImageSelectionButtons();
}
else if ( sender == GUI->Clear_PushButton )
{
instance.targetFrames.Clear();
UpdateTargetImagesList();
UpdateImageSelectionButtons();
}
else if ( sender == GUI->FullPaths_CheckBox )
{
UpdateTargetImagesList();
UpdateImageSelectionButtons();
}
}
void GradientsHdrCompositionInterface::__ToggleSection( SectionBar& sender, Control& section, bool start )
{
if ( start )
GUI->TargetImages_TreeBox.SetFixedHeight();
else
{
GUI->TargetImages_TreeBox.SetMinHeight( IMAGELIST_MINHEIGHT( Font() ) );
GUI->TargetImages_TreeBox.SetMaxHeight( int_max );
}
}
void GradientsHdrCompositionInterface::__logBiasUpdated( NumericEdit& sender, double value )
{
if ( sender == GUI->LogBias_NumericControl )
instance.dLogBias = value;
}
void GradientsHdrCompositionInterface::__KeepLogClicked( Button& sender, bool checked )
{
if ( sender == GUI->KeepLog_CheckBox )
instance.bKeepLog=checked;
}
void GradientsHdrCompositionInterface::__NegativeBiasClicked( Button& sender, bool checked )
{
if ( sender == GUI->NegativeBias_CheckBox )
instance.bNegativeBias=checked;
}
void GradientsHdrCompositionInterface::__GenerateMaskClicked( Button& sender, bool checked )
{
if ( sender == GUI->GenerateMask_CheckBox )
instance.generateMask=checked;
}
void GradientsHdrCompositionInterface::__FileDrag( Control& sender, const Point& pos, const StringList& files, unsigned modifiers, bool& wantsFiles )
{
if ( sender == GUI->TargetImages_TreeBox.Viewport() )
wantsFiles = true;
}
void GradientsHdrCompositionInterface::__FileDrop( Control& sender, const Point& pos, const StringList& files, unsigned modifiers )
{
if ( sender == GUI->TargetImages_TreeBox.Viewport() )
{
StringList inputFiles;
bool recursive = IsControlOrCmdPressed();
for ( const String& item : files )
if ( File::Exists( item ) )
inputFiles << item;
else if ( File::DirectoryExists( item ) )
inputFiles << FileFormat::SupportedImageFiles( item, true/*toRead*/, false/*toWrite*/, recursive );
inputFiles.Sort();
size_type i0 = TreeInsertionIndex( GUI->TargetImages_TreeBox );
for ( const String& file : inputFiles )
instance.targetFrames.Insert( instance.targetFrames.At( i0++ ), GradientsHdrCompositionInstance::ImageItem( file ) );
UpdateTargetImagesList();
UpdateImageSelectionButtons();
}
}
// ----------------------------------------------------------------------------
GradientsHdrCompositionInterface::GUIData::GUIData( GradientsHdrCompositionInterface& w )
{
pcl::Font fnt = w.Font();
int const labelWidth1 = fnt.Width( String( "Optimization window (px):" ) + 'T' );
int const editWidth1 = fnt.Width( String( 'M', 5 ) );
//
w.SetToolTip( "<p>Integrates images of different exposures into a combined image using a gradient domain method. "
"Useful for creating HDR images.</p>"
"<p>(c) 2011 Georg Viehoever, published under LGPL 2.1. "
"With important contributions in terms of tests, test data, code and ideas "
"by Carlos Milovic, Harry Page and Alejandro Tombolini.</p>" );
TargetImages_SectionBar.SetTitle( "Target Frames" );
TargetImages_SectionBar.SetSection( TargetImages_Control );
TargetImages_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&GradientsHdrCompositionInterface::__ToggleSection, w );
TargetImages_TreeBox.SetMinHeight( IMAGELIST_MINHEIGHT( fnt ) );
TargetImages_TreeBox.SetNumberOfColumns( 3 );
TargetImages_TreeBox.HideHeader();
TargetImages_TreeBox.EnableMultipleSelections();
TargetImages_TreeBox.DisableRootDecoration();
TargetImages_TreeBox.EnableAlternateRowColor();
TargetImages_TreeBox.OnCurrentNodeUpdated( (TreeBox::node_navigation_event_handler)&GradientsHdrCompositionInterface::__TargetImages_CurrentNodeUpdated, w );
TargetImages_TreeBox.OnNodeActivated( (TreeBox::node_event_handler)&GradientsHdrCompositionInterface::__TargetImages_NodeActivated, w );
TargetImages_TreeBox.OnNodeSelectionUpdated( (TreeBox::tree_event_handler)&GradientsHdrCompositionInterface::__TargetImages_NodeSelectionUpdated, w );
TargetImages_TreeBox.Viewport().OnFileDrag( (Control::file_drag_event_handler)&GradientsHdrCompositionInterface::__FileDrag, w );
TargetImages_TreeBox.Viewport().OnFileDrop( (Control::file_drop_event_handler)&GradientsHdrCompositionInterface::__FileDrop, w );
AddFiles_PushButton.SetText( "Add Files..." );
AddFiles_PushButton.SetToolTip( "<p>Add existing image files to the list.</p>" );
AddFiles_PushButton.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
SelectAll_PushButton.SetText( "Select All" );
SelectAll_PushButton.SetToolTip( "<p>Select all images.</p>" );
SelectAll_PushButton.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
InvertSelection_PushButton.SetText( "Invert Selection" );
InvertSelection_PushButton.SetToolTip( "<p>Invert the current selection of images.</p>" );
InvertSelection_PushButton.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
ToggleSelected_PushButton.SetText( "Toggle Selected" );
ToggleSelected_PushButton.SetToolTip( "<p>Toggle the enabled/disabled state of currently selected images.</p>"
"<p>Disabled images will be ignored during the process.</p>" );
ToggleSelected_PushButton.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
RemoveSelected_PushButton.SetText( "Remove Selected" );
RemoveSelected_PushButton.SetToolTip( "<p>Remove all currently selected images.</p>" );
RemoveSelected_PushButton.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
Clear_PushButton.SetText( "Clear" );
Clear_PushButton.SetToolTip( "<p>Clear the list of images.</p>" );
Clear_PushButton.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
FullPaths_CheckBox.SetText( "Full paths" );
FullPaths_CheckBox.SetToolTip( "<p>Show full paths for image files.</p>" );
FullPaths_CheckBox.OnClick( (Button::click_event_handler)&GradientsHdrCompositionInterface::__TargetImages_Click, w );
TargetButtons_Sizer.SetSpacing( 4 );
TargetButtons_Sizer.Add( AddFiles_PushButton );
TargetButtons_Sizer.Add( SelectAll_PushButton );
TargetButtons_Sizer.Add( InvertSelection_PushButton );
TargetButtons_Sizer.Add( ToggleSelected_PushButton );
TargetButtons_Sizer.Add( RemoveSelected_PushButton );
TargetButtons_Sizer.Add( Clear_PushButton );
TargetButtons_Sizer.Add( FullPaths_CheckBox );
TargetButtons_Sizer.AddStretch();
TargetImages_Sizer.SetSpacing( 4 );
TargetImages_Sizer.Add( TargetImages_TreeBox, 100 );
TargetImages_Sizer.Add( TargetButtons_Sizer );
TargetImages_Control.SetSizer( TargetImages_Sizer );
TargetImages_Control.AdjustToContents();
Parameters_SectionBar.SetTitle( "Parameters" );
Parameters_SectionBar.SetSection( Parameters_Control );
Parameters_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&GradientsHdrCompositionInterface::__ToggleSection, w );
const char *biasToolTip="<p>Log10 of bias of image. This should identify the true black point of the images. " // ### Clarify description
"Smallest value is neutral. Use if result image is too faint</p>";
LogBias_NumericControl.label.SetText( "Log10 Bias:" );
LogBias_NumericControl.label.SetFixedWidth( labelWidth1 );
LogBias_NumericControl.slider.SetScaledMinWidth( 250 );
LogBias_NumericControl.slider.SetRange( 0, 100 );
LogBias_NumericControl.SetReal();
LogBias_NumericControl.SetRange( TheGradientsHdrCompositionLogBiasParameter->MinimumValue(), TheGradientsHdrCompositionLogBiasParameter->MaximumValue() );
LogBias_NumericControl.SetPrecision( TheGradientsHdrCompositionLogBiasParameter->Precision() );
LogBias_NumericControl.SetToolTip( biasToolTip);
LogBias_NumericControl.edit.SetFixedWidth( editWidth1 );
LogBias_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&GradientsHdrCompositionInterface::__logBiasUpdated, w );
const char* negativeBiasToolTip="<p>Experimental: Use if you suspect your image has a negative bias (very unusual).</p>";
NegativeBias_Label.SetText("NegativeBias:");
NegativeBias_Label.SetFixedWidth(labelWidth1);
NegativeBias_Label.SetTextAlignment(TextAlign::Right|TextAlign::VertCenter );
NegativeBias_Label.SetToolTip(negativeBiasToolTip);
NegativeBias_CheckBox.SetChecked(TheGradientsHdrCompositionNegativeBiasParameter->DefaultValue());
NegativeBias_CheckBox.SetToolTip(negativeBiasToolTip);
NegativeBias_CheckBox.OnClick( (pcl::Button::click_event_handler)&GradientsHdrCompositionInterface::__NegativeBiasClicked,w);
Bias_Sizer.SetSpacing( 4 );
Bias_Sizer.Add(LogBias_NumericControl);
const char* keepLogToolTip="<p>Check to keep the result in the logarithmic scale, which is better for visualization. "
"Uncheck to get a more or less linear result, which is better for further processing.</p>";
KeepLog_Label.SetText("Keep in log() scale:");
KeepLog_Label.SetFixedWidth(labelWidth1);
KeepLog_Label.SetTextAlignment(TextAlign::Right|TextAlign::VertCenter );
KeepLog_Label.SetToolTip(keepLogToolTip);
KeepLog_CheckBox.SetChecked(TheGradientsHdrCompositionKeepLogParameter->DefaultValue());
KeepLog_CheckBox.SetToolTip(keepLogToolTip);
KeepLog_CheckBox.OnClick( (pcl::Button::click_event_handler)&GradientsHdrCompositionInterface::__KeepLogClicked,w);
KeepLog_Sizer.SetSpacing( 4 );
KeepLog_Sizer.Add(KeepLog_Label);
KeepLog_Sizer.Add(KeepLog_CheckBox);
const char* maskToolTip="<p>Check to generate two masks showing the contributions of each image to horizontal and vertical "
"gradients. Each pixel identifies the image that contributed to the respective gradient. 0 means no image. "
"The masks are rescaled before displaying.</p>";
GenerateMask_Label.SetText("Generate masks:");
GenerateMask_Label.SetFixedWidth(labelWidth1);
GenerateMask_Label.SetTextAlignment(TextAlign::Right|TextAlign::VertCenter );
GenerateMask_Label.SetToolTip(maskToolTip);
GenerateMask_CheckBox.SetChecked(TheGradientsHdrCompositionGenerateMaskParameter->DefaultValue());
GenerateMask_CheckBox.SetToolTip(maskToolTip);
GenerateMask_CheckBox.OnClick( (pcl::Button::click_event_handler)&GradientsHdrCompositionInterface::__GenerateMaskClicked,w);
GenerateMask_Sizer.SetSpacing( 4 );
GenerateMask_Sizer.Add(GenerateMask_Label);
GenerateMask_Sizer.Add(GenerateMask_CheckBox);
GenerateMask_Sizer.Add(NegativeBias_Label);
GenerateMask_Sizer.Add(NegativeBias_CheckBox);
Parameters_Sizer.SetSpacing( 4 );
Parameters_Sizer.Add(Bias_Sizer);
Parameters_Sizer.Add(KeepLog_Sizer);
Parameters_Sizer.Add(GenerateMask_Sizer);
Parameters_Control.SetSizer(Parameters_Sizer);
Parameters_Control.AdjustToContents();
Global_Sizer.SetMargin( 8 );
Global_Sizer.SetSpacing( 6 );
Global_Sizer.Add( TargetImages_SectionBar );
Global_Sizer.Add( TargetImages_Control );
Global_Sizer.Add( Parameters_SectionBar );
Global_Sizer.Add( Parameters_Control );
w.SetSizer( Global_Sizer );
w.SetFixedWidth();
w.AdjustToContents();
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF GradientsHdrCompositionInterface.cpp - Released 2019-01-21T12:06:42Z
| 40.666093 | 160 | 0.708765 | kkretzschmar |
6d35050ec88a2f695294c9421d6faa5217142410 | 18 | cpp | C++ | Mint/src/mtpch.cpp | orenccl/MintGameEngine | 45f4aa0e926f798448b53680ca5b31a83abf2522 | [
"Apache-2.0"
] | null | null | null | Mint/src/mtpch.cpp | orenccl/MintGameEngine | 45f4aa0e926f798448b53680ca5b31a83abf2522 | [
"Apache-2.0"
] | 3 | 2019-11-04T03:30:11.000Z | 2019-11-04T16:13:46.000Z | Mint/src/mtpch.cpp | orenccl/Mint | 45f4aa0e926f798448b53680ca5b31a83abf2522 | [
"Apache-2.0"
] | null | null | null | #include "mtpch.h" | 18 | 18 | 0.722222 | orenccl |
6d37910e5638aca73e1133de3350b3cc1ee3465f | 432 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/file/format.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/file/format.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/file/format.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace msw {
namespace file {
enum class format
{
bin
, ips
, pcap
, pcapng
};
inline std::string format_to_string(format fmt)
{
if (fmt == format::ips ) return "ips" ;
else if (fmt == format::pcap ) return "pcap" ;
else if (fmt == format::pcapng ) return "pcapng" ;
return "bin";
}
}}
| 16.615385 | 58 | 0.493056 | yklishevich |
6d386bc9b54f55ed9941f19ea5ef9527a88f3764 | 3,593 | cpp | C++ | src/ai/neural/neuralnet.cpp | FuSoftware/QOsuBut | cf89ee66a23efcddf94b6e38b7c708059e026995 | [
"MIT"
] | null | null | null | src/ai/neural/neuralnet.cpp | FuSoftware/QOsuBut | cf89ee66a23efcddf94b6e38b7c708059e026995 | [
"MIT"
] | null | null | null | src/ai/neural/neuralnet.cpp | FuSoftware/QOsuBut | cf89ee66a23efcddf94b6e38b7c708059e026995 | [
"MIT"
] | null | null | null | #include "neuralnet.h"
NeuralNet::NeuralNet(std::vector<int> topology)
{
this->init(topology);
}
void NeuralNet::init(std::vector<int> topology)
{
this->topology = topology;
this->node_count = 0;
this->weight_count = 0;
//Nodes initialization
this->nodes.clear();
this->weights.clear();
this->nodes.resize(topology.size());
this->weights.resize(topology.size()-1);
//Nodes
for(unsigned int x=0;x<topology.size();x++)
{
//If we are on the input or output layer, we keep the same node number. Else, we add a biad node
unsigned int n = (x==0 || x==topology.size()-1) ? topology[x] : topology[x]+1;
this->nodes[x].resize(n);
this->node_count += n;
}
//Weights
for(unsigned int x=0;x<topology.size()-1;x++)
{
unsigned int n = topology[x];
unsigned int nl = x == topology.size()-1 ? topology[x+1] : topology[x+1] -1 ;
this->weights[x].resize(n);
for(unsigned int y=0;y<n;y++)
{
this->weights[x][y].resize(nl);
this->weight_count += nl;
}
}
//Set the bias nodes
for(unsigned int x=1;x<topology.size()-1;x++)
this->nodes[x][topology[x]] = BIAS_VALUE;
this->layer_count = topology.size();
this->output_layer = this->layer_count-1;
//Output count
std::cout << "Network initialized with " << this->node_count << " nodes and " << this->weight_count << " weights";
}
void NeuralNet::setWeights(std::vector<float> weights)
{
int c = 0;
for(unsigned x=0; x<this->weights.size();x++)
{
for(unsigned y=0; y<this->weights[x].size();y++)
{
for(unsigned z=0; z<this->weights[x][y].size();z++)
{
this->weights[x][y][z] = weights[c];
c++;
}
}
}
}
std::vector<float> NeuralNet::getWeights()
{
std::vector<float> w;
for(unsigned x=0; x<this->weights.size();x++)
for(unsigned y=0; y<this->weights[x].size();y++)
for(unsigned z=0; z<this->weights[x][y].size();z++)
w.push_back(this->weights[x][y][z]);
return w;
}
std::vector<float> NeuralNet::process(std::vector<float> inputs)
{
//Set the inputs
for(unsigned i=0; i<inputs.size(); i++)
this->nodes[0][i] = inputs[i];
//Process each layer except the input one
for(unsigned x=1; x<this->layer_count; x++)
{
//Current Layer Count : Number of nodes to calculate on the current layer
unsigned clc = topology[x];
//Current Layer Count : Number of nodes on the previous layer
unsigned plc = x-1 == 0 ? topology[x-1] : topology[x-1] + 1;
//For each node in the current layer
for(unsigned y = 0; y < clc; y++)
{
float sum = 0.f;
//For each node in the previous layer
for(unsigned z = 0; z < plc; z++)
{
sum += nodes[x][z] * weights[x][z][y];
}
this->nodes[x][y] = sigmoid(sum);
}
}
//Get the outputs
return this->getOutputs();
}
float NeuralNet::transferFunction(float x)
{
return sigmoid(x);
}
float NeuralNet::sigmoid(float x)
{
return tanh(x);
}
float NeuralNet::relu(float x)
{
return x <= 0 ? 0 : x;
}
float NeuralNet::transferFunctionh(float x)
{
return sigmoidh(x);
}
float NeuralNet::sigmoidh(float x)
{
return 1.f - x*x;
}
float NeuralNet::reluh(float x)
{
return x <= 0 ? 0 : 1;
}
std::vector<float> NeuralNet::getOutputs()
{
return this->nodes.back();
}
| 23.331169 | 118 | 0.555525 | FuSoftware |
6d3e3e04457f3ddd0f7978af9ad850f68fb8c470 | 3,243 | cc | C++ | t/logical_expressions_simple/src/generator/rule/terminal_rule.cc | coppit/yagg | 8fd076d817f28ed6739e6ba0cd246e37e96fc00c | [
"FSFAP"
] | 4 | 2016-07-22T03:28:21.000Z | 2020-08-20T23:38:36.000Z | t/logical_expressions_simple/src/generator/rule/terminal_rule.cc | coppit/yagg | 8fd076d817f28ed6739e6ba0cd246e37e96fc00c | [
"FSFAP"
] | null | null | null | t/logical_expressions_simple/src/generator/rule/terminal_rule.cc | coppit/yagg | 8fd076d817f28ed6739e6ba0cd246e37e96fc00c | [
"FSFAP"
] | null | null | null | #include "generator/rule/terminal_rule.h"
#include <cassert>
#ifdef SHORT_RULE_TRACE
#include <iostream>
#include "generator/utility/utility.h"
using namespace Utility;
#endif // SHORT_RULE_TRACE
using namespace std;
Terminal_Rule::Terminal_Rule()
{
m_string_count = 0;
m_terminals.push_back(this);
}
// ---------------------------------------------------------------------------
Terminal_Rule::~Terminal_Rule()
{
}
// ---------------------------------------------------------------------------
void Terminal_Rule::Initialize(const unsigned int in_allowed_length, const Rule *in_previous_rule)
{
Rule::Initialize(in_allowed_length,in_previous_rule);
}
// ---------------------------------------------------------------------------
void Terminal_Rule::Reset_String()
{
Rule::Reset_String();
#ifdef SHORT_RULE_TRACE
cerr << "RESET: " << Utility::indent <<
"Terminal: " << Utility::readable_type_name(typeid(*this)) <<
"(" << m_allowed_length << ")" << endl;
Utility::Indent();
#endif // SHORT_RULE_TRACE
m_string_count = 0;
if (m_allowed_length != 1)
{
#ifdef SHORT_RULE_TRACE
cerr << "RESET: " << Utility::indent <<
"Terminal: " << Utility::readable_type_name(typeid(*this)) <<
" -> NOT VALID" << endl;
Utility::Unindent();
#endif // SHORT_RULE_TRACE
Invalidate();
return;
}
#ifdef SHORT_RULE_TRACE
cerr << "RESET: " << Utility::indent <<
"Terminal: " << Utility::readable_type_name(typeid(*this)) <<
" -> VALID" << endl;
Utility::Unindent();
#endif // SHORT_RULE_TRACE
}
// ---------------------------------------------------------------------------
const bool Terminal_Rule::Check_For_String()
{
#ifdef SHORT_RULE_TRACE
cerr << "CHECK: " << Utility::indent << "Terminal: " <<
Utility::readable_type_name(typeid(*this)) << "(" << m_allowed_length << ")";
list<const Rule*> previous_rules;
for (const Rule* a_rule = m_previous_rule;
a_rule != NULL;
a_rule = a_rule->Get_Previous_Rule())
previous_rules.push_front(a_rule);
cerr << " (Prefix rules: " << previous_rules << ")" << endl;
Utility::Indent();
#endif // SHORT_RULE_TRACE
if (!Rule::Check_For_String())
{
#ifdef SHORT_RULE_TRACE
cerr << "CHECK: " << Utility::indent <<
"Terminal: " << Utility::readable_type_name(typeid(*this)) <<
" -> NOT VALID" << endl;
Utility::Unindent();
#endif // SHORT_RULE_TRACE
return false;
}
m_string_count++;
// Default implementation assumes 1 string per terminal
if (m_string_count > 1)
{
#ifdef SHORT_RULE_TRACE
cerr << "CHECK: " << Utility::indent <<
"Terminal: " << Utility::readable_type_name(typeid(*this)) <<
" -> NOT VALID" << endl;
Utility::Unindent();
#endif // SHORT_RULE_TRACE
return false;
}
else
{
#ifdef SHORT_RULE_TRACE
cerr << "CHECK: " << Utility::indent <<
"Terminal: " << Utility::readable_type_name(typeid(*this)) <<
" -> VALID" << endl;
Utility::Unindent();
#endif // SHORT_RULE_TRACE
return true;
}
}
// ---------------------------------------------------------------------------
const Rule* Terminal_Rule::operator[](const unsigned int in_index) const
{
assert (in_index == 0);
return this;
}
| 23.671533 | 98 | 0.570768 | coppit |
6d3f81dc443d1f2457db3666892bdd24743d246f | 8,313 | hpp | C++ | libs/dmlf/include/dmlf/colearn/muddle_learner_networker_impl.hpp | vhavrylov-ncube/ledger | 1e216c304aea344e8ef88e1954658ff665f4f4ac | [
"Apache-2.0"
] | 1 | 2019-09-30T12:22:46.000Z | 2019-09-30T12:22:46.000Z | libs/dmlf/include/dmlf/colearn/muddle_learner_networker_impl.hpp | EVSmithFetchAI/ledger | c1f904a23a8c431a86b6610bb528f38f2e2c3ad5 | [
"Apache-2.0"
] | null | null | null | libs/dmlf/include/dmlf/colearn/muddle_learner_networker_impl.hpp | EVSmithFetchAI/ledger | c1f904a23a8c431a86b6610bb528f38f2e2c3ad5 | [
"Apache-2.0"
] | 1 | 2021-05-04T11:37:20.000Z | 2021-05-04T11:37:20.000Z | #pragma once
//------------------------------------------------------------------------------
//
// 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 "core/service_ids.hpp"
#include "crypto/ecdsa.hpp"
#include "dmlf/colearn/abstract_message_controller.hpp"
#include "dmlf/colearn/colearn_protocol.hpp"
#include "dmlf/colearn/random_double.hpp"
#include "dmlf/colearn/update_store.hpp"
#include "dmlf/deprecated/abstract_learner_networker.hpp"
#include "dmlf/deprecated/update_interface.hpp"
#include "json/document.hpp"
#include "logging/logging.hpp"
#include "muddle/muddle_interface.hpp"
#include "muddle/rpc/client.hpp"
#include "muddle/rpc/server.hpp"
#include "network/service/call_context.hpp"
#include "oef-base/threading/Taskpool.hpp"
#include "oef-base/threading/Threadpool.hpp"
namespace fetch {
namespace dmlf {
namespace colearn {
class MuddleLearnerNetworkerImpl : public AbstractMessageController
{
public:
using Taskpool = oef::base::Taskpool;
using Address = fetch::muddle::Address;
using AlgorithmClass = AbstractMessageController::AlgorithmClass;
using Bytes = ColearnUpdate::Data;
using ConstUpdatePtr = AbstractMessageController::ConstUpdatePtr;
using Criteria = UpdateStoreInterface::Criteria;
using Lock = std::unique_lock<Mutex>;
using MuddlePtr = muddle::MuddlePtr;
using NetMan = fetch::network::NetworkManager;
using NetManPtr = std::shared_ptr<NetMan>;
using Payload = fetch::muddle::Packet::Payload;
using Peers = std::unordered_set<Address>;
using Proto = ColearnProtocol;
using ProtoPtr = std::shared_ptr<ColearnProtocol>;
using Randomiser = RandomDouble;
using RpcClient = fetch::muddle::rpc::Client;
using RpcClientPtr = std::shared_ptr<RpcClient>;
using RpcServer = fetch::muddle::rpc::Server;
using RpcServerPtr = std::shared_ptr<RpcServer>;
using Signer = fetch::crypto::ECDSASigner;
using SignerPtr = std::shared_ptr<Signer>;
using Sources = std::set<std::string>;
using SourcesList = std::vector<std::string>;
using Store = UpdateStore;
using StorePtr = std::shared_ptr<Store>;
using SubscriptionPtr = fetch::muddle::MuddleEndpoint::SubscriptionPtr;
using TaskPtr = Taskpool::TaskP;
using Threadpool = oef::base::Threadpool;
using UpdateClass = AbstractMessageController::UpdateClass;
using UpdatePtr = AbstractMessageController::UpdatePtr;
using UpdateType = UpdateStore::UpdateType;
using Uri = fetch::network::Uri;
using deprecated_UpdateInterfacePtr = dmlf::deprecated_UpdateInterfacePtr;
static constexpr char const *LOGGING_NAME = "MuddleLearnerNetworkerImpl";
explicit MuddleLearnerNetworkerImpl(const std::string &priv, unsigned short int port,
const std::string &remote = "");
explicit MuddleLearnerNetworkerImpl(MuddlePtr mud, StorePtr update_store);
explicit MuddleLearnerNetworkerImpl(fetch::json::JSONDocument &cloud_config,
std::size_t instance_number);
~MuddleLearnerNetworkerImpl() override;
MuddleLearnerNetworkerImpl(MuddleLearnerNetworkerImpl const &other) = delete;
MuddleLearnerNetworkerImpl &operator=(MuddleLearnerNetworkerImpl const &other) = delete;
bool operator==(MuddleLearnerNetworkerImpl const &other) = delete;
bool operator<(MuddleLearnerNetworkerImpl const &other) = delete;
void PushUpdate(UpdatePtr const &update, AlgorithmClass const &algorithm,
UpdateClass const &upd_class) override
{
PushUpdate(update->data(), algorithm, upd_class);
}
void PushUpdate(Bytes const & update, AlgorithmClass const & /*algorithm*/,
UpdateClass const &upd_class) override
{
PushUpdateBytes(upd_class, update);
}
std::size_t GetUpdateCount(AlgorithmClass const &algo = "algo0",
UpdateClass const & type = "gradients") const override
{
FETCH_UNUSED(algo);
FETCH_UNUSED(type);
return GetUpdateTotalCount();
}
std::size_t GetUpdateTotalCount() const override
{
return update_store_->GetUpdateCount();
}
ConstUpdatePtr GetUpdate(AlgorithmClass const &algo = "algo0",
UpdateType const & type = "gradients") override
{
return update_store_->GetUpdate(algo, type);
}
void PushUpdateBytes(UpdateType const &type_name, Bytes const &update);
void PushUpdateBytes(UpdateType const &type_name, Bytes const &update, Peers const &peers);
void PushUpdateBytes(UpdateType const &type_name, Bytes const &update, Peers const &peers,
double broadcast_proportion);
ConstUpdatePtr GetUpdate(AlgorithmClass const &algo, UpdateType const &type,
Criteria const &criteria);
virtual void submit(TaskPtr const &t);
// This is the exposed interface
uint64_t NetworkColearnUpdate(service::CallContext const &context, const std::string &type_name,
byte_array::ConstByteArray bytes, double proportion = 1.0,
double random_factor = 0.0);
Randomiser &access_randomiser()
{
return randomiser_;
}
void set_broadcast_proportion(double proportion)
{
broadcast_proportion_ = std::max(0.0, std::min(1.0, proportion));
}
Address GetAddress() const;
std::string GetAddressAsString() const;
void SetShuffleAlgorithm(const std::shared_ptr<ShuffleAlgorithmInterface> &alg);
std::size_t GetPeerCount() const
{
return supplied_peers_.size();
}
void AddPeers(const std::vector<std::string> &new_peers)
{
for (auto const &peer : new_peers)
{
supplied_peers_.emplace_back(peer);
}
}
void ClearPeers()
{
supplied_peers_.clear();
}
protected:
friend class MuddleOutboundAnnounceTask;
void Setup(MuddlePtr mud, StorePtr update_store);
uint64_t ProcessUpdate(const std::string &type_name, byte_array::ConstByteArray bytes,
double proportion, double random_factor, const std::string &source);
void Setup(std::string const &priv, unsigned short int port,
std::unordered_set<std::string> const &remotes);
private:
std::shared_ptr<Taskpool> taskpool_;
std::shared_ptr<Threadpool> tasks_runners_;
MuddlePtr mud_;
RpcClientPtr client_;
RpcServerPtr server_;
ProtoPtr proto_;
StorePtr update_store_;
Randomiser randomiser_;
double broadcast_proportion_;
double randomising_offset_;
SubscriptionPtr subscription_;
byte_array::ConstByteArray public_key_;
NetManPtr netm_;
Sources detected_peers_;
SourcesList supplied_peers_;
const unsigned int INITIAL_PEERS_COUNT = 10;
mutable Mutex mutex_;
std::shared_ptr<ShuffleAlgorithmInterface> alg_;
friend class MuddleMessageHandler;
};
} // namespace colearn
} // namespace dmlf
} // namespace fetch
| 39.028169 | 98 | 0.63527 | vhavrylov-ncube |
6d417c215f5630de542e49b9711d5fc258e0b32a | 197 | hpp | C++ | objdatatypes.hpp | phkeese/objimport | 59fc3bb8287874b8b93d6c5ffc123f5fb10e8aa3 | [
"MIT"
] | null | null | null | objdatatypes.hpp | phkeese/objimport | 59fc3bb8287874b8b93d6c5ffc123f5fb10e8aa3 | [
"MIT"
] | null | null | null | objdatatypes.hpp | phkeese/objimport | 59fc3bb8287874b8b93d6c5ffc123f5fb10e8aa3 | [
"MIT"
] | null | null | null | #pragma once
/**
* Datatype Definitions used by both the OBJ and MTL format
*/
namespace objimport {
struct Vector3 {
float x, y, z;
};
using index = unsigned int;
} // namespace objimport
| 12.3125 | 59 | 0.685279 | phkeese |
6d41a50b4965d9d935aa6fa841c656c9265d61ec | 2,016 | cpp | C++ | sources/modules/helperOC/ValFuncs/rotateData.cpp | mdoshi96/beacls | 860426ed1336d9539dea195987efcdd8a8276a1c | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 30 | 2017-12-17T22:57:50.000Z | 2022-01-30T17:06:34.000Z | sources/modules/helperOC/ValFuncs/rotateData.cpp | codingblazes/beacls | 6c1d685ee00e3b39d8100c4a170a850682679abc | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 2 | 2017-03-24T06:18:16.000Z | 2017-04-04T16:16:06.000Z | sources/modules/helperOC/ValFuncs/rotateData.cpp | codingblazes/beacls | 6c1d685ee00e3b39d8100c4a170a850682679abc | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 8 | 2018-07-06T01:47:21.000Z | 2021-07-23T15:50:34.000Z | #include <helperOC/helperOC_type.hpp>
#include <helperOC/ValFuncs/rotateData.hpp>
#include <helperOC/ValFuncs/eval_u.hpp>
#include <levelset/Grids/HJI_Grid.hpp>
#include <vector>
#include <iostream>
#include <algorithm>
bool helperOC::rotateData(
beacls::FloatVec& dataOut,
const levelset::HJI_Grid* g,
const beacls::FloatVec& dataIn,
const FLOAT_TYPE theta,
const beacls::IntegerVec& pdims,
const beacls::IntegerVec& adims,
const beacls::Interpolate_Type interp_method
)
{
const beacls::FloatVec& xs_pdims0 = g->get_xs(pdims[0]);
const beacls::FloatVec& xs_pdims1 = g->get_xs(pdims[1]);
std::vector<beacls::FloatVec> rxss(xs_pdims0.size());
rxss[pdims[0]].resize(xs_pdims0.size());
rxss[pdims[1]].resize(xs_pdims1.size());
//!< Get a list of new indices
//!< Multiply by rotation matrix for position dimensions
std::transform(xs_pdims0.cbegin(), xs_pdims0.cend(), xs_pdims1.cbegin(), rxss.begin(), [theta, pdims, adims](const auto& lhs, const auto& rhs) {
beacls::FloatVec res(2+adims.size());
res[pdims[0]] = std::cos(-theta) * lhs - sin(-theta) * rhs;
res[pdims[1]] = std::sin(-theta) * lhs + cos(-theta) * rhs;
return res;
});
//!< Translate in angle
if (!adims.empty()) {
std::for_each(adims.cbegin(), adims.cend(), [theta, &rxss, g](const auto& rhs) {
const size_t adim = rhs;
const beacls::FloatVec& xs_adim = g->get_xs(rhs);
std::transform(xs_adim.cbegin(), xs_adim.cend(), rxss.begin(), rxss.begin(), [theta, adim](const auto& lhs, auto& rhs) {
rhs[adim] = lhs - theta;
return rhs;
});
});
}
//!< Interpolate dataIn to get approximation of rotated data
helperOC::eval_u(dataOut, g, dataIn, rxss, interp_method);
FLOAT_TYPE max_val = dataOut[0];
std::for_each(dataOut.cbegin()+1, dataOut.cend(), [&max_val](const auto& rhs) {
if ((max_val < rhs) || std::isnan(max_val)) max_val = rhs;
});
std::transform(dataOut.cbegin(), dataOut.cend(), dataOut.begin(), [max_val](const auto& rhs) { return (std::isnan(rhs)) ? max_val : rhs; });
return true;
}
| 38.037736 | 145 | 0.686012 | mdoshi96 |
6d43b6f2613163a2bf25f0bbff73584fcfd6f96c | 88,441 | cpp | C++ | src/core/tools/vargen/utils/assembler.cpp | Schaudge/octopus | d0cc5d0840aefdfefae5af8595e3330620106054 | [
"MIT"
] | 278 | 2016-10-03T16:30:49.000Z | 2022-03-25T05:59:32.000Z | src/core/tools/vargen/utils/assembler.cpp | Schaudge/octopus | d0cc5d0840aefdfefae5af8595e3330620106054 | [
"MIT"
] | 229 | 2016-10-13T14:07:35.000Z | 2022-03-19T18:59:58.000Z | src/core/tools/vargen/utils/assembler.cpp | Schaudge/octopus | d0cc5d0840aefdfefae5af8595e3330620106054 | [
"MIT"
] | 37 | 2016-10-28T22:47:54.000Z | 2022-03-20T07:28:43.000Z | // Copyright (c) 2015-2021 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#include "assembler.hpp"
#include <iterator>
#include <algorithm>
#include <array>
#include <cmath>
#include <numeric>
#include <limits>
#include <cassert>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/dag_shortest_paths.hpp>
#include <boost/graph/dominator_tree.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/exception.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/copy.hpp>
#include "ksp/yen_ksp.hpp"
#include "utils/sequence_utils.hpp"
#include "utils/append.hpp"
#include "utils/maths.hpp"
#define _unused(x) ((void)(x))
namespace octopus { namespace coretools {
namespace {
template <typename I>
auto sequence_length(const I num_kmers, const unsigned kmer_size) noexcept
{
return num_kmers > 0 ? num_kmers + kmer_size - 1 : 0;
}
template <typename T>
std::size_t count_kmers(const T& sequence, const unsigned kmer_size) noexcept
{
return sequence.size() >= kmer_size ? sequence.size() - kmer_size + 1 : 0;
}
} // namespace
// public methods
Assembler::NonCanonicalReferenceSequence::NonCanonicalReferenceSequence(NucleotideSequence reference_sequence)
: std::invalid_argument {"bad reference sequence"}
, reference_sequence_ {std::move(reference_sequence)}
{}
const char* Assembler::NonCanonicalReferenceSequence::what() const noexcept
{
return std::invalid_argument::what();
}
Assembler::Assembler(const Parameters params)
: params_ {params}
, reference_kmers_ {}
, reference_head_position_ {0}
, reference_vertices_ {}
{}
Assembler::Assembler(const Parameters params, const NucleotideSequence& reference)
: params_ {params}
, reference_kmers_ {}
, reference_head_position_ {0}
, reference_vertices_ {}
{
insert_reference_into_empty_graph(reference);
}
Assembler::Assembler(const Assembler& other)
: params_ {other.params_}
, reference_kmers_ {other.reference_kmers_}
, reference_head_position_ {other.reference_head_position_}
{
std::unordered_map<Vertex, std::size_t> index_map {};
index_map.reserve(boost::num_vertices(other.graph_));
const auto p = boost::vertices(other.graph_);
std::size_t i {0};
std::for_each(p.first, p.second, [&i, &index_map] (const Vertex& v) { index_map.emplace(v, i++); });
std::unordered_map<Vertex, Vertex> vertex_copy_map {};
vertex_copy_map.reserve(boost::num_vertices(other.graph_));
boost::copy_graph(other.graph_, this->graph_,
boost::vertex_index_map(boost::make_assoc_property_map(index_map))
.orig_to_copy(boost::make_assoc_property_map(vertex_copy_map)));
vertex_cache_ = other.vertex_cache_;
for (auto& p : vertex_cache_) {
p.second = vertex_copy_map.at(p.second);
}
reference_vertices_ = other.reference_vertices_;
for (auto& v : reference_vertices_) {
v = vertex_copy_map.at(v);
}
for (const auto& other_edge : other.reference_edges_) {
Edge e; bool e_in_graph;
const auto u = vertex_copy_map.at(boost::source(other_edge, other.graph_));
const auto v = vertex_copy_map.at(boost::target(other_edge, other.graph_));
std::tie(e, e_in_graph) = boost::edge(u, v, graph_);
assert(e_in_graph);
reference_edges_.push_back(e);
}
}
unsigned Assembler::kmer_size() const noexcept
{
return params_.kmer_size;
}
Assembler::Parameters Assembler::params() const
{
return params_;
}
void Assembler::insert_reference(const NucleotideSequence& sequence)
{
if (sequence.size() >= kmer_size()) {
if (is_empty()) {
insert_reference_into_empty_graph(sequence);
} else if (reference_kmers_.empty()) {
insert_reference_into_populated_graph(sequence);
} else {
throw std::runtime_error {"Assembler: only one reference sequence can be inserted into the graph"};
}
} else {
throw std::runtime_error {"Assembler:: reference length must >= kmer_size"};
}
}
void Assembler::insert_read(const NucleotideSequence& sequence,
const BaseQualityVector& base_qualities,
const Direction strand,
const SampleID sample)
{
if (sequence.size() >= kmer_size()) {
const bool is_forward_strand {strand == Direction::forward};
auto kmer_begin = std::cbegin(sequence);
auto kmer_end = std::next(kmer_begin, kmer_size());
auto base_quality_itr = std::next(std::cbegin(base_qualities), kmer_size());
Kmer prev_kmer {kmer_begin, kmer_end};
bool prev_kmer_good {true};
auto vertex_itr = vertex_cache_.find(prev_kmer);
auto ref_kmer_itr = std::cbegin(reference_kmers_);
if (vertex_itr == std::cend(vertex_cache_)) {
const auto u = add_vertex(prev_kmer);
if (!u) prev_kmer_good = false;
} else if (is_reference(vertex_itr->second)) {
ref_kmer_itr = std::find(std::cbegin(reference_kmers_), std::cend(reference_kmers_), prev_kmer);
assert(ref_kmer_itr != std::cend(reference_kmers_));
auto next_kmer_begin = std::next(kmer_begin);
auto next_kmer_end = std::next(kmer_end);
const auto ref_offset = std::distance(std::cbegin(reference_kmers_), ref_kmer_itr);
auto ref_vertex_itr = std::next(std::cbegin(reference_vertices_), ref_offset);
auto ref_edge_itr = std::next(std::cbegin(reference_edges_), ref_offset);
++ref_kmer_itr;
for (; next_kmer_end <= std::cend(sequence) && ref_kmer_itr < std::cend(reference_kmers_);
++next_kmer_begin, ++next_kmer_end, ++ref_kmer_itr, ++ref_vertex_itr, ++ref_edge_itr, ++base_quality_itr) {
if (std::equal(next_kmer_begin, next_kmer_end, std::cbegin(*ref_kmer_itr))) {
assert(ref_edge_itr != std::cend(reference_edges_));
increment_weight(*ref_edge_itr, is_forward_strand, *base_quality_itr, sample);
} else {
break;
}
}
if (next_kmer_end > std::cend(sequence)) {
return;
}
kmer_begin = std::prev(next_kmer_begin);
kmer_end = std::prev(next_kmer_end);
assert(kmer_end <= std::cend(sequence));
prev_kmer = Kmer {kmer_begin, kmer_end};
}
++kmer_begin;
++kmer_end;
for (; kmer_end <= std::cend(sequence); ++kmer_begin, ++kmer_end, ++base_quality_itr) {
Kmer kmer {kmer_begin, kmer_end};
const auto kmer_itr = vertex_cache_.find(kmer);
if (kmer_itr == std::cend(vertex_cache_)) {
const auto v = add_vertex(kmer);
if (v) {
if (prev_kmer_good) {
assert(vertex_cache_.count(prev_kmer) == 1);
const auto u = vertex_cache_.at(prev_kmer);
add_edge(u, *v, 1, is_forward_strand, *base_quality_itr, false, sample);
}
prev_kmer_good = true;
} else {
prev_kmer_good = false;
}
} else {
if (prev_kmer_good) {
const auto u = vertex_cache_.at(prev_kmer);
const auto v = kmer_itr->second;
Edge e; bool e_in_graph;
std::tie(e, e_in_graph) = boost::edge(u, v, graph_);
if (e_in_graph) {
increment_weight(e, is_forward_strand, *base_quality_itr, sample);
} else {
add_edge(u, v, 1, is_forward_strand, *base_quality_itr, false, sample);
}
}
if (is_reference(kmer_itr->second)) {
ref_kmer_itr = std::find(ref_kmer_itr, std::cend(reference_kmers_), kmer);
if (ref_kmer_itr != std::cend(reference_kmers_)) {
auto next_kmer_begin = std::next(kmer_begin);
auto next_kmer_end = std::next(kmer_end);
const auto ref_offset = std::distance(std::cbegin(reference_kmers_), ref_kmer_itr);
auto ref_vertex_itr = std::next(std::cbegin(reference_vertices_), ref_offset);
auto ref_edge_itr = std::next(std::cbegin(reference_edges_), ref_offset);
++ref_kmer_itr;
for (; next_kmer_end <= std::cend(sequence) && ref_kmer_itr < std::cend(reference_kmers_);
++next_kmer_begin, ++next_kmer_end, ++ref_kmer_itr, ++ref_vertex_itr, ++ref_edge_itr) {
if (std::equal(next_kmer_begin, next_kmer_end, std::cbegin(*ref_kmer_itr))) {
assert(ref_edge_itr != std::cend(reference_edges_));
increment_weight(*ref_edge_itr, is_forward_strand, *base_quality_itr, sample);
} else {
break;
}
}
if (next_kmer_end > std::cend(sequence)) {
return;
}
kmer_begin = std::prev(next_kmer_begin);
kmer_end = std::prev(next_kmer_end);
assert(kmer_end <= std::cend(sequence));
kmer = Kmer {kmer_begin, kmer_end};
}
}
prev_kmer_good = true;
}
prev_kmer = kmer;
}
}
}
std::size_t Assembler::num_kmers() const noexcept
{
return vertex_cache_.size();
}
bool Assembler::is_empty() const noexcept
{
return vertex_cache_.empty();
}
bool Assembler::is_acyclic() const
{
return !(graph_has_trivial_cycle() || graph_has_nontrivial_cycle());
}
void Assembler::remove_nonreference_cycles(bool break_chains)
{
remove_all_nonreference_cycles(break_chains);
}
namespace {
struct CycleDetector : public boost::default_dfs_visitor
{
struct CycleDetectedException {};
explicit CycleDetector(bool allow_self_edges = true) : allow_self_edges_ {allow_self_edges} {}
template <typename Graph>
void back_edge(typename boost::graph_traits<Graph>::edge_descriptor e, const Graph& g)
{
if (boost::source(e, g) != boost::target(e, g) || !allow_self_edges_) {
throw CycleDetectedException {};
}
}
protected:
const bool allow_self_edges_;
};
template <typename Container>
struct CyclicEdgeDetector : public boost::default_dfs_visitor
{
CyclicEdgeDetector(Container& result, bool include_self_edges = true)
: include_self_edges_ {include_self_edges}, result_ {result} {}
template <typename Graph>
void back_edge(typename boost::graph_traits<Graph>::edge_descriptor e, const Graph& g)
{
if (boost::source(e, g) != boost::target(e, g) || include_self_edges_) {
result_.push_back(e);
}
}
protected:
const bool include_self_edges_;
Container& result_;
};
} // namespace
std::vector<Assembler::SampleID> Assembler::find_cyclic_samples(const unsigned min_weight) const
{
const auto index_map = boost::get(&GraphNode::index, graph_);
std::deque<Edge> cyclic_edges {};
CyclicEdgeDetector<decltype(cyclic_edges)> vis {cyclic_edges};
boost::depth_first_search(graph_, boost::visitor(vis).root_vertex(reference_head()).vertex_index_map(index_map));
std::set<SampleID> cyclic_samples {};
for (const Edge& e : cyclic_edges) {
if (!is_reference(e)) {
for (const auto& p : graph_[e].samples) {
if (p.second.weight >= min_weight) {
cyclic_samples.insert(p.first);
}
}
}
}
return {std::begin(cyclic_samples), std::end(cyclic_samples)};
}
bool Assembler::is_all_reference() const
{
const auto p = boost::edges(graph_);
return std::all_of(p.first, p.second, [this] (const Edge& e) { return is_reference(e); });
}
bool Assembler::is_unique_reference() const
{
return is_reference_unique_path();
}
void Assembler::try_recover_dangling_branches()
{
const auto p = boost::vertices(graph_);
std::for_each(p.first, p.second, [this] (const Vertex& v) {
if (is_dangling_branch(v)) {
const auto joining_kmer = find_joining_kmer(v);
if (joining_kmer) {
add_edge(v, *joining_kmer, 1, 0, false);
}
}
});
}
void Assembler::prune(const unsigned min_weight)
{
remove_low_weight_edges(min_weight);
}
void Assembler::cleanup()
{
if (!is_reference_unique_path()) {
throw NonUniqueReferenceSequence {};
}
auto old_size = boost::num_vertices(graph_);
if (old_size < 2) return;
assert(is_reference_unique_path());
remove_disconnected_vertices();
auto new_size = boost::num_vertices(graph_);
if (new_size != old_size) {
regenerate_vertex_indices();
if (new_size < 2) return;
old_size = new_size;
}
assert(is_reference_unique_path());
remove_vertices_that_cant_be_reached_from(reference_head());
new_size = boost::num_vertices(graph_);
if (new_size != old_size) {
regenerate_vertex_indices();
if (new_size < 2) return;
old_size = new_size;
}
assert(is_reference_unique_path());
remove_vertices_past(reference_tail());
new_size = boost::num_vertices(graph_);
if (new_size != old_size) {
regenerate_vertex_indices();
if (new_size < 2) return;
old_size = new_size;
}
assert(is_reference_unique_path());
remove_vertices_that_cant_reach(reference_tail());
new_size = boost::num_vertices(graph_);
if (new_size != old_size) {
regenerate_vertex_indices();
if (new_size < 2) return;
old_size = new_size;
}
assert(is_reference_unique_path());
prune_reference_flanks();
assert(is_reference_unique_path());
if (is_reference_empty()) {
clear();
return;
}
new_size = boost::num_vertices(graph_);
assert(new_size != 0);
assert(!(boost::num_edges(graph_) == 0 && new_size > 1));
assert(is_reference_unique_path());
if (new_size != old_size) {
regenerate_vertex_indices();
}
}
void Assembler::clear(const std::vector<SampleID>& samples)
{
const auto can_remove_edge = [&] (const Edge& e) {
if (is_reference(e)) return false;
if (is_artificial(e)) return false;
if (graph_[e].samples.size() > samples.size()) return false;
const auto includes_sample = [&] (const auto& p) {
return std::find(std::cbegin(samples), std::cend(samples), p.first) != std::cend(samples);
};
return std::all_of(std::cbegin(graph_[e].samples), std::cend(graph_[e].samples), includes_sample);
};
boost::remove_edge_if(can_remove_edge, graph_);
const auto p = boost::edges(graph_);
std::for_each(p.first, p.second, [&] (const Edge& e) {
auto& edge = graph_[e];
for (const auto& sample : samples) {
const auto sample_itr = edge.samples.find(sample);
if (sample_itr != std::cend(edge.samples)) {
edge.weight -= sample_itr->second.weight;
edge.forward_strand_weight -= sample_itr->second.forward_strand_weight;
edge.base_quality_sum -= sample_itr->second.base_quality_sum;
edge.samples.erase(sample_itr);
}
}
});
}
void Assembler::clear()
{
graph_.clear();
vertex_cache_.clear();
reference_kmers_.clear();
reference_kmers_.shrink_to_fit();
reference_vertices_.clear();
reference_vertices_.shrink_to_fit();
reference_edges_.clear();
reference_edges_.shrink_to_fit();
}
bool operator<(const Assembler::Variant& lhs, const Assembler::Variant& rhs) noexcept
{
if (lhs.begin_pos == rhs.begin_pos) {
if (lhs.ref.size() == rhs.ref.size()) {
return lhs.alt < rhs.alt;
}
return lhs.ref.size() < rhs.ref.size();
}
return lhs.begin_pos < rhs.begin_pos;
}
std::deque<Assembler::Variant>
Assembler::extract_variants(const unsigned max_bubbles, const BubbleScoreSetter min_bubble_scorer)
{
if (is_empty() || is_all_reference()) return {};
set_all_edge_transition_scores_from(reference_head());
auto result = extract_bubble_paths(max_bubbles, min_bubble_scorer);
std::sort(std::begin(result), std::end(result));
result.erase(std::unique(std::begin(result), std::end(result)), std::end(result));
return result;
}
void Assembler::write_dot(std::ostream& out) const
{
const auto vertex_writer = [this] (std::ostream& out, Vertex v) {
if (is_reference(v)) {
out << " [shape=box,color=blue]" << std::endl;
} else {
out << " [shape=box,color=red]" << std::endl;
}
out << " [label=\"" << kmer_of(v) << "\"]" << std::endl;
};
const auto edge_writer = [this] (std::ostream& out, Edge e) {
if (is_reference(e)) {
out << " [color=blue]" << std::endl;
} else if (is_artificial(e)) {
out << " [style=dotted,color=grey]" << std::endl;
} else {
out << " [color=red]" << std::endl;
}
out << " [label=\"" << graph_[e].weight << "\"]" << std::endl;
};
const auto graph_writer = [] (std::ostream& out) {
out << "rankdir=LR" << std::endl;
};
boost::write_graphviz(out, graph_, vertex_writer, edge_writer, graph_writer);
}
// Kmer
Assembler::Kmer::Kmer(SequenceIterator first, SequenceIterator last) noexcept
: first_ {first}
, last_ {last}
, hash_ {boost::hash_range(first_, last_)}
{}
char Assembler::Kmer::front() const noexcept
{
return *first_;
}
char Assembler::Kmer::back() const noexcept
{
return *std::prev(last_);
}
Assembler::Kmer::SequenceIterator Assembler::Kmer::begin() const noexcept
{
return first_;
}
Assembler::Kmer::SequenceIterator Assembler::Kmer::end() const noexcept
{
return last_;
}
Assembler::Kmer::operator NucleotideSequence() const
{
return NucleotideSequence {first_, last_};
}
std::size_t Assembler::Kmer::hash() const noexcept
{
return hash_;
}
bool operator==(const Assembler::Kmer& lhs, const Assembler::Kmer& rhs) noexcept
{
return std::equal(lhs.first_, lhs.last_, rhs.first_);
}
bool operator<(const Assembler::Kmer& lhs, const Assembler::Kmer& rhs) noexcept
{
return std::lexicographical_compare(lhs.first_, lhs.last_, rhs.first_, rhs.last_);
}
//
// Assembler private methods
//
void Assembler::insert_reference_into_empty_graph(const NucleotideSequence& sequence)
{
assert(sequence.size() >= kmer_size());
vertex_cache_.reserve(sequence.size() + std::pow(4, 5));
auto kmer_begin = std::cbegin(sequence);
auto kmer_end = std::next(kmer_begin, kmer_size());
reference_kmers_.emplace_back(kmer_begin, kmer_end);
if (!contains_kmer(reference_kmers_.back())) {
const auto u = add_vertex(reference_kmers_.back(), true);
if (!u) {
throw NonCanonicalReferenceSequence {sequence};
}
reference_vertices_.push_back(*u);
} else {
reference_vertices_.push_back(vertex_cache_.at(reference_kmers_.back()));
}
++kmer_begin;
++kmer_end;
for (; kmer_end <= std::cend(sequence); ++kmer_begin, ++kmer_end) {
reference_kmers_.emplace_back(kmer_begin, kmer_end);
const auto& kmer = reference_kmers_.back();
if (!contains_kmer(kmer)) {
const auto v = add_vertex(kmer, true);
if (v) {
reference_vertices_.push_back(*v);
const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);
const auto e = add_reference_edge(u, *v);
reference_edges_.push_back(e);
} else {
throw NonCanonicalReferenceSequence {sequence};
}
} else {
const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);
const auto v = vertex_cache_.at(kmer);
reference_vertices_.push_back(v);
const auto e = add_reference_edge(u, v);
reference_edges_.push_back(e);
}
}
assert(reference_vertices_.size() == reference_kmers_.size());
assert(reference_edges_.size() == reference_vertices_.size() - 1);
reference_kmers_.shrink_to_fit();
reference_vertices_.shrink_to_fit();
reference_edges_.shrink_to_fit();
}
void Assembler::insert_reference_into_populated_graph(const NucleotideSequence& sequence)
{
assert(sequence.size() >= kmer_size());
assert(reference_kmers_.empty());
vertex_cache_.reserve(vertex_cache_.size() + sequence.size() + std::pow(4, 5));
auto kmer_begin = std::cbegin(sequence);
auto kmer_end = std::next(kmer_begin, kmer_size());
reference_kmers_.emplace_back(kmer_begin, kmer_end);
if (!contains_kmer(reference_kmers_.back())) {
const auto u = add_vertex(reference_kmers_.back(), true);
if (!u) {
throw NonCanonicalReferenceSequence {sequence};
}
reference_vertices_.push_back(*u);
} else {
set_vertex_reference(reference_kmers_.back());
reference_vertices_.push_back(vertex_cache_.at(reference_kmers_.back()));
}
++kmer_begin;
++kmer_end;
for (; kmer_end <= std::cend(sequence); ++kmer_begin, ++kmer_end) {
reference_kmers_.emplace_back(kmer_begin, kmer_end);
if (!contains_kmer(reference_kmers_.back())) {
const auto v = add_vertex(reference_kmers_.back(), true);
if (v) {
reference_vertices_.push_back(*v);
const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);
const auto e = add_reference_edge(u, *v);
reference_edges_.push_back(e);
} else {
throw NonCanonicalReferenceSequence {sequence};
}
} else {
const auto u = vertex_cache_.at(std::crbegin(reference_kmers_)[1]);
const auto v = vertex_cache_.at(reference_kmers_.back());
reference_vertices_.push_back(v);
set_vertex_reference(v);
Edge e; bool e_in_graph;
std::tie(e, e_in_graph) = boost::edge(u, v, graph_);
if (e_in_graph) {
set_edge_reference(e);
} else {
e = add_reference_edge(u, v);
}
reference_edges_.push_back(e);
}
}
vertex_cache_.rehash(vertex_cache_.size());
reference_kmers_.shrink_to_fit();
reference_vertices_.shrink_to_fit();
reference_edges_.shrink_to_fit();
regenerate_vertex_indices();
reference_head_position_ = 0;
}
bool Assembler::contains_kmer(const Kmer& kmer) const noexcept
{
return vertex_cache_.count(kmer) == 1;
}
std::size_t Assembler::count_kmer(const Kmer& kmer) const noexcept
{
return vertex_cache_.count(kmer);
}
std::size_t Assembler::reference_size() const noexcept
{
return sequence_length(reference_kmers_.size(), kmer_size());
}
void Assembler::regenerate_vertex_indices()
{
const auto p = boost::vertices(graph_);
unsigned idx {0};
std::for_each(p.first, p.second, [this, &idx] (Vertex v) { graph_[v].index = idx++; });
}
bool Assembler::is_reference_unique_path() const
{
if (is_reference_empty()) {
return true;
} else {
auto u = reference_head();
const auto tail = reference_tail();
const auto is_reference_edge = [this] (const Edge e) { return is_reference(e); };
while (u != tail) {
const auto p = boost::out_edges(u, graph_);
const auto itr = std::find_if(p.first, p.second, is_reference_edge);
assert(itr != p.second);
if (std::any_of(boost::next(itr), p.second, is_reference_edge)) {
return false;
}
u = boost::target(*itr, graph_);
}
const auto p = boost::out_edges(tail, graph_);
return std::none_of(p.first, p.second, is_reference_edge);
}
}
Assembler::Vertex Assembler::null_vertex() const
{
return boost::graph_traits<KmerGraph>::null_vertex();
}
boost::optional<Assembler::Vertex> Assembler::add_vertex(const Kmer& kmer, const bool is_reference)
{
if (!utils::is_canonical_dna(kmer)) return boost::none;
const auto u = boost::add_vertex({boost::num_vertices(graph_), kmer, is_reference}, graph_);
vertex_cache_.emplace(kmer, u);
return u;
}
void Assembler::remove_vertex(const Vertex v)
{
const auto c = vertex_cache_.erase(kmer_of(v));
assert(c == 1);
_unused(c); // make production build happy
boost::remove_vertex(v, graph_);
}
void Assembler::clear_and_remove_vertex(const Vertex v)
{
const auto c = vertex_cache_.erase(kmer_of(v));
assert(c == 1);
_unused(c); // make production build happy
boost::clear_vertex(v, graph_);
boost::remove_vertex(v, graph_);
}
void Assembler::clear_and_remove_all(const std::unordered_set<Vertex>& vertices)
{
for (const Vertex v : vertices) {
clear_and_remove_vertex(v);
}
}
Assembler::Edge
Assembler::add_edge(const Vertex u, const Vertex v,
const GraphEdge::WeightType weight,
GraphEdge::WeightType forward_weight,
const int base_quality_sum,
const bool is_reference,
const boost::optional<Assembler::SampleID> sample)
{
decltype(GraphEdge::samples) samples {};
if (sample) {
samples[*sample] = {weight, forward_weight, base_quality_sum};
}
return boost::add_edge(u, v, {std::move(samples), weight, forward_weight, base_quality_sum, is_reference}, graph_).first;
}
Assembler::Edge Assembler::add_reference_edge(const Vertex u, const Vertex v)
{
return add_edge(u, v, 0, 0, 0, true);
}
void Assembler::remove_edge(const Vertex u, const Vertex v)
{
boost::remove_edge(u, v, graph_);
}
void Assembler::remove_edge(const Edge e)
{
boost::remove_edge(e, graph_);
}
void Assembler::increment_weight(const Edge e, const bool is_forward, const int base_quality, const SampleID sample)
{
auto& edge = graph_[e];
auto sample_itr = edge.samples.find(sample);
if (sample_itr != std::cend(edge.samples)) {
++sample_itr->second.weight;
sample_itr->second.base_quality_sum += base_quality;
if (is_forward) ++sample_itr->second.base_quality_sum;
} else {
edge.samples[sample] = {1, is_forward, base_quality};
}
++edge.weight;
edge.base_quality_sum += base_quality;
if (is_forward) ++edge.forward_strand_weight;
}
void Assembler::set_vertex_reference(const Vertex v)
{
graph_[v].is_reference = true;
}
void Assembler::set_vertex_reference(const Kmer& kmer)
{
set_vertex_reference(vertex_cache_.at(kmer));
}
void Assembler::set_edge_reference(const Edge e)
{
graph_[e].is_reference = true;
}
const Assembler::Kmer& Assembler::kmer_of(const Vertex v) const
{
return graph_[v].kmer;
}
char Assembler::front_base_of(const Vertex v) const
{
return kmer_of(v).front();
}
char Assembler::back_base_of(const Vertex v) const
{
return kmer_of(v).back();
}
const Assembler::Kmer& Assembler::source_kmer_of(const Edge e) const
{
return kmer_of(boost::source(e, graph_));
}
const Assembler::Kmer& Assembler::target_kmer_of(const Edge e) const
{
return kmer_of(boost::target(e, graph_));
}
bool Assembler::is_reference(const Vertex v) const
{
return graph_[v].is_reference;
}
bool Assembler::is_source_reference(const Edge e) const
{
return is_reference(boost::source(e, graph_));
}
bool Assembler::is_target_reference(const Edge e) const
{
return is_reference(boost::target(e, graph_));
}
bool Assembler::is_reference(const Edge e) const
{
return graph_[e].is_reference;
}
bool Assembler::is_artificial(const Edge e) const
{
return graph_[e].samples.empty();
}
bool Assembler::is_reference_empty() const noexcept
{
return reference_vertices_.empty();
}
Assembler::Vertex Assembler::reference_head() const
{
return reference_vertices_.front();
}
Assembler::Vertex Assembler::reference_tail() const
{
return reference_vertices_.back();
}
Assembler::Vertex Assembler::next_reference(const Vertex u) const
{
const auto p = boost::out_edges(u, graph_);
const auto itr = std::find_if(p.first, p.second, [this] (const Edge e) { return is_reference(e); });
assert(itr != p.second);
return boost::target(*itr, graph_);
}
Assembler::Vertex Assembler::prev_reference(const Vertex v) const
{
const auto p = boost::in_edges(v, graph_);
const auto itr = std::find_if(p.first, p.second, [this] (const Edge e) { return is_reference(e); });
assert(itr != p.second);
return boost::source(*itr, graph_);
}
std::size_t Assembler::num_reference_kmers() const
{
const auto p = boost::vertices(graph_);
return std::count_if(p.first, p.second, [this] (const Vertex& v) { return is_reference(v); });
}
bool Assembler::is_dangling_branch(const Vertex v) const
{
return !is_reference(v) && boost::in_degree(v, graph_) > 0 && boost::out_degree(v, graph_) == 0;
}
boost::optional<Assembler::Vertex> Assembler::find_joining_kmer(const Vertex v) const
{
const auto& kmer = kmer_of(v);
NucleotideSequence adjacent_kmer {std::next(std::cbegin(kmer)), std::cend(kmer)};
adjacent_kmer.resize(kmer_size());
constexpr std::array<NucleotideSequence::value_type, 4> bases {'A', 'C', 'G', 'T'};
for (const auto base : bases) {
adjacent_kmer.back() = base;
const Kmer k {std::cbegin(adjacent_kmer), std::cend(adjacent_kmer)};
const auto itr = vertex_cache_.find(k);
if (itr != std::cend(vertex_cache_)) {
return itr->second;
}
}
return boost::none;
}
Assembler::NucleotideSequence Assembler::make_sequence(const Path& path) const
{
assert(!path.empty());
NucleotideSequence result(kmer_size() + path.size() - 1, 'N');
const auto& first_kmer = kmer_of(path.front());
auto itr = std::copy(std::cbegin(first_kmer), std::cend(first_kmer), std::begin(result));
std::transform(std::next(std::cbegin(path)), std::cend(path), itr,
[this] (const Vertex v) { return back_base_of(v); });
return result;
}
Assembler::NucleotideSequence Assembler::make_reference(Vertex from, const Vertex to) const
{
const auto null = null_vertex();
NucleotideSequence result {};
if (from == to || from == null) {
return result;
}
auto last = to;
if (last == null) {
if (from == reference_tail()) {
return static_cast<NucleotideSequence>(kmer_of(from));
}
last = reference_tail();
}
result.reserve(2 * kmer_size());
const auto& first_kmer = kmer_of(from);
result.assign(std::cbegin(first_kmer), std::cend(first_kmer));
from = next_reference(from);
while (from != last) {
result.push_back(back_base_of(from));
from = next_reference(from);
}
if (to == null) {
result.push_back(back_base_of(last));
}
result.shrink_to_fit();
return result;
}
void Assembler::remove_path(const std::deque<Vertex>& path)
{
assert(!path.empty());
if (path.size() == 1) {
clear_and_remove_vertex(path.front());
} else {
remove_edge(*boost::in_edges(path.front(), graph_).first);
auto prev = path.front();
std::for_each(std::next(std::cbegin(path)), std::cend(path),
[this, &prev] (const Vertex v) {
remove_edge(prev, v);
remove_vertex(prev);
prev = v;
});
remove_edge(*boost::out_edges(path.back(), graph_).first);
remove_vertex(path.back());
}
}
bool Assembler::is_bridge(const Vertex v) const
{
return boost::in_degree(v, graph_) == 1 && boost::out_degree(v, graph_) == 1;
}
bool Assembler::is_reference_bridge(const Vertex v) const
{
return is_reference(v) && is_bridge(v);
}
Assembler::Path::const_iterator
Assembler::is_bridge_until(const Path::const_iterator first, const Path::const_iterator last) const
{
return std::find_if_not(first, last, [this] (const Vertex v) { return is_bridge(v); });
}
Assembler::Path::const_iterator Assembler::is_bridge_until(const Path& path) const
{
return is_bridge_until(std::cbegin(path), std::cend(path));
}
bool Assembler::is_bridge(Path::const_iterator first, Path::const_iterator last) const
{
return std::all_of(first, last, [this] (const Vertex v) { return is_bridge(v); });
}
bool Assembler::is_bridge(const Path& path) const
{
return is_bridge(std::cbegin(path), std::cend(path));
}
std::pair<bool, Assembler::Vertex> Assembler::is_bridge_to_reference(Vertex from) const
{
while (is_bridge(from)) {
from = *boost::adjacent_vertices(from, graph_).first;
if (is_reference(from)) {
return std::make_pair(true, from);
}
}
return std::make_pair(false, null_vertex());
}
bool Assembler::joins_reference_only(const Vertex v) const
{
return boost::out_degree(v, graph_) == 1 && is_reference(*boost::out_edges(v, graph_).first);
}
bool Assembler::joins_reference_only(Path::const_iterator first, Path::const_iterator last) const
{
const auto itr = std::find_if(first, last, [this] (Vertex v) { return is_reference(v) || boost::out_degree(v, graph_) != 1; });
return itr == last || is_reference(*itr);
}
bool Assembler::is_trivial_cycle(const Edge e) const
{
return boost::source(e, graph_) == boost::target(e, graph_);
}
bool Assembler::graph_has_trivial_cycle() const
{
const auto p = boost::edges(graph_);
return std::any_of(p.first, p.second, [this] (const Edge& e) { return is_trivial_cycle(e); });
}
bool Assembler::graph_has_nontrivial_cycle() const
{
const auto index_map = boost::get(&GraphNode::index, graph_);
try {
boost::depth_first_search(graph_, boost::visitor(CycleDetector {}).root_vertex(reference_head()).vertex_index_map(index_map));
return false;
} catch (const CycleDetector::CycleDetectedException&) {
return true;
}
}
void Assembler::remove_trivial_nonreference_cycles()
{
boost::remove_edge_if([this] (const Edge e) { return !is_reference(e) && is_trivial_cycle(e); }, graph_);
}
void Assembler::remove_nontrivial_nonreference_cycles()
{
const auto index_map = boost::get(&GraphNode::index, graph_);
std::deque<Edge> cyclic_edges {};
CyclicEdgeDetector<decltype(cyclic_edges)> vis {cyclic_edges, false};
boost::depth_first_search(graph_, boost::visitor(vis).root_vertex(reference_head()).vertex_index_map(index_map));
for (const Edge& e : cyclic_edges) {
if (!(is_reference(e) || is_simple_deletion(e))) {
remove_edge(e);
}
}
}
void Assembler::remove_all_nonreference_cycles(const bool break_chains)
{
const auto index_map = boost::get(&GraphNode::index, graph_);
std::deque<Edge> cyclic_edges {};
CyclicEdgeDetector<decltype(cyclic_edges)> vis {cyclic_edges};
boost::depth_first_search(graph_, boost::visitor(vis).root_vertex(reference_head()).vertex_index_map(index_map));
if (cyclic_edges.empty()) return;
std::unordered_set<Vertex> bad_kmers {}, reference_origins {}, reference_sinks {};
std::deque<std::pair<Vertex, Vertex>> cyclic_reference_segments {};
if (break_chains) {
bad_kmers.reserve(std::min(2 * cyclic_edges.size(), num_kmers()));
reference_origins.reserve(num_reference_kmers());
}
for (const Edge& back_edge : cyclic_edges) {
if (!is_reference(back_edge)) {
if (break_chains) {
Vertex cycle_origin {boost::source(back_edge, graph_)};
while (!is_reference(cycle_origin) && is_bridge(cycle_origin) && bad_kmers.count(cycle_origin) == 0) {
bad_kmers.insert(cycle_origin);
cycle_origin = *boost::inv_adjacent_vertices(cycle_origin, graph_).first;
}
bool is_reference_origin {false};
if (is_reference(cycle_origin)) {
reference_origins.insert(cycle_origin);
is_reference_origin = true;
} else {
bad_kmers.insert(cycle_origin);
}
Vertex cycle_sink {boost::target(back_edge, graph_)};
while (!is_reference(cycle_sink) && is_bridge(cycle_sink) && bad_kmers.count(cycle_sink) == 0) {
bad_kmers.insert(cycle_origin);
cycle_sink = *boost::adjacent_vertices(cycle_sink, graph_).first;
}
if (is_reference(cycle_sink)) {
reference_sinks.insert(cycle_sink);
if (is_reference_origin) {
cyclic_reference_segments.emplace_back(cycle_sink, cycle_origin);
} else if (boost::out_degree(cycle_origin, graph_) > 1) {
const auto p = boost::out_edges(cycle_origin, graph_);
std::vector<Vertex> reference_tails {};
reference_tails.reserve(std::distance(p.first, p.second));
std::for_each(p.first, p.second, [&] (Edge tail_edge) {
if (tail_edge != back_edge) {
auto tail = boost::target(tail_edge, graph_);
while (!is_reference(tail) && boost::out_degree(tail, graph_) == 1
&& bad_kmers.count(tail) == 0) {
bad_kmers.insert(tail);
tail = *boost::adjacent_vertices(tail, graph_).first;
}
if (is_reference(tail)) {
reference_tails.push_back(tail);
}
}
});
if (!reference_tails.empty()) {
Vertex cycle_tail;
if (reference_tails.size() == 1) {
cycle_tail = reference_tails.front();
} else {
// Just add the rightmost reference vertex
auto itr = std::find_first_of(std::crbegin(reference_vertices_), std::crend(reference_vertices_),
std::cbegin(reference_tails), std::cend(reference_tails));
assert(itr != std::crend(reference_vertices_));
cycle_tail = *itr;
}
const std::array<Vertex, 2> cycle_vertices {cycle_sink, cycle_tail};
auto itr = std::find_first_of(std::cbegin(reference_vertices_), std::cend(reference_vertices_),
std::cbegin(cycle_vertices), std::cend(cycle_vertices));
assert(itr != std::cend(reference_vertices_));
if (*itr == cycle_vertices.front()) {
cyclic_reference_segments.emplace_back(cycle_sink, cycle_tail);
} else {
cyclic_reference_segments.emplace_back(cycle_tail, cycle_sink);
}
}
}
} else {
bad_kmers.insert(cycle_sink);
}
}
remove_edge(back_edge);
}
}
bool regenerate_indices {false};
for (Vertex v : reference_origins) {
boost::remove_in_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);
regenerate_indices = true;
}
for (Vertex v : reference_sinks) {
boost::remove_out_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);
regenerate_indices = true;
}
if (!bad_kmers.empty()) {
clear_and_remove_all(bad_kmers);
regenerate_indices = true;
}
if (!cyclic_reference_segments.empty()) {
for (const auto& p : cyclic_reference_segments) {
const auto first_vertex_itr = std::find(std::cbegin(reference_vertices_), std::cend(reference_vertices_), p.first);
assert(first_vertex_itr != std::cend(reference_vertices_));
const auto last_vertex_itr = std::find(first_vertex_itr, std::cend(reference_vertices_), p.second);
assert(last_vertex_itr != std::cend(reference_vertices_));
std::for_each(first_vertex_itr, last_vertex_itr, [this] (Vertex v) {
boost::remove_in_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);
boost::remove_out_edge_if(v, [this] (Edge e) { return !is_reference(e); }, graph_);
});
}
regenerate_indices = true;
}
if (regenerate_indices) {
regenerate_vertex_indices();
}
}
bool Assembler::is_simple_deletion(Edge e) const
{
return !is_reference(e) && is_source_reference(e) && is_target_reference(e);
}
bool Assembler::is_on_path(const Edge e, const Path& path) const
{
if (path.size() < 2) return false;
auto first_vertex = std::cbegin(path);
auto next_vertex = std::next(first_vertex);
const auto last_vertex = std::cend(path);
Edge path_edge; bool good;
for (; next_vertex != last_vertex; ++first_vertex, ++next_vertex) {
std::tie(path_edge, good) = boost::edge(*first_vertex, *next_vertex, graph_);
assert(good);
if (path_edge == e) return true;
}
return false;
}
bool Assembler::connects_to_path(Edge e, const Path& path) const
{
return e == *boost::in_edges(path.front(), graph_).first || e == *boost::out_edges(path.back(), graph_).first;
}
bool Assembler::is_dependent_on_path(Edge e, const Path& path) const
{
return connects_to_path(e, path) || is_on_path(e, path);
}
Assembler::GraphEdge::WeightType Assembler::weight(const Path& path) const
{
if (path.size() < 2) return 0;
return std::inner_product(std::cbegin(path), std::prev(std::cend(path)),
std::next(std::cbegin(path)), GraphEdge::WeightType {0},
std::plus<> {},
[this] (const auto& u, const auto& v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(u, v, graph_);
assert(good);
return graph_[e].weight;
});
}
Assembler::GraphEdge::WeightType Assembler::max_weight(const Path& path) const
{
GraphEdge::WeightType result {0};
for (std::size_t u {0}, v {1}; v < path.size(); ++u, ++v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(path[u], path[v], graph_);
assert(good);
result = std::max(result, graph_[e].weight);
}
return result;
}
unsigned Assembler::count_low_weights(const Path& path, const unsigned low_weight) const
{
if (path.size() < 2) return 0;
return std::inner_product(std::cbegin(path), std::prev(std::cend(path)), std::next(std::cbegin(path)), 0u, std::plus<> {},
[this, low_weight] (const auto& u, const auto& v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(u, v, graph_);
assert(good);
return graph_[e].weight <= low_weight ? 1 : 0;
});
}
bool Assembler::has_low_weight_flanks(const Path& path, const unsigned low_weight) const
{
if (path.size() < 2) return false;
Edge e; bool good;
std::tie(e, good) = boost::edge(path[0], path[1], graph_);
assert(good);
if (graph_[e].weight <= low_weight) return true;
std::tie(e, good) = boost::edge(std::crbegin(path)[1], std::crbegin(path)[0], graph_);
assert(good);
return graph_[e].weight <= low_weight;
}
unsigned Assembler::count_low_weight_flanks(const Path& path, unsigned low_weight) const
{
if (path.size() < 2) return 0;
const auto is_low_weight = [this, low_weight] (const auto& u, const auto& v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(u, v, graph_);
assert(good);
return graph_[e].weight > low_weight ? 1 : 0;
};
const auto first_head_high_weight = std::adjacent_find(std::cbegin(path), std::cend(path), is_low_weight);
const auto first_tail_high_weight = std::adjacent_find(std::crbegin(path), std::make_reverse_iterator(first_head_high_weight),
[&] (const auto& u, const auto& v) {
return is_low_weight(v, u);
});
const auto num_head_low_weight = std::distance(std::cbegin(path), first_head_high_weight);
const auto num_tail_low_weight = std::distance(std::crbegin(path), first_tail_high_weight);
return static_cast<unsigned>(num_head_low_weight + num_tail_low_weight);
}
Assembler::PathWeightStats Assembler::compute_weight_stats(const Path& path) const
{
PathWeightStats result {};
if (path.size() > 1) {
result.max = max_weight(path);
result.min = result.max;
result.distribution.resize(result.max + 1);
std::vector<GraphEdge::WeightType> weights(path.size() - 1);
for (std::size_t u {0}, v {1}; v < path.size(); ++u, ++v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(path[u], path[v], graph_);
assert(good);
const auto weight = graph_[e].weight;
++result.distribution[weight];
result.total += weight;
result.min = std::min(result.min, weight);
if (!is_artificial(e)) {
const auto forward_weight = graph_[e].forward_strand_weight;
result.total_forward += forward_weight;
result.total_reverse += weight - forward_weight;
}
weights[u] = weight;
}
for (auto& w : result.distribution) w /= weights.size();
result.mean = static_cast<double>(result.total) / weights.size();
result.median = maths::median(weights);
result.stdev = maths::stdev(weights);
}
return result;
}
Assembler::GraphEdge::WeightType Assembler::sum_source_in_edge_weight(const Edge e) const
{
const auto p = boost::in_edges(boost::source(e, graph_), graph_);
using Weight = GraphEdge::WeightType;
return std::accumulate(p.first, p.second, Weight {0},
[this] (const Weight curr, const Edge& e) {
return curr + graph_[e].weight;
});
}
Assembler::GraphEdge::WeightType Assembler::sum_target_out_edge_weight(const Edge e) const
{
const auto p = boost::out_edges(boost::target(e, graph_), graph_);
using Weight = GraphEdge::WeightType;
return std::accumulate(p.first, p.second, Weight {0},
[this] (const Weight curr, const Edge& e) {
return curr + graph_[e].weight;
});
}
bool Assembler::all_in_edges_low_weight(Vertex v, unsigned min_weight) const
{
const auto p = boost::in_edges(v, graph_);
return std::all_of(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });
}
bool Assembler::all_out_edges_low_weight(Vertex v, unsigned min_weight) const
{
const auto p = boost::out_edges(v, graph_);
return std::all_of(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });
}
bool Assembler::is_low_weight(const Vertex v, const unsigned min_weight) const
{
return !is_reference(v) && all_in_edges_low_weight(v, min_weight) && all_out_edges_low_weight(v, min_weight);
}
std::size_t Assembler::low_weight_out_degree(Vertex v, unsigned min_weight) const
{
const auto p = boost::out_edges(v, graph_);
const auto d = std::count_if(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });
return static_cast<std::size_t>(d);
}
std::size_t Assembler::low_weight_in_degree(Vertex v, unsigned min_weight) const
{
const auto p = boost::in_edges(v, graph_);
const auto d = std::count_if(p.first, p.second, [this, min_weight] (Edge e) { return graph_[e].weight < min_weight; });
return static_cast<std::size_t>(d);
}
bool Assembler::is_low_weight_source(Vertex v, unsigned min_weight) const
{
const auto num_low_weight = low_weight_out_degree(v, min_weight);
return num_low_weight > 0 && num_low_weight < boost::out_degree(v, graph_);
}
bool Assembler::is_low_weight_sink(Vertex v, unsigned min_weight) const
{
const auto num_low_weight = low_weight_in_degree(v, min_weight);
return num_low_weight > 0 && num_low_weight < boost::in_degree(v, graph_);
}
namespace {
template <typename Iterator, typename Set>
bool all_in(Iterator first, Iterator last, const Set& values)
{
return std::all_of(first, last, [&] (const auto& value) { return values.count(value) == 1; });
}
} // namespace
void Assembler::remove_low_weight_edges(const unsigned min_weight)
{
boost::remove_edge_if([this, min_weight] (const Edge& e) {
return !is_reference(e) && graph_[e].weight < min_weight
&& sum_source_in_edge_weight(e) < min_weight
&& sum_target_out_edge_weight(e) < min_weight;
}, graph_);
}
void Assembler::remove_disconnected_vertices()
{
VertexIterator vi, vi_end, vi_next;
std::tie(vi, vi_end) = boost::vertices(graph_);
for (vi_next = vi; vi != vi_end; vi = vi_next) {
++vi_next;
if (boost::degree(*vi, graph_) == 0) {
remove_vertex(*vi);
}
}
}
std::unordered_set<Assembler::Vertex> Assembler::find_reachable_kmers(const Vertex from) const
{
std::unordered_set<Vertex> result {};
result.reserve(boost::num_vertices(graph_));
auto vis = boost::make_bfs_visitor(boost::write_property(boost::typed_identity_property_map<Vertex>(),
std::inserter(result, std::begin(result)),
boost::on_discover_vertex()));
boost::breadth_first_search(graph_, from,
boost::visitor(vis).vertex_index_map(boost::get(&GraphNode::index, graph_)));
return result;
}
std::deque<Assembler::Vertex> Assembler::remove_vertices_that_cant_be_reached_from(const Vertex v)
{
const auto reachables = find_reachable_kmers(v);
VertexIterator vi, vi_end, vi_next;
std::tie(vi, vi_end) = boost::vertices(graph_);
std::deque<Vertex> result {};
for (vi_next = vi; vi != vi_end; vi = vi_next) {
++vi_next;
if (reachables.count(*vi) == 0) {
result.push_back(*vi);
clear_and_remove_vertex(*vi);
}
}
return result;
}
void Assembler::remove_vertices_that_cant_reach(const Vertex v)
{
if (!is_reference_empty()) {
const auto transpose = boost::make_reverse_graph(graph_);
const auto index_map = boost::get(&GraphNode::index, transpose);
std::unordered_set<Vertex> reachables {};
auto vis = boost::make_bfs_visitor(boost::write_property(boost::typed_identity_property_map<Vertex>(),
std::inserter(reachables, std::begin(reachables)),
boost::on_discover_vertex()));
boost::breadth_first_search(transpose, v, boost::visitor(vis).vertex_index_map(index_map));
VertexIterator vi, vi_end, vi_next;
std::tie(vi, vi_end) = boost::vertices(graph_);
for (vi_next = vi; vi != vi_end; vi = vi_next) {
++vi_next;
if (reachables.count(*vi) == 0) {
clear_and_remove_vertex(*vi);
}
}
}
}
void Assembler::remove_vertices_past(const Vertex v)
{
auto reachables = find_reachable_kmers(v);
reachables.erase(v);
boost::clear_out_edges(v, graph_);
std::deque<Vertex> cycle_tails {};
// Must check for cycles that lead back to v
for (auto u : reachables) {
Edge e; bool present;
std::tie(e, present) = boost::edge(u, v, graph_);
if (present) cycle_tails.push_back(u);
}
if (!cycle_tails.empty()) {
// We can check reachable back edges as the links from v were cut previously
const auto transpose = boost::make_reverse_graph(graph_);
const auto index_map = boost::get(&GraphNode::index, transpose);
std::unordered_set<Vertex> back_reachables {};
auto vis = boost::make_bfs_visitor(boost::write_property(boost::typed_identity_property_map<Vertex>(),
std::inserter(back_reachables, std::begin(back_reachables)),
boost::on_discover_vertex()));
for (auto u : cycle_tails) {
boost::breadth_first_search(transpose, u, boost::visitor(vis).vertex_index_map(index_map));
reachables.erase(u);
}
// The intersection of reachables & back_reachables are vertices part
// of a cycle past v. The remaining vertices in reachables are safe to
// remove.
bool has_intersects {false};
for (auto u : back_reachables) {
const auto iter = reachables.find(u);
if (iter != std::cend(reachables)) {
reachables.erase(iter);
has_intersects = true;
}
}
if (has_intersects) {
const auto removed = remove_vertices_that_cant_be_reached_from(reference_head());
for (auto u : removed) reachables.erase(u);
}
}
clear_and_remove_all(reachables);
}
bool Assembler::can_prune_reference_flanks() const
{
return boost::out_degree(reference_head(), graph_) == 1 || boost::in_degree(reference_tail(), graph_) == 1;
}
void Assembler::pop_reference_head()
{
reference_kmers_.pop_front();
reference_vertices_.pop_front();
if (!reference_edges_.empty()) {
reference_edges_.pop_front();
}
++reference_head_position_;
}
void Assembler::pop_reference_tail()
{
reference_kmers_.pop_back();
reference_vertices_.pop_back();
if (!reference_edges_.empty()) {
reference_edges_.pop_back();
}
}
void Assembler::prune_reference_flanks()
{
if (!is_reference_empty()) {
auto new_head_itr = std::cbegin(reference_vertices_);
const auto is_bridge_vertex = [this] (const Vertex v) { return is_bridge(v); };
if (boost::in_degree(reference_head(), graph_) == 0 && boost::out_degree(reference_head(), graph_) == 1) {
new_head_itr = std::find_if_not(std::next(new_head_itr), std::cend(reference_vertices_), is_bridge_vertex);
std::for_each(std::cbegin(reference_vertices_), new_head_itr, [this] (const Vertex u) {
remove_edge(u, *boost::adjacent_vertices(u, graph_).first);
remove_vertex(u);
pop_reference_head();
});
}
if (new_head_itr != std::cend(reference_vertices_) && boost::in_degree(reference_tail(), graph_) == 1
&& boost::out_degree(reference_tail(), graph_) == 0) {
const auto new_tail_itr = std::find_if_not(std::next(std::crbegin(reference_vertices_)),
std::make_reverse_iterator(new_head_itr),
is_bridge_vertex);
std::for_each(std::crbegin(reference_vertices_), new_tail_itr, [this] (const Vertex u) {
remove_edge(*boost::inv_adjacent_vertices(u, graph_).first, u);
remove_vertex(u);
pop_reference_tail();
});
}
}
}
Assembler::DominatorMap
Assembler::build_dominator_tree(const Vertex from) const
{
DominatorMap result;
result.reserve(boost::num_vertices(graph_));
boost::lengauer_tarjan_dominator_tree(graph_, from, boost::make_assoc_property_map(result));
auto it = std::cbegin(result);
for (; it != std::cend(result);) {
if (it->second == null_vertex()) {
it = result.erase(it);
} else {
++it;
}
}
result.rehash(result.size());
return result;
}
std::unordered_set<Assembler::Vertex> Assembler::extract_nondominants(const Vertex from) const
{
const auto dom_tree = build_dominator_tree(from);
std::unordered_set<Vertex> dominators {};
dominators.reserve(dom_tree.size());
for (const auto& p : dom_tree) {
dominators.emplace(p.second);
}
std::unordered_set<Vertex> result {};
result.reserve(dom_tree.size());
for (const auto& p : dom_tree) {
if (dominators.count(p.first) == 0) {
result.emplace(p.first);
}
}
return result;
}
std::deque<Assembler::Vertex> Assembler::extract_nondominant_reference(const DominatorMap& dominator_tree) const
{
std::unordered_set<Vertex> dominators {};
dominators.reserve(dominator_tree.size());
for (const auto& p : dominator_tree) {
dominators.emplace(p.second);
}
std::deque<Vertex> result {};
for (const auto& p : dominator_tree) {
if (is_reference(p.first) && p.first != reference_tail() && dominators.count(p.first) == 0) {
result.push_back(p.first);
}
}
return result;
}
std::pair<Assembler::Vertex, unsigned> Assembler::find_bifurcation(Vertex from, const Vertex to) const
{
unsigned count {0};
while (from != to) {
const auto d = boost::out_degree(from, graph_);
if (d == 0 || d > 1) {
return std::make_pair(from, count);
}
from = *boost::adjacent_vertices(from, graph_).first;
++count;
}
return std::make_pair(from, count);
}
template <typename V, typename G>
auto count_out_weight(const V& v, const G& g)
{
using T = decltype(g[typename boost::graph_traits<G>::edge_descriptor()].weight);
const auto p = boost::out_edges(v, g);
return std::accumulate(p.first, p.second, T {0},
[&g] (const auto curr, const auto& e) {
return curr + g[e].weight;
});
}
template <typename R, typename T>
auto compute_transition_score(const T edge_weight, const T total_out_weight) noexcept
{
if (total_out_weight == 0) {
return R {0};
} else if (edge_weight == 0) {
return -10 * std::log10(R {1} / total_out_weight);
} else if (edge_weight == total_out_weight) {
return R {1} / edge_weight;
} else {
return -10 * std::log10(static_cast<R>(edge_weight) / total_out_weight);
}
}
void Assembler::set_out_edge_transition_scores(const Vertex v)
{
const auto total_out_weight = count_out_weight(v, graph_);
const auto p = boost::out_edges(v, graph_);
using R = GraphEdge::ScoreType;
std::for_each(p.first, p.second, [this, total_out_weight] (const Edge& e) {
graph_[e].transition_score = compute_transition_score<R>(graph_[e].weight, total_out_weight);
});
}
template <typename R, typename G, typename PropertyMap>
struct TransitionScorer : public boost::default_dfs_visitor
{
using Vertex = typename boost::graph_traits<G>::vertex_descriptor;
PropertyMap map;
TransitionScorer(PropertyMap m) : map {m} {}
void discover_vertex(Vertex v, const G& g)
{
const auto total_out_weight = count_out_weight(v, g);
const auto p = boost::out_edges(v, g);
std::for_each(p.first, p.second, [this, &g, total_out_weight] (const auto& e) {
boost::put(map, e, compute_transition_score<R>(g[e].weight, total_out_weight));
});
}
};
void Assembler::set_all_edge_transition_scores_from(const Vertex src)
{
auto score_map = boost::get(&GraphEdge::transition_score, graph_);
TransitionScorer<GraphEdge::ScoreType, KmerGraph, decltype(score_map)> vis {score_map};
boost::depth_first_search(graph_, boost::visitor(vis)
.vertex_index_map(boost::get(&GraphNode::index, graph_)));
for (auto p = boost::edges(graph_); p.first != p.second; ++p.first) {
graph_[*p.first].transition_score = score_map[*p.first];
}
}
void Assembler::set_all_in_edge_transition_scores(const Vertex v, const GraphEdge::ScoreType score)
{
const auto p = boost::in_edges(v, graph_);
std::for_each(p.first, p.second, [this, score] (const Edge e) {
graph_[e].transition_score = score;
});
}
void Assembler::block_all_in_edges(const Vertex v)
{
const auto total_out_weight = count_out_weight(v, graph_);
set_all_in_edge_transition_scores(v, compute_transition_score<GraphEdge::ScoreType>(0u, total_out_weight));
}
Assembler::PredecessorMap Assembler::find_shortest_scoring_paths(const Vertex from, const bool use_weights) const
{
assert(from != null_vertex());
std::unordered_map<Vertex, Vertex> result {};
result.reserve(boost::num_vertices(graph_));
if (use_weights) {
boost::dag_shortest_paths(graph_, from,
boost::weight_map(boost::get(&GraphEdge::weight, graph_))
.predecessor_map(boost::make_assoc_property_map(result))
.vertex_index_map(boost::get(&GraphNode::index, graph_)));
} else {
boost::dag_shortest_paths(graph_, from,
boost::weight_map(boost::get(&GraphEdge::transition_score, graph_))
.predecessor_map(boost::make_assoc_property_map(result))
.vertex_index_map(boost::get(&GraphNode::index, graph_)));
}
return result;
}
bool Assembler::is_on_path(const Vertex v, const PredecessorMap& predecessors, const Vertex from) const
{
if (v == from) return true;
assert(predecessors.count(from) == 1);
auto itr = predecessors.find(from);
while (itr != std::end(predecessors) && itr->first != itr->second) {
if (itr->second == v) return true;
itr = predecessors.find(itr->second);
}
return false;
}
bool Assembler::is_on_path(const Edge e, const PredecessorMap& predecessors, const Vertex from) const
{
assert(predecessors.count(from) == 1);
const auto last = std::cend(predecessors);
auto itr1 = predecessors.find(from);
assert(itr1 != last);
auto itr2 = predecessors.find(itr1->second);
Edge path_edge; bool good;
while (itr2 != last && itr1 != itr2) {
std::tie(path_edge, good) = boost::edge(itr2->second, itr1->second, graph_);
assert(good);
if (path_edge == e) {
return true;
}
itr1 = itr2;
itr2 = predecessors.find(itr1->second);
}
return false;
}
Assembler::Path Assembler::extract_full_path(const PredecessorMap& predecessors, const Vertex from) const
{
assert(predecessors.count(from) == 1);
Path result {from};
auto itr = predecessors.find(from);
while (itr != std::end(predecessors) && itr->first != itr->second) {
result.push_front(itr->second);
itr = predecessors.find(itr->second);
}
return result;
}
std::tuple<Assembler::Vertex, Assembler::Vertex, unsigned>
Assembler::backtrack_until_nonreference(const PredecessorMap& predecessors, Vertex from) const
{
assert(predecessors.count(from) == 1);
auto v = predecessors.at(from);
unsigned count {1};
const auto head = reference_head();
while (v != head) {
assert(from != v); // was not reachable from source
const auto p = boost::edge(v, from, graph_);
assert(p.second);
if (!is_reference(p.first)) break;
from = v;
assert(predecessors.count(from) == 1);
v = predecessors.at(from);
++count;
}
return std::make_tuple(v, from, count);
}
Assembler::Path Assembler::extract_nonreference_path(const PredecessorMap& predecessors, Vertex from) const
{
Path result {from};
from = predecessors.at(from);
while (!is_reference(from)) {
result.push_front(from);
from = predecessors.at(from);
}
return result;
}
template <typename Map>
auto count_unreachables(const Map& predecessors)
{
return std::count_if(std::cbegin(predecessors), std::cend(predecessors),
[] (const auto& p) { return p.first == p.second; });
}
template <typename Path, typename Map>
void erase_all(const Path& path, Map& dominator_tree)
{
for (const auto& v : path) dominator_tree.erase(v);
}
template <typename V, typename BidirectionalIt, typename Map>
bool is_dominated_by_path(const V& vertex, const BidirectionalIt first, const BidirectionalIt last,
const Map& dominator_tree)
{
const auto& dominator = dominator_tree.at(vertex);
const auto rfirst = std::make_reverse_iterator(last);
const auto rlast = std::make_reverse_iterator(first);
// reverse because more likely to be a closer vertex
return std::find(rfirst, rlast, dominator) != rlast;
}
Assembler::Edge Assembler::head_edge(const Path& path) const
{
assert(path.size() > 1);
Edge e; bool good;
std::tie(e, good) = boost::edge(path[0], path[1], graph_);
assert(good);
return e;
}
int Assembler::head_mean_base_quality(const Path& path) const
{
const auto& fork_edge = graph_[head_edge(path)];
return fork_edge.weight > 0 ? fork_edge.base_quality_sum / fork_edge.weight : 0;
}
int Assembler::tail_mean_base_quality(const Path& path) const
{
if (path.size() < 3) return 0;
int base_quality_sum {0};
const auto add_edge = [&] (const auto& u, const auto& v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(u, v, graph_);
assert(good);
base_quality_sum += graph_[e].base_quality_sum;
return graph_[e].weight;
};
auto total_weight = std::inner_product(std::next(std::cbegin(path)), std::prev(std::cend(path)),
std::next(std::cbegin(path), 2), GraphEdge::WeightType {0},
std::plus<> {}, add_edge);
return base_quality_sum / total_weight;
}
double Assembler::get_min_bubble_score(Vertex ref_head, Vertex ref_tail, BubbleScoreSetter min_bubble_scorer) const
{
const auto ref_head_itr = std::find(std::cbegin(reference_vertices_), std::cend(reference_vertices_), ref_head);
assert(ref_head_itr != std::cend(reference_vertices_));
const auto ref_head_idx = static_cast<std::size_t>(std::distance(std::cbegin(reference_vertices_), ref_head_itr));
const auto ref_tail_itr = std::find(ref_head_itr, std::cend(reference_vertices_), ref_tail);
assert(ref_tail_itr != std::cend(reference_vertices_));
const auto ref_tail_idx = static_cast<std::size_t>(std::distance(std::cbegin(reference_vertices_), ref_tail_itr));
return min_bubble_scorer(ref_head_idx, ref_tail_idx);
}
namespace {
double base_quality_probability(const int base_quality)
{
// If the given base quality is zero then there were no observations so just report 1
return base_quality > 0 ? maths::phred_to_probability<>(base_quality) : 1.0;
}
} // namespace
double Assembler::bubble_score(const Path& path) const
{
if (path.size() < 2) return 0;
const auto weight_stats = compute_weight_stats(path);
auto result = static_cast<double>(weight_stats.max);
if (params_.use_strand_bias) {
GraphEdge::WeightType context_forward_weight {0}, context_reverse_weight {0};
const auto add_strand_weights = [&] (const auto& p) {
std::for_each(p.first, p.second, [&] (const Edge e) {
const auto forward_weight = graph_[e].forward_strand_weight;
context_forward_weight += forward_weight;
context_reverse_weight += (graph_[e].weight - forward_weight);
});
};
add_strand_weights(boost::in_edges(path.front(), graph_));
// path.front() is reference, path.back() is not
const auto p = boost::adjacent_vertices(path.back(), graph_);
std::for_each(p.first, p.second, [&] (Vertex v) {
add_strand_weights(boost::out_edges(v, graph_));
});
auto pval = maths::fisher_exact_test(weight_stats.total_forward, context_forward_weight,
weight_stats.total_reverse, context_reverse_weight);
if (pval < 0.001) result *= pval;
}
if (params_.use_base_qualities) {
result *= base_quality_probability(head_mean_base_quality(path));
if (path.size() > 2) {
result *= base_quality_probability(tail_mean_base_quality(path));
}
}
return result;
}
std::vector<Assembler::EdgePath> Assembler::extract_k_shortest_paths(Vertex src, Vertex dst, unsigned k) const
{
auto weights = boost::get(&GraphEdge::transition_score, graph_);
auto indices = boost::get(&GraphNode::index, graph_);
const auto ksps = boost::yen_ksp(graph_, src, dst, std::move(weights), std::move(indices), k);
std::vector<EdgePath> result {};
result.reserve(k);
for (const auto& p : ksps) {
result.emplace_back(std::cbegin(p.second), std::cend(p.second));
}
return result;
}
struct BfsSearcherSuccess {};
template <typename Vertex>
struct BfsSearcher : public boost::default_bfs_visitor
{
BfsSearcher(Vertex v) : v_ {v} {}
template <typename Graph>
void discover_vertex(Vertex v, const Graph& g) const
{
if (v == v_) throw BfsSearcherSuccess {};
}
private:
Vertex v_;
};
template <typename Vertex>
auto make_bfs_searcher(Vertex v)
{
return BfsSearcher<Vertex> {v};
}
std::deque<Assembler::Variant>
Assembler::extract_bubble_paths(unsigned k, const BubbleScoreSetter min_bubble_scorer)
{
auto num_remaining_alt_kmers = num_kmers() - num_reference_kmers();
std::deque<Variant> result {};
boost::optional<DominatorMap> dominator_tree {};
bool use_weights {false};
while (k > 0 && num_remaining_alt_kmers > 0) {
auto predecessors = find_shortest_scoring_paths(reference_head(), use_weights);
assert(count_unreachables(predecessors) == 1);
Vertex ref, alt; unsigned rhs_kmer_count;
std::tie(alt, ref, rhs_kmer_count) = backtrack_until_nonreference(predecessors, reference_tail());
if (alt == reference_head()) {
// complete reference path is shortest path
if (dominator_tree) {
if (use_weights) {
utils::append(extract_bubble_paths_with_ksp(k, min_bubble_scorer), result);
return result;
} else {
use_weights = true;
continue;
}
} else {
dominator_tree = build_dominator_tree(reference_head());
const auto nondominant_reference = extract_nondominant_reference(*dominator_tree);
for (Vertex v : nondominant_reference) {
block_all_in_edges(v);
}
continue;
}
}
bool removed_bubble {false};
while (alt != reference_head()) {
auto alt_path = extract_nonreference_path(predecessors, alt);
assert(!alt_path.empty());
assert(predecessors.count(alt_path.front()) == 1);
const auto ref_before_bubble = predecessors.at(alt_path.front());
auto ref_seq = make_reference(ref_before_bubble, ref);
alt_path.push_front(ref_before_bubble);
const auto min_bubble_score = get_min_bubble_score(ref_before_bubble, ref, min_bubble_scorer);
const auto score = bubble_score(alt_path);
const bool is_extractable {score >= min_bubble_score};
auto alt_seq = make_sequence(alt_path);
alt_path.pop_front();
rhs_kmer_count += count_kmers(ref_seq, kmer_size());
if (is_extractable) {
const auto pos = reference_head_position_ + reference_size() - sequence_length(rhs_kmer_count, kmer_size());
result.emplace_front(pos, std::move(ref_seq), std::move(alt_seq));
}
--rhs_kmer_count; // because we padded one reference kmer to make ref_seq
Edge edge_to_alt; bool good;
std::tie(edge_to_alt, good) = boost::edge(alt, ref, graph_);
assert(good);
if (alt_path.size() == 1 && is_simple_deletion(edge_to_alt)) {
remove_edge(alt_path.front(), ref);
set_out_edge_transition_scores(alt_path.front());
} else {
auto vertex_before_bridge = ref_before_bubble;
assert(is_reference(vertex_before_bridge));
const auto bifurication_point_itr = is_bridge_until(alt_path);
if (bifurication_point_itr == std::cend(alt_path)) {
/*
-> ref -> ref -> ->
/ \
ref ref*
\ /
-> alt -> alt -> alt
The entire alt path can be removed as it never needs to be explored again;
the reference path can always be taken.
*/
remove_path(alt_path);
regenerate_vertex_indices();
set_out_edge_transition_scores(vertex_before_bridge);
num_remaining_alt_kmers -= alt_path.size();
alt_path.clear();
removed_bubble = true;
} else if (joins_reference_only(bifurication_point_itr, std::cend(alt_path))) {
/*
-> ref -> ref -> ref -> ref ->
/ \
ref -> alt -> -> alt ref
\ \ /
-> alt -> alt -> alt* -> alt ->
The alt path can be removed up until the bifurication point as one of the other
alt paths can be taken in future paths.
*/
if (bifurication_point_itr == std::cbegin(alt_path)) {
remove_edge(ref_before_bubble, alt_path.front());
alt_path.clear();
} else {
alt_path.erase(bifurication_point_itr, std::cend(alt_path));
remove_path(alt_path);
}
regenerate_vertex_indices();
set_out_edge_transition_scores(vertex_before_bridge);
num_remaining_alt_kmers -= alt_path.size();
removed_bubble = true;
} else if (boost::in_degree(*bifurication_point_itr, graph_) == 1) {
const auto next_bifurication_point_itr = is_bridge_until(std::next(bifurication_point_itr), std::cend(alt_path));
if (next_bifurication_point_itr != std::cend(alt_path)) {
if (boost::out_degree(*next_bifurication_point_itr, graph_) == 1) {
if (joins_reference_only(next_bifurication_point_itr, std::cend(alt_path))) {
const auto p = boost::adjacent_vertices(*bifurication_point_itr, graph_);
auto is_simple_bubble = std::all_of(p.first, p.second, [&] (Vertex v) {
if (v == *std::next(bifurication_point_itr)) {
return true;
} else {
try {
boost::breadth_first_search(graph_, v,
boost::visitor(make_bfs_searcher(*next_bifurication_point_itr)).
vertex_index_map(boost::get(&GraphNode::index, graph_)));
} catch (const BfsSearcherSuccess&) {
return true;
}
return false;
}
});
if (is_simple_bubble) {
/*
-> ref -> ref -> ref -> ref ->
/ \
ref -> alt -> -> alt ref
\ / \ /
-> alt* -> alt -> alt -> alt ->
*/
const auto bifurication_point = *bifurication_point_itr;
if (std::next(bifurication_point_itr) == next_bifurication_point_itr) {
remove_edge(*bifurication_point_itr, *std::next(bifurication_point_itr));
alt_path.clear();
} else {
alt_path.erase(std::cbegin(alt_path), std::next(bifurication_point_itr));
alt_path.erase(next_bifurication_point_itr, std::cend(alt_path));
remove_path(alt_path);
}
regenerate_vertex_indices();
set_all_edge_transition_scores_from(bifurication_point);
num_remaining_alt_kmers -= alt_path.size();
removed_bubble = true;
}
}
}
} else {
/*
-> ref -> ref -> ref -> ref ->
/ / \
ref -> alt -> -> alt ref
\ / /
-> alt* -> alt -> alt -> alt ->
*/
const auto bifurication_point = *bifurication_point_itr;
alt_path.erase(std::cbegin(alt_path), std::next(bifurication_point_itr));
if (alt_path.empty()) {
remove_edge(bifurication_point, ref);
} else {
remove_path(alt_path);
}
regenerate_vertex_indices();
set_all_edge_transition_scores_from(bifurication_point);
num_remaining_alt_kmers -= alt_path.size();
removed_bubble = true;
}
}
}
unsigned kmer_count_to_alt;
std::tie(alt, ref, kmer_count_to_alt) = backtrack_until_nonreference(predecessors, ref_before_bubble);
rhs_kmer_count += kmer_count_to_alt;
if (!use_weights && k > 0) --k;
}
if (!removed_bubble && use_weights) {
if (can_prune_reference_flanks()) {
prune_reference_flanks();
regenerate_vertex_indices();
}
utils::append(extract_bubble_paths_with_ksp(k, min_bubble_scorer), result);
return result;
} else if (!removed_bubble) {
use_weights = true;
}
assert(boost::out_degree(reference_head(), graph_) > 0);
assert(boost::in_degree(reference_tail(), graph_) > 0);
if (can_prune_reference_flanks()) {
prune_reference_flanks();
regenerate_vertex_indices();
}
}
return result;
}
std::deque<Assembler::SubGraph> Assembler::find_independent_subgraphs() const
{
assert(!reference_vertices_.empty());
const auto diverges = [this] (const Vertex& v) { return boost::out_degree(v, graph_) > 1; };
const auto coalesces = [this] (const Vertex& v) { return boost::in_degree(v, graph_) > 1; };
auto subgraph_head_itr = std::find_if(std::cbegin(reference_vertices_), std::cend(reference_vertices_), diverges);
if (subgraph_head_itr == std::cend(reference_vertices_)) {
return {{reference_head(), reference_tail(), 0}};
}
auto candidate_subgraph_tail_itr = std::find_if(subgraph_head_itr, std::cend(reference_vertices_), coalesces);
if (candidate_subgraph_tail_itr == std::cend(reference_vertices_)) {
return {{reference_head(), reference_tail(), 0}};
} else {
std::deque<Vertex> coalescent_points {*candidate_subgraph_tail_itr};
std::copy_if(std::next(candidate_subgraph_tail_itr), std::cend(reference_vertices_),
std::front_inserter(coalescent_points), coalesces);
const auto dominator = build_dominator_tree(reference_head());
std::deque<SubGraph> result {};
while (subgraph_head_itr != std::cend(reference_vertices_)) {
auto subbgraph_end = std::find_if(std::cbegin(coalescent_points), std::cend(coalescent_points),
[&] (const Vertex& v) { return dominator.at(v) == *subgraph_head_itr; });
assert(subbgraph_end != std::cend(coalescent_points));
auto subgraph_offset = static_cast<std::size_t>(std::distance(std::cbegin(reference_vertices_), subgraph_head_itr));
result.push_back({*subgraph_head_itr, *subbgraph_end, subgraph_offset});
subgraph_head_itr = std::find_if(std::find(subgraph_head_itr, std::cend(reference_vertices_), *subbgraph_end),
std::cend(reference_vertices_), diverges);
coalescent_points.erase(subbgraph_end, std::cend(coalescent_points));
}
return result;
}
}
std::deque<Assembler::Variant> Assembler::extract_bubble_paths_with_ksp(const unsigned k, const BubbleScoreSetter min_bubble_scorer)
{
const auto subgraphs = find_independent_subgraphs();
std::deque<Variant> result {};
for (const auto& subgraph : subgraphs) {
auto shortest_paths = extract_k_shortest_paths(subgraph.head, subgraph.tail, k);
for (const auto& path : shortest_paths) {
assert(!path.empty());
const auto is_alt_edge = [this] (const Edge e) { return !is_reference(e); };
auto alt_head_itr = std::find_if(std::cbegin(path), std::cend(path), is_alt_edge);
auto lhs_kmer_count = std::distance(std::cbegin(path), alt_head_itr);
while (alt_head_itr != std::cend(path)) {
const auto ref_before_bubble = boost::source(*alt_head_itr, graph_);
assert(is_reference(ref_before_bubble));
const auto alt_tail_itr = std::find_if(alt_head_itr, std::cend(path), [this] (Edge e) { return is_target_reference(e); });
assert(alt_tail_itr != std::cend(path));
const auto ref_after_bubble = boost::target(*alt_tail_itr, graph_);
assert(!is_reference(*alt_tail_itr));
assert(is_reference(ref_after_bubble));
auto ref_seq = make_reference(ref_before_bubble, ref_after_bubble);
Path alt_path {};
std::transform(alt_head_itr, std::next(alt_tail_itr), std::back_inserter(alt_path),
[this] (Edge e) { return boost::source(e, graph_); });
const auto num_ref_kmers = count_kmers(ref_seq, kmer_size());
const auto min_bubble_score = get_min_bubble_score(ref_before_bubble, ref_after_bubble, min_bubble_scorer);
const auto score = bubble_score(alt_path);
if (score >= min_bubble_score) {
auto alt_seq = make_sequence(alt_path);
const auto pos = reference_head_position_ + subgraph.reference_offset + lhs_kmer_count;
result.emplace_front(pos, std::move(ref_seq), std::move(alt_seq));
}
alt_head_itr = std::find_if(std::next(alt_tail_itr), std::cend(path), is_alt_edge);
lhs_kmer_count += num_ref_kmers + std::distance(alt_tail_itr, alt_head_itr) - 1;
}
}
}
return result;
}
// debug
std::ostream& operator<<(std::ostream& os, const Assembler::Kmer& kmer)
{
std::copy(std::cbegin(kmer), std::cend(kmer), std::ostreambuf_iterator<char> {os});
return os;
}
void Assembler::print_reference_head() const
{
std::cout << "reference head is " << kmer_of(reference_head()) << std::endl;
}
void Assembler::print_reference_tail() const
{
std::cout << "reference tail is " << kmer_of(reference_tail()) << std::endl;
}
void Assembler::print_reference_path() const
{
print(reference_vertices_);
}
void Assembler::print(const Edge e) const
{
std::cout << kmer_of(boost::source(e, graph_)) << "->" << kmer_of(boost::target(e, graph_));
}
void Assembler::print(const Path& path) const
{
assert(!path.empty());
std::transform(std::cbegin(path), std::prev(std::cend(path)), std::ostream_iterator<Kmer> {std::cout, "->"},
[this] (const Vertex v) { return kmer_of(v); });
std::cout << kmer_of(path.back());
}
void Assembler::print_verbose(const Path& path) const
{
if (path.size() < 2) return;
std::transform(std::cbegin(path), std::prev(std::cend(path)), std::next(std::cbegin(path)),
std::ostream_iterator<std::string> {std::cout, "->"},
[this] (const auto& u, const auto& v) {
Edge e; bool good;
std::tie(e, good) = boost::edge(u, v, graph_);
assert(good);
auto result = static_cast<std::string>(this->kmer_of(v));
result += "(";
result += std::to_string(graph_[e].weight);
result += ", " + std::to_string(graph_[e].forward_strand_weight);
result += ", " + std::to_string(graph_[e].base_quality_sum);
result += ")";
return result;
});
std::cout << kmer_of(path.back());
}
void Assembler::print_dominator_tree() const
{
const auto dom_tree = build_dominator_tree(reference_head());
for (const auto& p : dom_tree) {
std::cout << kmer_of(p.first) << " dominated by " << kmer_of(p.second) << std::endl;
}
}
// non-member methods
bool operator==(const Assembler::Variant& lhs, const Assembler::Variant& rhs) noexcept
{
return lhs.begin_pos == rhs.begin_pos && lhs.ref.size() == rhs.ref.size() && lhs.alt == rhs.alt;
}
} // namespace coretools
} // namespace octopus
| 39.324589 | 138 | 0.600954 | Schaudge |
6d44e96700a7f0444704bd6eef5380e1b426b2cf | 604 | cpp | C++ | src/main/driver/cpp/adiIMUJNI.cpp | juchong/adi_frc_imu | 1558fdecb5b3f1fb721a01832dcfbf15a69c4161 | [
"MIT"
] | 1 | 2021-02-05T05:44:39.000Z | 2021-02-05T05:44:39.000Z | src/main/driver/cpp/adiIMUJNI.cpp | juchong/adi_frc_imu | 1558fdecb5b3f1fb721a01832dcfbf15a69c4161 | [
"MIT"
] | null | null | null | src/main/driver/cpp/adiIMUJNI.cpp | juchong/adi_frc_imu | 1558fdecb5b3f1fb721a01832dcfbf15a69c4161 | [
"MIT"
] | null | null | null | #include "jni.h"
#include "com_analogdevices_jni_adiIMUJNI.h"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
// Check to ensure the JNI version is valid
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
return JNI_ERR;
// In here is also where you store things like class references
// if they are ever needed
return JNI_VERSION_1_6;
}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {}
JNIEXPORT jint JNICALL Java_com_analogdevices_jni_adiIMUJNI_initialize
(JNIEnv *, jclass) {
return 0;
}
| 26.26087 | 78 | 0.72351 | juchong |
6d47aa5057d2788d2549fcf98748fef0ff03e7b0 | 595 | hpp | C++ | src/Evolution/Systems/NewtonianEuler/Sources/NoSource.hpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 2 | 2021-04-11T04:07:42.000Z | 2021-04-11T05:07:54.000Z | src/Evolution/Systems/NewtonianEuler/Sources/NoSource.hpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 4 | 2018-06-04T20:26:40.000Z | 2018-07-27T14:54:55.000Z | src/Evolution/Systems/NewtonianEuler/Sources/NoSource.hpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 1 | 2019-01-03T21:47:04.000Z | 2019-01-03T21:47:04.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include "Utilities/TMPL.hpp"
/// \cond
namespace PUP {
class er;
} // namespace PUP
/// \endcond
namespace NewtonianEuler {
namespace Sources {
/*!
* \brief Used to mark that the initial data do not require source
* terms in the evolution equations.
*/
struct NoSource {
using sourced_variables = tmpl::list<>;
using argument_tags = tmpl::list<>;
// clang-tidy: google-runtime-references
void pup(PUP::er& /*p*/) noexcept {} // NOLINT
};
} // namespace Sources
} // namespace NewtonianEuler
| 20.517241 | 66 | 0.694118 | macedo22 |
6d47da4f8881a41c3345d4108f5037603516e42a | 697 | cpp | C++ | leetcode/557.cpp | lizheng3401/ALG | 55d1da810c627b3a23652423c35ef6baa7bfad41 | [
"MIT"
] | null | null | null | leetcode/557.cpp | lizheng3401/ALG | 55d1da810c627b3a23652423c35ef6baa7bfad41 | [
"MIT"
] | null | null | null | leetcode/557.cpp | lizheng3401/ALG | 55d1da810c627b3a23652423c35ef6baa7bfad41 | [
"MIT"
] | null | null | null | #include <string>
#include <algorithm>
#include <iostream>
string reverseWords(string s) {
string S, temp;
for(int i = 0; i < s.size(); ++i)
{
if(s[i] == ' ' || i == s.size() - 1)
{
if(i != s.size() - 1)
{
reverse(temp.begin(), temp.end());
S += temp+" ";
}
else
{
temp = temp+s[i];
reverse(temp.begin(), temp.end());
S += temp;
}
temp = "";
continue;
}
temp += s[i];
}
return S;
}
int main()
{
cout << reverseWords("Let's take LeetCode contest");
return 0;
} | 20.5 | 56 | 0.377331 | lizheng3401 |
6d49f7b5bcd462bde57e362a57672d9f0683f151 | 1,748 | hpp | C++ | source/bounded/string_view.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | source/bounded/string_view.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | source/bounded/string_view.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2017.
// 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)
#include <bounded/detail/comparison.hpp>
#include "../test_assert.hpp"
namespace bounded_test {
// Add in some asserts and manually make special member functions non-trivial
struct string_view {
constexpr string_view(char const * value_):
value(value_) {
}
constexpr string_view(string_view const & other):
value(other.value)
{
BOUNDED_TEST(not other.moved_from);
}
constexpr auto & operator=(string_view const & other) {
BOUNDED_TEST(not other.moved_from);
value = other.value;
moved_from = false;
return *this;
}
constexpr string_view(string_view && other) noexcept:
value(other.value)
{
BOUNDED_TEST(not other.moved_from);
other.moved_from = true;
}
constexpr auto & operator=(string_view && other) noexcept {
BOUNDED_TEST(not other.moved_from);
value = other.value;
moved_from = false;
other.moved_from = true;
return *this;
}
friend constexpr auto operator<=>(string_view lhs, string_view rhs) {
BOUNDED_TEST(not lhs.moved_from and not rhs.moved_from);
while (true) {
if (auto const cmp = *lhs.value <=> *rhs.value; cmp != 0 or *lhs.value == '\0') {
return cmp;
}
++lhs.value;
++rhs.value;
}
}
friend constexpr auto operator==(string_view lhs, string_view rhs) -> bool {
BOUNDED_TEST(not lhs.moved_from and not rhs.moved_from);
while (true) {
if (*lhs.value != *rhs.value) {
return false;
}
if (*lhs.value == '\0') {
return true;
}
++lhs.value;
++rhs.value;
}
}
private:
char const * value;
bool moved_from = false;
};
} // namespace bounded_test
| 24.619718 | 84 | 0.689359 | davidstone |
6d4b1d5bde216d4f953728feb9acd59a7d10fa89 | 378 | hpp | C++ | src/motorcycle.hpp | TralahM/ParkingLotSystem | 0add5d8581505a086f1eee4074dac1c377fd07fd | [
"MIT"
] | null | null | null | src/motorcycle.hpp | TralahM/ParkingLotSystem | 0add5d8581505a086f1eee4074dac1c377fd07fd | [
"MIT"
] | null | null | null | src/motorcycle.hpp | TralahM/ParkingLotSystem | 0add5d8581505a086f1eee4074dac1c377fd07fd | [
"MIT"
] | null | null | null | #ifndef __MOTORCYCLE
#define __MOTORCYCLE
#include "vehicle.hpp"
/*! \class Motorcycle : public Vehicle
* \brief Brief class description
*
* Detailed description
*/
class Motorcycle : public Vehicle
{
public:
Motorcycle(const std::string& plate, Color color):Vehicle{plate,color}{}
~Motorcycle(){}
protected:
Size size=S;
};
#endif /* ifndef __MOTORCYCLE */
| 18.9 | 76 | 0.706349 | TralahM |
6d4c10e41dea9747d048487c426d0f3976b904ae | 1,647 | cpp | C++ | src/syntax/AST/Equals.cpp | pougetat/decacompiler | 3181c87fce7c28d742f372300daabeb9f9f8d3c6 | [
"MIT"
] | null | null | null | src/syntax/AST/Equals.cpp | pougetat/decacompiler | 3181c87fce7c28d742f372300daabeb9f9f8d3c6 | [
"MIT"
] | null | null | null | src/syntax/AST/Equals.cpp | pougetat/decacompiler | 3181c87fce7c28d742f372300daabeb9f9f8d3c6 | [
"MIT"
] | null | null | null | #include "Equals.h"
Equals::Equals(AbstractExpr * e1, AbstractExpr * e2)
{
m_left_operand = e1;
m_right_operand = e2;
}
AbstractExpr * Equals::Clone()
{
return new Equals(
m_left_operand->Clone(),
m_right_operand->Clone()
);
}
void Equals::Display(string tab)
{
cout << tab << ">" << "[EQUALS]" << endl;
m_left_operand->Display(tab + "--");
m_right_operand->Display(tab + "--");
}
void Equals::CodeGenExpr(
EnvironmentType * env_types,
GeneratorEnvironment * gen_env)
{
m_left_operand->CodeGenExpr(env_types, gen_env);
m_right_operand->CodeGenExpr(env_types, gen_env);
string branch_instruct = "";
if (m_left_operand->m_expr_type->IsClassType())
{
branch_instruct = "if_acmpne";
}
if (m_left_operand->m_expr_type->IsIntType())
{
branch_instruct = "if_icmpne";
}
if (m_left_operand->m_expr_type->IsFloatType())
{
gen_env->output_file << " fcmpl" << endl;
return;
}
int label_num = gen_env->GetNewLabel();
gen_env->output_file
<< " "
<< branch_instruct << " label" << label_num << ".false" << endl;
gen_env->output_file << " goto label" << label_num << ".true" << endl;
gen_env->output_file << " label" << label_num << ".true:" << endl;
gen_env->output_file << " bipush 1" << endl;
gen_env->output_file << " goto endlabel" << label_num << endl;
gen_env->output_file << " label" << label_num << ".false:" << endl;
gen_env->output_file << " bipush 0" << endl;
gen_env->output_file << " endlabel" << label_num << ":" << endl;
} | 27.915254 | 77 | 0.592593 | pougetat |
6d4d162d11686fb958bece3cb012243925b451a1 | 1,046 | cpp | C++ | parkgates.cpp | whit1206/Themepark-Animation | 2167b698e3b86273d6c2ec03cb1ed0d70e4f01d0 | [
"Unlicense"
] | null | null | null | parkgates.cpp | whit1206/Themepark-Animation | 2167b698e3b86273d6c2ec03cb1ed0d70e4f01d0 | [
"Unlicense"
] | null | null | null | parkgates.cpp | whit1206/Themepark-Animation | 2167b698e3b86273d6c2ec03cb1ed0d70e4f01d0 | [
"Unlicense"
] | null | null | null | #include "parkgates.h"
#include "eventscheduler.h"
#include "globals.h"
ParkGates::ParkGates() {
visitorCount = 0;
}
void ParkGates::open() {
// create a kick-off event
generateNewEvent(1);
// go!
scheduler->run();
}
void ParkGates::paint(GP142Display& display) const {
display.write(-290, -220, "Park occupancy: ", Black, FONT_SIZE);
display.write(-200, -220, visitorCount, Black, FONT_SIZE);
}
void ParkGates::acceptVisitor(Visitor* v) {
// v is leaving
delete v;
visitorCount--;
}
void ParkGates::handleEvent(const Event&) {
if (visitorCount < MAX_PARK_OCCUPANCY) {
// time to send in another visitor
admitOne();
} // else the angry visitor goes back home
int t = generateRandomNumber(AVG_VISITOR_INTERVAL);
generateNewEvent(t);
}
void ParkGates::admitOne() {
char name = generateRandomChar();
bool is_female = generateRandomBool(.5);
Visitor* v = new Visitor(name, scheduler->getCurrentTime(), is_female);
passVisitor(v);
visitorCount++;
} | 18.350877 | 73 | 0.664436 | whit1206 |
6d4f87e32ba23587f8382c9a055ae4af79ea382b | 4,403 | cpp | C++ | igl/isolines.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | igl/isolines.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | igl/isolines.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2017 Oded Stein <oded.stein@columbia.edu>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "isolines.h"
#include <vector>
#include <array>
#include <iostream>
#include "remove_duplicate_vertices.h"
template <typename DerivedV,
typename DerivedF,
typename DerivedZ,
typename DerivedIsoV,
typename DerivedIsoE>
IGL_INLINE void igl::isolines(
const Eigen::MatrixBase<DerivedV>& V,
const Eigen::MatrixBase<DerivedF>& F,
const Eigen::MatrixBase<DerivedZ>& z,
const int n,
Eigen::PlainObjectBase<DerivedIsoV>& isoV,
Eigen::PlainObjectBase<DerivedIsoE>& isoE)
{
//Constants
const int dim = V.cols();
assert(dim==2 || dim==3);
const int nVerts = V.rows();
assert(z.rows() == nVerts &&
"There must be as many function entries as vertices");
const int nFaces = F.rows();
const int np1 = n+1;
const double min = z.minCoeff(), max = z.maxCoeff();
//Following http://www.alecjacobson.com/weblog/?p=2529
typedef typename DerivedZ::Scalar Scalar;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vec;
Vec iso(np1);
for(int i=0; i<np1; ++i)
iso(i) = Scalar(i)/Scalar(n)*(max-min) + min;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;
std::array<Matrix,3> t{{Matrix(nFaces, np1),
Matrix(nFaces, np1), Matrix(nFaces, np1)}};
for(int i=0; i<nFaces; ++i) {
for(int k=0; k<3; ++k) {
const Scalar z1=z(F(i,k)), z2=z(F(i,(k+1)%3));
for(int j=0; j<np1; ++j) {
t[k](i,j) = (iso(j)-z1) / (z2-z1);
if(t[k](i,j)<0 || t[k](i,j)>1)
t[k](i,j) = std::numeric_limits<Scalar>::quiet_NaN();
}
}
}
std::array<std::vector<int>,3> Fij, Iij;
for(int i=0; i<nFaces; ++i) {
for(int j=0; j<np1; ++j) {
for(int k=0; k<3; ++k) {
const int kp1=(k+1)%3, kp2=(k+2)%3;
if(std::isfinite(t[kp1](i,j)) && std::isfinite(t[kp2](i,j))) {
Fij[k].push_back(i);
Iij[k].push_back(j);
}
}
}
}
const int K = Fij[0].size()+Fij[1].size()+Fij[2].size();
isoV.resize(2*K, dim);
int b = 0;
for(int k=0; k<3; ++k) {
const int kp1=(k+1)%3, kp2=(k+2)%3;
for(int i=0; i<Fij[k].size(); ++i) {
isoV.row(b+i) = (1.-t[kp1](Fij[k][i],Iij[k][i]))*
V.row(F(Fij[k][i],kp1)) +
t[kp1](Fij[k][i],Iij[k][i])*V.row(F(Fij[k][i],kp2));
isoV.row(K+b+i) = (1.-t[kp2](Fij[k][i],Iij[k][i]))*
V.row(F(Fij[k][i],kp2)) +
t[kp2](Fij[k][i],Iij[k][i])*V.row(F(Fij[k][i],k));
}
b += Fij[k].size();
}
isoE.resize(K,2);
for(int i=0; i<K; ++i)
isoE.row(i) << i, K+i;
//Remove double entries
typedef typename DerivedIsoV::Scalar LScalar;
typedef typename DerivedIsoE::Scalar LInt;
typedef Eigen::Matrix<LInt, Eigen::Dynamic, 1> LIVec;
typedef Eigen::Matrix<LScalar, Eigen::Dynamic, Eigen::Dynamic> LMat;
typedef Eigen::Matrix<LInt, Eigen::Dynamic, Eigen::Dynamic> LIMat;
LIVec dummy1, dummy2;
igl::remove_duplicate_vertices(LMat(isoV), LIMat(isoE),
2.2204e-15, isoV, dummy1, dummy2, isoE);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
template void igl::isolines<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, int const, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > &, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > &);
#endif
| 37.632479 | 579 | 0.53509 | aviadtzemah |
6d4fb23ff4fdea206d4effd547e8f27dc2d5bb16 | 1,131 | hpp | C++ | ODFAEG/extlibs/headers/MySQL/conncpp/compat/Array.hpp | Mechap/ODFAEG | ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40 | [
"Zlib"
] | null | null | null | ODFAEG/extlibs/headers/MySQL/conncpp/compat/Array.hpp | Mechap/ODFAEG | ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40 | [
"Zlib"
] | 1 | 2020-02-14T14:19:44.000Z | 2020-12-04T17:39:17.000Z | ODFAEG/extlibs/headers/MySQL/conncpp/compat/Array.hpp | Mechap/ODFAEG | ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40 | [
"Zlib"
] | 2 | 2021-05-23T13:45:28.000Z | 2021-07-24T13:36:13.000Z | /*
*
* MariaDB C++ Connector
*
* Copyright (c) 2020 MariaDB Ab.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not see <http://www.gnu.org/licenses>
* or write to the Free Software Foundation, Inc.,
* 51 Franklin St., Fifth Floor, Boston, MA 02110, USA
*
*/
#ifndef _ARRAY_H_
#define _ARRAY_H_
/* Stub class for the interface, that is used in one of methods for the non-implemented functionality. */
namespace sql
{
class Array{
Array(const Array&);
void operator=(Array &);
public:
Array() {}
virtual ~Array(){}
};
}
#endif
| 29.763158 | 105 | 0.721485 | Mechap |
6d4fcca6ae7254b98ab1e7db63f9ddf6aa8f7077 | 7,268 | hpp | C++ | include/System/Resources/ManifestBasedResourceGroveler.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/System/Resources/ManifestBasedResourceGroveler.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/System/Resources/ManifestBasedResourceGroveler.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Resources.IResourceGroveler
#include "System/Resources/IResourceGroveler.hpp"
// Including type: System.Resources.ResourceManager
#include "System/Resources/ResourceManager.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Globalization
namespace System::Globalization {
// Forward declaring type: CultureInfo
class CultureInfo;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: Assembly
class Assembly;
}
// Forward declaring namespace: System::Resources
namespace System::Resources {
// Skipping declaration: UltimateResourceFallbackLocation because it is already included!
}
// Completed forward declares
// Type namespace: System.Resources
namespace System::Resources {
// Forward declaring type: ManifestBasedResourceGroveler
class ManifestBasedResourceGroveler;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Resources::ManifestBasedResourceGroveler);
DEFINE_IL2CPP_ARG_TYPE(::System::Resources::ManifestBasedResourceGroveler*, "System.Resources", "ManifestBasedResourceGroveler");
// Type namespace: System.Resources
namespace System::Resources {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.Resources.ManifestBasedResourceGroveler
// [TokenAttribute] Offset: FFFFFFFF
class ManifestBasedResourceGroveler : public ::Il2CppObject/*, public ::System::Resources::IResourceGroveler*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.Resources.ResourceManager/System.Resources.ResourceManagerMediator _mediator
// Size: 0x8
// Offset: 0x10
::System::Resources::ResourceManager::ResourceManagerMediator* mediator;
// Field size check
static_assert(sizeof(::System::Resources::ResourceManager::ResourceManagerMediator*) == 0x8);
public:
// Creating interface conversion operator: operator ::System::Resources::IResourceGroveler
operator ::System::Resources::IResourceGroveler() noexcept {
return *reinterpret_cast<::System::Resources::IResourceGroveler*>(this);
}
// Creating conversion operator: operator ::System::Resources::ResourceManager::ResourceManagerMediator*
constexpr operator ::System::Resources::ResourceManager::ResourceManagerMediator*() const noexcept {
return mediator;
}
// Get instance field reference: private System.Resources.ResourceManager/System.Resources.ResourceManagerMediator _mediator
::System::Resources::ResourceManager::ResourceManagerMediator*& dyn__mediator();
// public System.Void .ctor(System.Resources.ResourceManager/System.Resources.ResourceManagerMediator mediator)
// Offset: 0xECB434
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ManifestBasedResourceGroveler* New_ctor(::System::Resources::ResourceManager::ResourceManagerMediator* mediator) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Resources::ManifestBasedResourceGroveler::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ManifestBasedResourceGroveler*, creationType>(mediator)));
}
// static System.Globalization.CultureInfo GetNeutralResourcesLanguage(System.Reflection.Assembly a, ref System.Resources.UltimateResourceFallbackLocation fallbackLocation)
// Offset: 0xECB460
static ::System::Globalization::CultureInfo* GetNeutralResourcesLanguage(::System::Reflection::Assembly* a, ByRef<::System::Resources::UltimateResourceFallbackLocation> fallbackLocation);
// static private System.Boolean GetNeutralResourcesLanguageAttribute(System.Reflection.Assembly assembly, ref System.String cultureName, ref System.Int16 fallbackLocation)
// Offset: 0xECB7D8
static bool GetNeutralResourcesLanguageAttribute(::System::Reflection::Assembly* assembly, ByRef<::StringW> cultureName, ByRef<int16_t> fallbackLocation);
}; // System.Resources.ManifestBasedResourceGroveler
#pragma pack(pop)
static check_size<sizeof(ManifestBasedResourceGroveler), 16 + sizeof(::System::Resources::ResourceManager::ResourceManagerMediator*)> __System_Resources_ManifestBasedResourceGrovelerSizeCheck;
static_assert(sizeof(ManifestBasedResourceGroveler) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Resources::ManifestBasedResourceGroveler::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Resources::ManifestBasedResourceGroveler::GetNeutralResourcesLanguage
// Il2CppName: GetNeutralResourcesLanguage
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Globalization::CultureInfo* (*)(::System::Reflection::Assembly*, ByRef<::System::Resources::UltimateResourceFallbackLocation>)>(&System::Resources::ManifestBasedResourceGroveler::GetNeutralResourcesLanguage)> {
static const MethodInfo* get() {
static auto* a = &::il2cpp_utils::GetClassFromName("System.Reflection", "Assembly")->byval_arg;
static auto* fallbackLocation = &::il2cpp_utils::GetClassFromName("System.Resources", "UltimateResourceFallbackLocation")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Resources::ManifestBasedResourceGroveler*), "GetNeutralResourcesLanguage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{a, fallbackLocation});
}
};
// Writing MetadataGetter for method: System::Resources::ManifestBasedResourceGroveler::GetNeutralResourcesLanguageAttribute
// Il2CppName: GetNeutralResourcesLanguageAttribute
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Reflection::Assembly*, ByRef<::StringW>, ByRef<int16_t>)>(&System::Resources::ManifestBasedResourceGroveler::GetNeutralResourcesLanguageAttribute)> {
static const MethodInfo* get() {
static auto* assembly = &::il2cpp_utils::GetClassFromName("System.Reflection", "Assembly")->byval_arg;
static auto* cultureName = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg;
static auto* fallbackLocation = &::il2cpp_utils::GetClassFromName("System", "Int16")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Resources::ManifestBasedResourceGroveler*), "GetNeutralResourcesLanguageAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{assembly, cultureName, fallbackLocation});
}
};
| 60.566667 | 289 | 0.780545 | RedBrumbler |
6d504cce8af2f9b1d71156ebebbb2898eeaedca5 | 1,835 | cpp | C++ | 3D Engine/Inspector.cpp | ofaura/Resonance-Engine | 129b94d38f32b3b34a9dd95c5ee5a2adf064da92 | [
"MIT"
] | null | null | null | 3D Engine/Inspector.cpp | ofaura/Resonance-Engine | 129b94d38f32b3b34a9dd95c5ee5a2adf064da92 | [
"MIT"
] | null | null | null | 3D Engine/Inspector.cpp | ofaura/Resonance-Engine | 129b94d38f32b3b34a9dd95c5ee5a2adf064da92 | [
"MIT"
] | null | null | null | #include "Inspector.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "ModuleSceneIntro.h"
#include "GameObject.h"
#include "mmgr/mmgr.h"
Inspector::Inspector(bool is_visible) : EditorElement(is_visible) {}
Inspector::~Inspector() {}
void Inspector::Start()
{
}
void Inspector::Draw()
{
if (!active) return;
ImGui::Begin("Inspector", &active, ImGuiWindowFlags_AlwaysAutoResize);
if (App->scene_intro->goSelected != nullptr)
{
GameObject* Selected = App->scene_intro->goSelected;
ImGui::BeginChild("child", ImVec2(0, 35), true);
ImGui::Checkbox(" ", &App->scene_intro->goSelected->enable);
ImGui::SameLine();
static char name[100] = "";
strcpy_s(name, 100, Selected->GetName());
if (ImGui::InputText("", name, 100, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll))
{
//Selected->SetName(name);
changedName = true;
}
if (changedName)
{
int count = 0;
string final_name = name;
string num;
for (int i = 0; i < App->scene_intro->root->children.size(); i++)
{
if (App->scene_intro->root->children[i] != Selected)
{
if (strcmp(App->scene_intro->root->children[i]->name.c_str(), name) == 0)
{
count++;
//final_name = strcat(name, "(");
//num = std::to_string(count);
//final_name = strcat_s(name, num.c_str());
//final_name = strcat(name, ")");
}
}
}
if (count != 0)
{
final_name = strcat(name, "(");
num = std::to_string(count);
final_name = strcat_s(name, num.c_str());
final_name = strcat(name, ")");
}
//name = App->scene_intro->SetAvailableName(name);
Selected->SetName(final_name.c_str());
changedName = false;
}
ImGui::EndChild();
App->scene_intro->goSelected->DrawInspector();
}
ImGui::End();
}
void Inspector::CleanUp()
{
}
| 21.588235 | 112 | 0.633787 | ofaura |
6d5218c045ba2eb49984a3a28abdbe905c3186ac | 7,498 | cpp | C++ | EvtGen1_06_00/src/EvtGenModels/EvtBtoXsgammaFermiUtil.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | EvtGen1_06_00/src/EvtGenModels/EvtBtoXsgammaFermiUtil.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | EvtGen1_06_00/src/EvtGenModels/EvtBtoXsgammaFermiUtil.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------
//
//
// Copyright Information: See EvtGen/COPYRIGHT
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Module: EvtBtoXsgammaFermiUtil.cc
//
// Description:
// Class to hold various fermi functions and their helper functions. The
// fermi functions are used in EvtBtoXsgammaKagan.
//
// Modification history:
//
// Jane Tinslay March 21, 2001 Module created
//------------------------------------------------------------------------
#include "EvtGenBase/EvtPatches.hh"
//-----------------------
// This Class's Header --
//-----------------------
#include "EvtGenModels/EvtBtoXsgammaFermiUtil.hh"
#include "EvtGenModels/EvtItgTwoCoeffFcn.hh"
#include "EvtGenModels/EvtBtoXsgammaRootFinder.hh"
#include "EvtGenModels/EvtItgFunction.hh"
#include "EvtGenBase/EvtConst.hh"
#include "EvtGenBase/EvtReport.hh"
//---------------
// C++ Headers --
//---------------
#include <iostream>
#include <math.h>
using std::endl;
double EvtBtoXsgammaFermiUtil::FermiExpFunc(double y, const std::vector<double> &coeffs) {
//coeffs: 1 = lambdabar, 2 = a, 3 = lam1, 4 = norm
// EvtGenReport(EVTGEN_INFO,"EvtGen")<<coeffs[4]<<endl;
return (pow(1. - (y/coeffs[1]),coeffs[2])*exp((-3.*pow(coeffs[1],2.)/coeffs[3])*y/coeffs[1]))/coeffs[4];
}
double EvtBtoXsgammaFermiUtil::FermiGaussFunc(double y, const std::vector<double> &coeffs) {
//coeffs: 1 = lambdabar, 2 = a, 3 = c, 4 = norm
return (pow(1. - (y/coeffs[1]),coeffs[2])*exp(-pow(coeffs[3],2.)*pow(1. - (y/coeffs[1]),2.)))/coeffs[4];
}
double EvtBtoXsgammaFermiUtil::FermiGaussFuncRoot(double lambdabar, double lam1, double mb, std::vector<double> &gammaCoeffs) {
std::vector<double> coeffs1(3);
std::vector<double> coeffs2(3);
coeffs1[0]=0.2;
coeffs1[1]=lambdabar;
coeffs1[2]=0.0;
coeffs2[0]=0.2;
coeffs2[1]=lambdabar;
coeffs2[2]=-lam1/3.;
EvtItgTwoCoeffFcn *lhFunc = new EvtItgTwoCoeffFcn(&FermiGaussRootFcnA, -mb, lambdabar, coeffs1, gammaCoeffs);
EvtItgTwoCoeffFcn *rhFunc = new EvtItgTwoCoeffFcn(&FermiGaussRootFcnB, -mb, lambdabar, coeffs2, gammaCoeffs);
EvtBtoXsgammaRootFinder *rootFinder = new EvtBtoXsgammaRootFinder();
double root = rootFinder->GetGaussIntegFcnRoot(lhFunc, rhFunc, 1.0e-4, 1.0e-4, 40, 40, -mb, lambdabar, 0.2, 0.4, 1.0e-6);
delete rootFinder; rootFinder=0;
delete lhFunc; lhFunc=0;
delete rhFunc; rhFunc=0;
return root;
}
double EvtBtoXsgammaFermiUtil::FermiGaussRootFcnA(double y, const std::vector<double> &coeffs1, const std::vector<double> &coeffs2) {
//coeffs1: 0=ap, 1=lambdabar, coeffs2=gamma function coeffs
double cp = Gamma((2.0 + coeffs1[0])/2., coeffs2)/Gamma((1.0 + coeffs1[0])/2., coeffs2);
return (y*y)*pow((1. - (y/coeffs1[1])),coeffs1[0])*exp(-pow(cp,2)*pow((1.-(y/coeffs1[1])),2.));
}
double EvtBtoXsgammaFermiUtil::FermiGaussRootFcnB(double y, const std::vector<double> &coeffs1, const std::vector<double> &coeffs2) {
//coeffs1: 0=ap, 1=lambdabar, coeffs2=gamma function coeffs
double cp = Gamma((2.0 + coeffs1[0])/2., coeffs2)/Gamma((1.0 + coeffs1[0])/2., coeffs2);
return pow((1. - (y/coeffs1[1])),coeffs1[0])*exp(-pow(cp,2)*pow((1.-(y/coeffs1[1])),2.));
}
double EvtBtoXsgammaFermiUtil::Gamma(double z, const std::vector<double> &coeffs) {
//Lifted from Numerical Recipies in C
double x, y, tmp, ser;
int j;
y = z;
x = z;
tmp = x + 5.5;
tmp = tmp - (x+0.5)*log(tmp);
ser=1.000000000190015;
for (j=0;j<6;j++) {
y = y +1.0;
ser = ser + coeffs[j]/y;
}
return exp(-tmp+log(2.5066282746310005*ser/x));
}
double EvtBtoXsgammaFermiUtil::BesselK1(double x) {
//Lifted from Numerical Recipies in C : Returns the modified Bessel
//function K_1(x) for positive real x
if (x<0.0) EvtGenReport(EVTGEN_INFO,"EvtGen") <<"x is negative !"<<endl;
double y, ans;
if (x <= 2.0) {
y=x*x/4.0;
ans = (log(x/2.0)*BesselI1(x))+(1.0/x)*(1.0+y*(0.15443144+y*(-0.67278579+y*(-0.18156897+y*(-0.1919402e-1+y*(-0.110404e-2+y*(-0.4686e-4)))))));
}
else {
y=2.0/x;
ans=(exp(-x)/sqrt(x))*(1.25331414+y*(0.23498619+y*(-0.3655620e-1+y*(0.1504268e-1+y*(-0.780353e-2+y*(0.325614e-2+y*(-0.68245e-3)))))));
}
return ans;
}
double EvtBtoXsgammaFermiUtil::BesselI1(double x) {
//Lifted from Numerical Recipies in C : Returns the modified Bessel
//function I_1(x) for any real x
double ax, ans;
double y;
ax=fabs(x);
if ( ax < 3.75) {
y=x/3.75;
y*=y;
ans=ax*(0.5+y*(0.87890594+y*(0.51498869+y*(0.15084934+y*(0.2658733e-1+y*(0.301532e-2+y*0.32411e-3))))));
}
else {
y=3.75/ax;
ans=0.2282967e-1+y*(-0.2895312e-1+y*(0.1787654e-1 -y*0.420059e-2));
ans=0.398914228+y*(-0.3988024e-1+y*(-0.362018e-2+y*(0.163801e-2+y*(-0.1031555e-1+y*ans))));
ans*=(exp(ax)/sqrt(ax));
}
return x < 0.0 ? -ans:ans;
}
double EvtBtoXsgammaFermiUtil::FermiRomanFuncRoot(double lambdabar, double lam1) {
EvtItgFunction *lhFunc = new EvtItgFunction(&FermiRomanRootFcnA, -1.e-6, 1.e6);
EvtBtoXsgammaRootFinder *rootFinder = new EvtBtoXsgammaRootFinder();
double rhSide = 1.0 - (lam1/(3.0*lambdabar*lambdabar));
double rho = rootFinder->GetRootSingleFunc(lhFunc, rhSide, 0.1, 0.4, 1.0e-6);
//rho=0.250353;
EvtGenReport(EVTGEN_INFO,"EvtGen")<<"rho/2 "<<rho/2.<<" bessel "<<BesselK1(rho/2.)<<endl;
double pF = lambdabar*sqrt(EvtConst::pi)/(rho*exp(rho/2.)*BesselK1(rho/2.));
EvtGenReport(EVTGEN_INFO,"EvtGen")<<"rho "<<rho<<" pf "<<pF<<endl;
delete lhFunc; lhFunc=0;
delete rootFinder; rootFinder=0;
return rho;
}
double EvtBtoXsgammaFermiUtil::FermiRomanRootFcnA(double y) {
return EvtConst::pi*(2. + y)*pow(y,-2.)*exp(-y)*pow(BesselK1(y/2.),-2.);
}
double EvtBtoXsgammaFermiUtil::FermiRomanFunc(double y, const std::vector<double> &coeffs) {
if (y == (coeffs[1]-coeffs[2])) y=0.99999999*(coeffs[1]-coeffs[2]);
//coeffs: 1 = mB, 2=mb, 3=rho, 4=lambdabar, 5=norm
double pF = coeffs[4]*sqrt(EvtConst::pi)/(coeffs[3]*exp(coeffs[3]/2.)*BesselK1(coeffs[3]/2.));
// EvtGenReport(EVTGEN_INFO,"EvtGen")<<" pf "<<y<<" "<<pF<<" "<<coeffs[1]<<" "<<coeffs[2]<<" "<<coeffs[3]<<" "<<coeffs[4]<<" "<<coeffs[5]<<endl;
//double pF=0.382533;
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<(coeffs[1]-coeffs[2])*(1./(sqrt(EvtConst::pi)*pF))<<endl;
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<(1.-y/(coeffs[1]-coeffs[2]))<<endl;
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<(coeffs[1]-coeffs[2])<<endl;
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<(coeffs[1]-coeffs[2])*(1.-y/(coeffs[1]-coeffs[2]))<<endl;
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<" "<<pF*coeffs[3]/((coeffs[1]-coeffs[2])*(1.-y/(coeffs[1]-coeffs[2])))<<endl;
// EvtGenReport(EVTGEN_INFO,"EvtGen")<<" "<<((coeffs[1]-coeffs[2])/pF)*(1. -y/(coeffs[1]-coeffs[2]))<<endl;
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<"result "<<(coeffs[1]-coeffs[2])*(1./(sqrt(EvtConst::pi)*pF))*exp(-(1./4.)*pow(pF*(coeffs[3]/((coeffs[1]-coeffs[2])*(1.-y/(coeffs[1]-coeffs[2])))) - ((coeffs[1]-coeffs[2])/pF)*(1. -y/(coeffs[1]-coeffs[2])),2.))/coeffs[5];
//EvtGenReport(EVTGEN_INFO,"EvtGen")<<"leaving"<<endl;
return (coeffs[1]-coeffs[2])*(1./(sqrt(EvtConst::pi)*pF))*exp(-(1./4.)*pow(pF*(coeffs[3]/((coeffs[1]-coeffs[2])*(1.-y/(coeffs[1]-coeffs[2])))) - ((coeffs[1]-coeffs[2])/pF)*(1. -y/(coeffs[1]-coeffs[2])),2.))/coeffs[5];
}
| 35.535545 | 261 | 0.631368 | klendathu2k |
6d56961d84a3db32a3779437e2bc90ed51fafb72 | 3,421 | cc | C++ | test/core/client_channel/parse_address_test.cc | wangzihust/gRPC | 123547c9625c56fdf5cb4ddd1df55ae0c785fa60 | [
"Apache-2.0"
] | null | null | null | test/core/client_channel/parse_address_test.cc | wangzihust/gRPC | 123547c9625c56fdf5cb4ddd1df55ae0c785fa60 | [
"Apache-2.0"
] | null | null | null | test/core/client_channel/parse_address_test.cc | wangzihust/gRPC | 123547c9625c56fdf5cb4ddd1df55ae0c785fa60 | [
"Apache-2.0"
] | 1 | 2018-03-01T07:37:08.000Z | 2018-03-01T07:37:08.000Z | /*
*
* Copyright 2017 gRPC authors.
*
* 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 "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include <string.h>
#ifdef GRPC_HAVE_UNIX_SOCKET
#include <sys/un.h>
#endif
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/socket_utils.h"
#include "test/core/util/test_config.h"
#ifdef GRPC_HAVE_UNIX_SOCKET
static void test_grpc_parse_unix(const char* uri_text, const char* pathname) {
grpc_core::ExecCtx exec_ctx;
grpc_uri* uri = grpc_uri_parse(uri_text, 0);
grpc_resolved_address addr;
GPR_ASSERT(1 == grpc_parse_unix(uri, &addr));
struct sockaddr_un* addr_un = (struct sockaddr_un*)addr.addr;
GPR_ASSERT(AF_UNIX == addr_un->sun_family);
GPR_ASSERT(0 == strcmp(addr_un->sun_path, pathname));
grpc_uri_destroy(uri);
}
#else /* GRPC_HAVE_UNIX_SOCKET */
static void test_grpc_parse_unix(const char* uri_text, const char* pathname) {}
#endif /* GRPC_HAVE_UNIX_SOCKET */
static void test_grpc_parse_ipv4(const char* uri_text, const char* host,
unsigned short port) {
grpc_core::ExecCtx exec_ctx;
grpc_uri* uri = grpc_uri_parse(uri_text, 0);
grpc_resolved_address addr;
char ntop_buf[INET_ADDRSTRLEN];
GPR_ASSERT(1 == grpc_parse_ipv4(uri, &addr));
struct sockaddr_in* addr_in = (struct sockaddr_in*)addr.addr;
GPR_ASSERT(AF_INET == addr_in->sin_family);
GPR_ASSERT(nullptr != grpc_inet_ntop(AF_INET, &addr_in->sin_addr, ntop_buf,
sizeof(ntop_buf)));
GPR_ASSERT(0 == strcmp(ntop_buf, host));
GPR_ASSERT(ntohs(addr_in->sin_port) == port);
grpc_uri_destroy(uri);
}
static void test_grpc_parse_ipv6(const char* uri_text, const char* host,
unsigned short port, uint32_t scope_id) {
grpc_core::ExecCtx exec_ctx;
grpc_uri* uri = grpc_uri_parse(uri_text, 0);
grpc_resolved_address addr;
char ntop_buf[INET6_ADDRSTRLEN];
GPR_ASSERT(1 == grpc_parse_ipv6(uri, &addr));
struct sockaddr_in6* addr_in6 = (struct sockaddr_in6*)addr.addr;
GPR_ASSERT(AF_INET6 == addr_in6->sin6_family);
GPR_ASSERT(nullptr != grpc_inet_ntop(AF_INET6, &addr_in6->sin6_addr, ntop_buf,
sizeof(ntop_buf)));
GPR_ASSERT(0 == strcmp(ntop_buf, host));
GPR_ASSERT(ntohs(addr_in6->sin6_port) == port);
GPR_ASSERT(addr_in6->sin6_scope_id == scope_id);
grpc_uri_destroy(uri);
}
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
grpc_init();
test_grpc_parse_unix("unix:/path/name", "/path/name");
test_grpc_parse_ipv4("ipv4:192.0.2.1:12345", "192.0.2.1", 12345);
test_grpc_parse_ipv6("ipv6:[2001:db8::1]:12345", "2001:db8::1", 12345, 0);
test_grpc_parse_ipv6("ipv6:[2001:db8::1%252]:12345", "2001:db8::1", 12345, 2);
grpc_shutdown();
}
| 33.213592 | 80 | 0.708272 | wangzihust |
6d5c798ad9895ef1d38b81ea9517683a84a6ee8e | 16,771 | hpp | C++ | include/Awl/boost/detail/ob_compressed_pair.hpp | Yalir/Awl | 92ef5996d8933bf92ceb37357d8cd2b169cb788e | [
"BSL-1.0"
] | 4 | 2016-07-01T02:33:28.000Z | 2020-03-03T17:52:54.000Z | include/Awl/boost/detail/ob_compressed_pair.hpp | Yalir/Awl | 92ef5996d8933bf92ceb37357d8cd2b169cb788e | [
"BSL-1.0"
] | null | null | null | include/Awl/boost/detail/ob_compressed_pair.hpp | Yalir/Awl | 92ef5996d8933bf92ceb37357d8cd2b169cb788e | [
"BSL-1.0"
] | null | null | null | // (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/utility for most recent version including documentation.
// see libs/utility/compressed_pair.hpp
//
/* Release notes:
20 Jan 2001:
Fixed obvious bugs (David Abrahams)
07 Oct 2000:
Added better single argument constructor support.
03 Oct 2000:
Added VC6 support (JM).
23rd July 2000:
Additional comments added. (JM)
Jan 2000:
Original version: this version crippled for use with crippled compilers
- John Maddock Jan 2000.
*/
#ifndef BOOST_OB_COMPRESSED_PAIR_HPP
#define BOOST_OB_COMPRESSED_PAIR_HPP
#include <algorithm>
#ifndef BOOST_OBJECT_TYPE_TRAITS_HPP
#include <Awl/boost/type_traits/object_traits.hpp>
#endif
#ifndef BOOST_SAME_TRAITS_HPP
#include <Awl/boost/type_traits/same_traits.hpp>
#endif
#ifndef BOOST_CALL_TRAITS_HPP
#include <Awl/boost/call_traits.hpp>
#endif
namespace boost
{
#ifdef BOOST_MSVC6_MEMBER_TEMPLATES
//
// use member templates to emulate
// partial specialisation. Note that due to
// problems with overload resolution with VC6
// each of the compressed_pair versions that follow
// have one template single-argument constructor
// in place of two specific constructors:
//
template <class T1, class T2>
class compressed_pair;
namespace detail{
template <class A, class T1, class T2>
struct best_conversion_traits
{
typedef char one;
typedef char (&two)[2];
static A a;
static one test(T1);
static two test(T2);
enum { value = sizeof(test(a)) };
};
template <int>
struct init_one;
template <>
struct init_one<1>
{
template <class A, class T1, class T2>
static void init(const A& a, T1* p1, T2*)
{
*p1 = a;
}
};
template <>
struct init_one<2>
{
template <class A, class T1, class T2>
static void init(const A& a, T1*, T2* p2)
{
*p2 = a;
}
};
// T1 != T2, both non-empty
template <class T1, class T2>
class compressed_pair_0
{
private:
T1 _first;
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_0() : _first(), _second() {}
compressed_pair_0(first_param_type x, second_param_type y) : _first(x), _second(y) {}
template <class A>
explicit compressed_pair_0(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, &_first, &_second);
}
compressed_pair_0(const ::boost::compressed_pair<T1,T2>& x)
: _first(x.first()), _second(x.second()) {}
#if 0
compressed_pair_0& operator=(const compressed_pair_0& x) {
cout << "assigning compressed pair 0" << endl;
_first = x._first;
_second = x._second;
cout << "finished assigning compressed pair 0" << endl;
return *this;
}
#endif
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair_0& y)
{
using std::swap;
swap(_first, y._first);
swap(_second, y._second);
}
};
// T1 != T2, T2 empty
template <class T1, class T2>
class compressed_pair_1 : T2
{
private:
T1 _first;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_1() : T2(), _first() {}
compressed_pair_1(first_param_type x, second_param_type y) : T2(y), _first(x) {}
template <class A>
explicit compressed_pair_1(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, &_first, static_cast<T2*>(this));
}
compressed_pair_1(const ::boost::compressed_pair<T1,T2>& x)
: T2(x.second()), _first(x.first()) {}
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
// Total weirdness. If the assignment to _first is moved after
// the call to the inherited operator=, then this breaks graph/test/graph.cpp
// by way of iterator_adaptor.
compressed_pair_1& operator=(const compressed_pair_1& x) {
_first = x._first;
T2::operator=(x);
return *this;
}
#endif
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return *this; }
second_const_reference second() const { return *this; }
void swap(compressed_pair_1& y)
{
// no need to swap empty base class:
using std::swap;
swap(_first, y._first);
}
};
// T1 != T2, T1 empty
template <class T1, class T2>
class compressed_pair_2 : T1
{
private:
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_2() : T1(), _second() {}
compressed_pair_2(first_param_type x, second_param_type y) : T1(x), _second(y) {}
template <class A>
explicit compressed_pair_2(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, static_cast<T1*>(this), &_second);
}
compressed_pair_2(const ::boost::compressed_pair<T1,T2>& x)
: T1(x.first()), _second(x.second()) {}
#if 0
compressed_pair_2& operator=(const compressed_pair_2& x) {
cout << "assigning compressed pair 2" << endl;
T1::operator=(x);
_second = x._second;
cout << "finished assigning compressed pair 2" << endl;
return *this;
}
#endif
first_reference first() { return *this; }
first_const_reference first() const { return *this; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair_2& y)
{
// no need to swap empty base class:
using std::swap;
swap(_second, y._second);
}
};
// T1 != T2, both empty
template <class T1, class T2>
class compressed_pair_3 : T1, T2
{
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_3() : T1(), T2() {}
compressed_pair_3(first_param_type x, second_param_type y) : T1(x), T2(y) {}
template <class A>
explicit compressed_pair_3(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, static_cast<T1*>(this), static_cast<T2*>(this));
}
compressed_pair_3(const ::boost::compressed_pair<T1,T2>& x)
: T1(x.first()), T2(x.second()) {}
first_reference first() { return *this; }
first_const_reference first() const { return *this; }
second_reference second() { return *this; }
second_const_reference second() const { return *this; }
void swap(compressed_pair_3& y)
{
// no need to swap empty base classes:
}
};
// T1 == T2, and empty
template <class T1, class T2>
class compressed_pair_4 : T1
{
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_4() : T1() {}
compressed_pair_4(first_param_type x, second_param_type y) : T1(x), m_second(y) {}
// only one single argument constructor since T1 == T2
explicit compressed_pair_4(first_param_type x) : T1(x), m_second(x) {}
compressed_pair_4(const ::boost::compressed_pair<T1,T2>& x)
: T1(x.first()), m_second(x.second()) {}
first_reference first() { return *this; }
first_const_reference first() const { return *this; }
second_reference second() { return m_second; }
second_const_reference second() const { return m_second; }
void swap(compressed_pair_4& y)
{
// no need to swap empty base classes:
}
private:
T2 m_second;
};
// T1 == T2, not empty
template <class T1, class T2>
class compressed_pair_5
{
private:
T1 _first;
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_5() : _first(), _second() {}
compressed_pair_5(first_param_type x, second_param_type y) : _first(x), _second(y) {}
// only one single argument constructor since T1 == T2
explicit compressed_pair_5(first_param_type x) : _first(x), _second(x) {}
compressed_pair_5(const ::boost::compressed_pair<T1,T2>& c)
: _first(c.first()), _second(c.second()) {}
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair_5& y)
{
using std::swap;
swap(_first, y._first);
swap(_second, y._second);
}
};
template <bool e1, bool e2, bool same>
struct compressed_pair_chooser
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_0<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<false, true, false>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_1<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<true, false, false>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_2<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<true, true, false>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_3<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<true, true, true>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_4<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<false, false, true>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_5<T1, T2> type;
};
};
template <class T1, class T2>
struct compressed_pair_traits
{
private:
typedef compressed_pair_chooser<is_empty<T1>::value, is_empty<T2>::value, is_same<T1,T2>::value> chooser;
typedef typename chooser::template rebind<T1, T2> bound_type;
public:
typedef typename bound_type::type type;
};
} // namespace detail
template <class T1, class T2>
class compressed_pair : public detail::compressed_pair_traits<T1, T2>::type
{
private:
typedef typename detail::compressed_pair_traits<T1, T2>::type base_type;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair() : base_type() {}
compressed_pair(first_param_type x, second_param_type y) : base_type(x, y) {}
template <class A>
explicit compressed_pair(const A& x) : base_type(x){}
first_reference first() { return base_type::first(); }
first_const_reference first() const { return base_type::first(); }
second_reference second() { return base_type::second(); }
second_const_reference second() const { return base_type::second(); }
};
template <class T1, class T2>
inline void swap(compressed_pair<T1, T2>& x, compressed_pair<T1, T2>& y)
{
x.swap(y);
}
#else
// no partial specialisation, no member templates:
template <class T1, class T2>
class compressed_pair
{
private:
T1 _first;
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair() : _first(), _second() {}
compressed_pair(first_param_type x, second_param_type y) : _first(x), _second(y) {}
explicit compressed_pair(first_param_type x) : _first(x), _second() {}
// can't define this in case T1 == T2:
// explicit compressed_pair(second_param_type y) : _first(), _second(y) {}
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair& y)
{
using std::swap;
swap(_first, y._first);
swap(_second, y._second);
}
};
template <class T1, class T2>
inline void swap(compressed_pair<T1, T2>& x, compressed_pair<T1, T2>& y)
{
x.swap(y);
}
#endif
} // boost
#endif // BOOST_OB_COMPRESSED_PAIR_HPP
| 32.819961 | 116 | 0.667104 | Yalir |
6d5ce775736d3b41f9f6012a1d3c63da8cc43597 | 1,128 | cpp | C++ | pgm10_21.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | 1 | 2021-07-13T03:58:36.000Z | 2021-07-13T03:58:36.000Z | pgm10_21.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | pgm10_21.cpp | neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C- | c9a29d2dd43ad8561e828c25f98de6a8c8f2317a | [
"Unlicense"
] | null | null | null | //
// This file contains the C++ code from Program 10.21 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm10_21.cpp
//
void BTree::InsertPair (Object& object, BTree& child)
{
unsigned int const index = FindIndex (object);
BTree& extraTree = InsertSubtree (index + 1, child);
Object& extraKey = InsertKey (index + 1, object);
if (++numberOfKeys == m)
{
if (parent == 0)
{
BTree& left = *new BTree (m, *this);
BTree& right = *new BTree (m, *this);
left.AttachLeftHalfOf (*this);
right.AttachRightHalfOf (*this, extraKey, extraTree);
AttachSubtree (0, left);
AttachKey (1, *key [(m + 1)/2]);
AttachSubtree (1, right);
numberOfKeys = 1;
}
else
{
numberOfKeys = (m + 1)/2 - 1;
BTree& right = *new BTree (m, *parent);
right.AttachRightHalfOf (*this, extraKey, extraTree);
parent->InsertPair (*key [(m + 1)/2], right);
}
}
}
| 28.923077 | 80 | 0.616135 | neharkarvishal |
6d6590c1f8fa236149ada09bc7fbad031b0c344f | 1,761 | hpp | C++ | Quiz4/figure.hpp | deror1869107/yypoop | f3605961787610bf08f8a9ea2afb905d1af3c5c0 | [
"MIT"
] | null | null | null | Quiz4/figure.hpp | deror1869107/yypoop | f3605961787610bf08f8a9ea2afb905d1af3c5c0 | [
"MIT"
] | null | null | null | Quiz4/figure.hpp | deror1869107/yypoop | f3605961787610bf08f8a9ea2afb905d1af3c5c0 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
using namespace std;
namespace figure{
//You can add member function in this class
class BasePoint{
public:
BasePoint(int px, int py):x(px),y(py){}
virtual ~BasePoint(){}
void settype(string s){
type = s;
}
virtual void info(){
cout<<"figure: "<<type<<endl;
cout<<"position x:"<<x<<" y:"<<y<<endl;
}
protected:
int x,y;
private:
string type;
};
//Fill your code here
class Figure1P: public BasePoint {
public:
Figure1P(int px,int py, int _p1):BasePoint(px, py), p1(_p1){}
void info(){
BasePoint::info();
cout<<"property 1: p1="<<p1<<endl;
}
protected:
int p1;
};
class Square: public Figure1P {
public:
Square(int px,int py, int _p1):Figure1P(px, py, _p1){
settype("square");
}
void info(){
Figure1P::info();
cout<<"area: "<<p1 * p1<<endl;
}
};
class Figure2P: public Figure1P {
public:
Figure2P(int px,int py, int _p1, int _p2):Figure1P(px, py, _p1), p2(_p2){}
void info(){
Figure1P::info();
cout<<"property 2: p2="<<p2<<endl;
}
protected:
int p2;
};
class Rectangle: public Figure2P {
public:
Rectangle(int px,int py, int _p1, int _p2):Figure2P(px, py, _p1, _p2){
settype("rectangle");
}
void info(){
Figure2P::info();
cout<<"area: "<<p1 * p2<<endl;
}
};
}
| 25.897059 | 86 | 0.454287 | deror1869107 |
6d665fe66e2e9576b3ec710c575ad4aec6f363a7 | 2,190 | cpp | C++ | src/LoboFEM/LoboDynamic/LoboDynamicSolver/LoboOptimizationSolver/Dense/NewtonDense.cpp | lrquad/LoboFEM2 | 4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5 | [
"MIT"
] | 5 | 2020-05-09T12:33:08.000Z | 2021-12-17T08:07:29.000Z | src/LoboFEM/LoboDynamic/LoboDynamicSolver/LoboOptimizationSolver/Dense/NewtonDense.cpp | FYTalon/LoboFEM2 | 4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5 | [
"MIT"
] | null | null | null | src/LoboFEM/LoboDynamic/LoboDynamicSolver/LoboOptimizationSolver/Dense/NewtonDense.cpp | FYTalon/LoboFEM2 | 4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5 | [
"MIT"
] | 2 | 2021-02-11T10:00:37.000Z | 2021-04-18T02:08:11.000Z | #include "NewtonDense.h"
#include "LoboDynamic/LoboDynamic.h"
#include <fstream>
#include <iostream>
Lobo::NewtonDense::NewtonDense(DynamicModel *model_, int maxiter, double tol) : LoboOptimizationSolver(model_, maxiter, tol)
{
q.resize(r);
q.setZero();
}
Lobo::NewtonDense::~NewtonDense()
{
}
void Lobo::NewtonDense::precompute()
{
hessian.resize(r,r);
jacobi.resize(r);
}
void Lobo::NewtonDense::solve(Eigen::VectorXd* initialGuessq)
{
q = *initialGuessq;
double newton_stepping = 1.0; //line length
int flags_all = 0;
flags_all |= Computeflags_energy|Computeflags_fisrt|Computeflags_second|Computeflags_reset;
int flags_energy = 0;
flags_energy |= Computeflags_energy|Computeflags_reset;
double pre_energy = DBL_MAX;
for(int i=0;i<maxiteration;i++)
{
model->computeEnergyDense(&q,&energy,&jacobi,&hessian,flags_all);
jacobi*=-1;
double tmp = std::abs(pre_energy-energy)/std::abs(energy+1e-15);
//std::cout<<tmp<<std::endl;
if(tmp < tolerance)
{
break;
}else
{
pre_energy = energy;
}
Eigen::VectorXd result_ = hessian.ldlt().solve(jacobi);
//wolfe condition
newton_stepping = 1.0;
bool wolfecondition = false;
double c1 = 0.0;
double c2 = 0.9;
//prepare wolf condition buffer
Eigen::VectorXd newton_g_k_1(r);
double newton_e_k_1 = 0.0;
Eigen::VectorXd newton_direction = result_;
while(!wolfecondition)
{
if(newton_stepping <0.01)
{
break;
}
Eigen::VectorXd q_k_1 = q + newton_direction*newton_stepping;
model->computeEnergyDense(&q_k_1,&newton_e_k_1,&newton_g_k_1,NULL,flags_energy);
bool wolf1 = newton_e_k_1 <= energy + c1*newton_stepping*(-jacobi.dot(newton_direction));
bool wolf2 = true;
wolfecondition = wolf1&&wolf2;
if (!wolfecondition)
newton_stepping *= 0.7;
}
q = q + newton_direction*newton_stepping;
}
}
void Lobo::NewtonDense::getResult(Eigen::VectorXd* result)
{
*result = q;
} | 26.071429 | 124 | 0.618721 | lrquad |
6d67e0363661e1d539e79d0f973a30d700353c89 | 2,135 | cpp | C++ | src/c++/methods/ModfileInstanceMethods.cpp | TestingTravis/modioSDK | b15c4442a8acdb4bf690a846232399eaf9fe18f6 | [
"MIT"
] | null | null | null | src/c++/methods/ModfileInstanceMethods.cpp | TestingTravis/modioSDK | b15c4442a8acdb4bf690a846232399eaf9fe18f6 | [
"MIT"
] | null | null | null | src/c++/methods/ModfileInstanceMethods.cpp | TestingTravis/modioSDK | b15c4442a8acdb4bf690a846232399eaf9fe18f6 | [
"MIT"
] | null | null | null | #include "c++/ModIOInstance.h"
namespace modio
{
void Instance::getModfile(u32 mod_id, u32 modfile_id, const std::function<void(const modio::Response &response, const modio::Modfile &modfile)> &callback)
{
const struct GetModfileCall *get_modfile_call = new GetModfileCall{callback};
get_modfile_calls[this->current_call_id] = (GetModfileCall *)get_modfile_call;
modioGetModfile((void *)new u32(this->current_call_id), mod_id, modfile_id, &onGetModfile);
this->current_call_id++;
}
void Instance::getAllModfiles(u32 mod_id, modio::FilterCreator &filter, const std::function<void(const modio::Response &, const std::vector<modio::Modfile> &modfiles)> &callback)
{
const struct GetAllModfilesCall *get_all_modfiles_call = new GetAllModfilesCall{callback};
get_all_modfiles_calls[this->current_call_id] = (GetAllModfilesCall *)get_all_modfiles_call;
modioGetAllModfiles((void *)new u32(this->current_call_id), mod_id, *filter.getFilter(), &onGetAllModfiles);
this->current_call_id++;
}
void Instance::addModfile(u32 mod_id, modio::ModfileCreator &modfile_handler)
{
modioAddModfile(mod_id, *modfile_handler.getModioModfileCreator());
}
void Instance::editModfile(u32 mod_id, u32 modfile_id, modio::ModfileEditor &modfile_handler, const std::function<void(const modio::Response &response, const modio::Modfile &modfile)> &callback)
{
const struct EditModfileCall *edit_modfile_call = new EditModfileCall{callback};
edit_modfile_calls[this->current_call_id] = (EditModfileCall *)edit_modfile_call;
modioEditModfile((void *)new u32(this->current_call_id), mod_id, modfile_id, *modfile_handler.getModioModfileEditor(), &onEditModfile);
this->current_call_id++;
}
void Instance::deleteModfile(u32 mod_id, u32 modfile_id, const std::function<void(const modio::Response &response)> &callback)
{
const struct GenericCall *delete_modfile_call = new GenericCall{callback};
delete_modfile_calls[this->current_call_id] = (GenericCall *)delete_modfile_call;
modioDeleteModfile((void *)new u32(this->current_call_id), mod_id, modfile_id, &onDeleteModfile);
this->current_call_id++;
}
} // namespace modio
| 42.7 | 194 | 0.783607 | TestingTravis |
6d704b1040852473351adb33515a52ba58481a7f | 1,625 | hpp | C++ | Framework/[C++ Core]/[[Tools]]/UISegment.hpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 3 | 2019-10-10T19:25:42.000Z | 2019-12-17T10:51:23.000Z | Framework/[C++ Core]/[[Tools]]/UISegment.hpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | null | null | null | Framework/[C++ Core]/[[Tools]]/UISegment.hpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 1 | 2021-11-16T15:29:40.000Z | 2021-11-16T15:29:40.000Z | //
// UISegment.hpp
// DigMMMac
//
// Created by Raptis, Nicholas on 7/4/18.
// Copyright © 2018 Darkswarm LLC. All rights reserved.
//
#ifndef UISegment_hpp
#define UISegment_hpp
#include "ToolMenuSectionRow.hpp"
#include "UISegmentButton.hpp"
class UISegment : public ToolMenuSectionRow {
public:
UISegment();
UISegment(int pSegmentCount);
virtual ~UISegment();
virtual void Layout() override;
virtual void Update() override;
virtual void Notify(void *pSender, const char *pNotification) override;
void SetSegmentCount(int pSegmentCount);
void SetSelectedIndex(int pIndex);
void SetTitle(int pSegment, const char *pTitle);
void SetTitles(const char *pTitle1, const char *pTitle2=0, const char *pTitle3=0, const char *pTitle4=0, const char *pTitle5=0, const char *pTitle6=0, const char *pTitle7=0, const char *pTitle8=0, const char *pTitle9=0, const char *pTitle10=0, const char *pTitle11=0, const char *pTitle12=0, const char *pTitle13=0, const char *pTitle14=0);
void SetTarget(int *pTarget);
int *mTarget;
UISegmentButton **mButton;
int mSegmentCount;
int mSelectedIndex;
};
#endif /* UISegment_hpp */
| 38.690476 | 383 | 0.521231 | nraptis |
6d7189c225fbad52339e579835965c13a10a89dc | 4,881 | cpp | C++ | HelloCocos/cocos2d/cocos/editor-support/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp | l-le/git-centos | 8479f0342d3d48df1ee7d0db4eafa96a0d151f43 | [
"MIT"
] | 34 | 2017-08-16T13:58:24.000Z | 2022-03-31T11:50:25.000Z | HelloCocos/cocos2d/cocos/editor-support/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp | l-le/git-centos | 8479f0342d3d48df1ee7d0db4eafa96a0d151f43 | [
"MIT"
] | null | null | null | HelloCocos/cocos2d/cocos/editor-support/cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.cpp | l-le/git-centos | 8479f0342d3d48df1ee7d0db4eafa96a0d151f43 | [
"MIT"
] | 17 | 2017-08-18T07:42:44.000Z | 2022-01-02T02:43:06.000Z | #include "tinyxml2/tinyxml2.h"
#include "flatbuffers/flatbuffers.h"
#include "cocostudio/WidgetReader/NodeReader/NodeReader.h"
#include "cocostudio/CSParseBinary_generated.h"
#include "CSArmatureNode_generated.h"
#include "cocostudio/WidgetReader/ArmatureNodeReader/ArmatureNodeReader.h"
#include "cocostudio/CCArmature.h"
USING_NS_CC;
using namespace cocostudio;
using namespace flatbuffers;
IMPLEMENT_CLASS_NODE_READER_INFO(ArmatureNodeReader)
ArmatureNodeReader::ArmatureNodeReader()
{
}
ArmatureNodeReader::~ArmatureNodeReader()
{
}
static ArmatureNodeReader* _instanceArmatureNodeReader = nullptr;
ArmatureNodeReader* ArmatureNodeReader::getInstance()
{
if (_instanceArmatureNodeReader == nullptr)
{
_instanceArmatureNodeReader = new (std::nothrow) ArmatureNodeReader();
}
return _instanceArmatureNodeReader;
}
Offset<Table> ArmatureNodeReader::createOptionsWithFlatBuffers(const tinyxml2::XMLElement *objectData,
flatbuffers::FlatBufferBuilder *builder)
{
auto temp = NodeReader::getInstance()->createOptionsWithFlatBuffers(objectData, builder);
auto nodeOptions = *(Offset<WidgetOptions>*)(&temp);
bool isloop = false;
bool isAutoPlay = false;
std::string currentAnimationName = "";
int type = 0;
std::string path = "";
const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute();
while (attribute)
{
std::string attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "IsLoop")
{
isloop = (value == "True") ? true : false;
}
else if (attriname == "IsAutoPlay")
{
isAutoPlay = (value == "True") ? true : false;
}
else if (attriname == "CurrentAnimationName")
{
currentAnimationName = value;
}
attribute = attribute->Next();
}
const tinyxml2::XMLElement* child = objectData->FirstChildElement();
while (child)
{
std::string attriname = child->Name();
if (attriname == "FileData")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "Type")
{
type = 0;
}
else if (attriname == "Path")
{
path = value;
}
attribute = attribute->Next();
}
}
child = child->NextSiblingElement();
}
auto options = CreateCSArmatureNodeOption(*builder,
nodeOptions,
CreateResourceItemData(*builder,
type,
builder->CreateString(path)),
isloop,
isAutoPlay,
builder->CreateString(currentAnimationName));
return *(Offset<Table>*)(&options);
}
void ArmatureNodeReader::setPropsWithFlatBuffers(cocos2d::Node *node,
const flatbuffers::Table *nodeOptions)
{
auto* custom = static_cast<Armature*>(node);
auto options = (flatbuffers::CSArmatureNodeOption*)nodeOptions;
bool fileExist = false;
std::string errorFilePath = "";
std::string filepath(options->fileData()->path()->c_str());
if (FileUtils::getInstance()->isFileExist(filepath))
{
fileExist = true;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(filepath);
std::string dirpath = fullpath.substr(0, fullpath.find_last_of("/"));
FileUtils::getInstance()->addSearchPath(dirpath);
ArmatureDataManager::getInstance()->addArmatureFileInfo(fullpath);
custom->init(getArmatureName(filepath));
std::string currentname = options->currentAnimationName()->c_str();
if (options->isAutoPlay())
custom->getAnimation()->play(currentname, -1, options->isLoop());
else
{
custom->getAnimation()->play(currentname);
custom->getAnimation()->gotoAndPause(0);
}
}
else
{
errorFilePath = filepath;
fileExist = false;
}
if (!fileExist)
{
auto label = Label::create();
label->setString(__String::createWithFormat("%s missed", filepath.c_str())->getCString());
custom->addChild(label);
}
}
cocos2d::Node* ArmatureNodeReader::createNodeWithFlatBuffers(const flatbuffers::Table *nodeOptions)
{
auto node = CCArmature::create();
// self
auto options = (flatbuffers::CSArmatureNodeOption*)nodeOptions;
setPropsWithFlatBuffers(node, (Table*)options);
// super node
auto NodeReader = NodeReader::getInstance();
NodeReader->setPropsWithFlatBuffers(node, (Table*)options->nodeOptions());
return node;
}
std::string ArmatureNodeReader::getArmatureName(const std::string& exporJsonPath)
{
//FileUtils.getFileData(exporJsonPath, "r", size) // need read armature name in exportJsonPath
size_t end = exporJsonPath.find_last_of(".");
size_t start = exporJsonPath.find_last_of("\\") + 1;
size_t start1 = exporJsonPath.find_last_of("/") + 1;
if (start < start1)
start = start1;
if (start == -1)
start = 0;
return exporJsonPath.substr(start, end - start);
} | 25.689474 | 102 | 0.686949 | l-le |
6d71bafb84372bfc6627297c7930573a2f711fbc | 2,670 | cpp | C++ | p4/CheckerRunner.cpp | sabrina-enriquez/ECS36c | e0b9f8128a086973c7c98e900ed2ceee7ce40a65 | [
"MIT"
] | null | null | null | p4/CheckerRunner.cpp | sabrina-enriquez/ECS36c | e0b9f8128a086973c7c98e900ed2ceee7ce40a65 | [
"MIT"
] | null | null | null | p4/CheckerRunner.cpp | sabrina-enriquez/ECS36c | e0b9f8128a086973c7c98e900ed2ceee7ce40a65 | [
"MIT"
] | null | null | null |
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include "CheckerRunner.h"
#include "checker.h"
#include "CPUTimer.h"
using namespace std;
MatchingWords* readTesterFile(const char *filename, int *numWords)
{
char line[1000], *ptr;
ifstream inf(filename);
inf >> *numWords;
MatchingWords *matchingWords = new MatchingWords[*numWords];
inf.ignore(1000, '\n');
for(int i = 0; i < *numWords; i++)
{
inf.getline(line, 1000);
ptr = strtok(line, ",");
matchingWords[i].word = new char[strlen(ptr) + 1];
strcpy(matchingWords[i].word, ptr);
matchingWords[i].count = atoi(strtok(NULL, ","));
matchingWords[i].matches = new char*[matchingWords[i].count];
for(int j = 0; j < matchingWords[i].count; j++)
{
ptr = strtok(NULL, ",");
matchingWords[i].matches[j] = new char[strlen(ptr) + 1];
strcpy(matchingWords[i].matches[j], ptr);
} // for each matching word
} // for each word
return matchingWords;
} // readTesterFile()
DictionaryWord* readWordsFile()
{
int count = 0;
char line[100];
DictionaryWord *words = new DictionaryWord[NUM_WORDS];
ifstream inf("words.txt");
while(inf.getline(line, 100))
strcpy(words[count++].word, line);
return words;
} // readWordsFile()
int main(int argc, char **argv)
{
char word[MAX_LENGTH + 1], matchingWords[100][MAX_LENGTH + 1];
int numWords, count;
DictionaryWord *words = readWordsFile();
MatchingWords *matchingWordsKey = readTesterFile(argv[1], &numWords);
CPUTimer ct;
Checker *checker = new Checker((const DictionaryWord*) words, NUM_WORDS);
delete words;
for(int i = 0; i < numWords; i++)
{
strcpy(word, matchingWordsKey[i].word);
checker->findWord(word, matchingWords, &count);
if(count != matchingWordsKey[i].count)
{
cout << "Incorrect count for trial# " << i << " for "
<< matchingWordsKey[i].word << " should be "
<< matchingWordsKey[i].count << " but received " << count << endl;
}
else // correct count
{
for(int j = 0; j < count; j++)
{
bool OK = false;
for(int k = 0; !OK && k < count; k++)
if(strcmp(matchingWordsKey[i].matches[j], matchingWords[k]) == 0)
OK = true;
if(!OK)
{
cout << "Words don't match for trial# " << i << " for "
<< matchingWordsKey[i].word << "they do not include"
<< matchingWordsKey[i].matches[j] << endl;
} // if invalid match
} // for j
} // else correct count
} // for each word
cout << "CPU Time: " << ct.cur_CPUTime() << endl;
return 0;
}
| 27.244898 | 75 | 0.597753 | sabrina-enriquez |
6d71bd48ffadd52eb0761454f9b6a0a9e2bc660b | 1,391 | cpp | C++ | lib/bigssMath/bigssKinematicsUtils.cpp | gaocong13/Orthopedic-Robot-Navigation | bf36f7de116c1c99b86c9ba50f111c3796336af0 | [
"MIT"
] | 13 | 2021-11-16T08:17:39.000Z | 2022-02-11T11:08:55.000Z | lib/bigssMath/bigssKinematicsUtils.cpp | gaocong13/Orthopedic-Robot-Navigation | bf36f7de116c1c99b86c9ba50f111c3796336af0 | [
"MIT"
] | null | null | null | lib/bigssMath/bigssKinematicsUtils.cpp | gaocong13/Orthopedic-Robot-Navigation | bf36f7de116c1c99b86c9ba50f111c3796336af0 | [
"MIT"
] | 1 | 2021-11-16T08:17:42.000Z | 2021-11-16T08:17:42.000Z |
#include "bigssKinematicsUtils.h"
vctMatrix4x4 FrameInverse(const vctMatrix4x4& f)
{
vctMatrix4x4 f_inv = vctMatrix4x4::Eye();
vctDynamicConstMatrixRef<double> R(f, 0, 0, 3, 3);
vctDynamicMatrixRef<double> R_T(f_inv, 0, 0, 3, 3);
R_T = R.Transpose();
vctDynamicConstMatrixRef<double> trans(f, 0, 3, 3, 1);
// inverse component of translation
vctDynamicMatrixRef<double>(f_inv, 0, 3, 3, 1) = -1.0 * R_T * trans;
return f_inv;
}
vctFrm4x4 ConvertFromURAxisAnglePose(const double ur_pose[6], const bool convert_from_m)
{
vctFrm4x4 pose;
pose.Translation().Assign(ur_pose[0],
ur_pose[1],
ur_pose[2]);
if (convert_from_m)
{
pose.Translation() *= 1000.0;
}
pose.Rotation().FromNormalized(
vctRodriguezRotation3<double>(ur_pose[3], ur_pose[4], ur_pose[5]));
return pose;
}
void ConvertToURAxisAnglePose(const vctFrm4x4& src, double ur_pose[6], const bool convert_to_m)
{
ur_pose[0] = src.Translation().X();
ur_pose[1] = src.Translation().Y();;
ur_pose[2] = src.Translation().Z();
if (convert_to_m)
{
ur_pose[0] /= 1000.0;
ur_pose[1] /= 1000.0;
ur_pose[2] /= 1000.0;
}
vctAxAnRot3 axis_angle(src.Rotation());
vctFixedSizeVectorRef<double,3,1> ur_ax_ang(ur_pose + 3);
ur_ax_ang = axis_angle.Axis();
ur_ax_ang *= axis_angle.Angle();
}
| 23.183333 | 95 | 0.64486 | gaocong13 |
6d7441e1dc2584b849f2a329b5d78eee5efaff4f | 3,904 | cpp | C++ | 517-13-C.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | 517-13-C.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | 517-13-C.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | /*
* Author: xiaohei_AWM
* Date:11.1
* Motto: Face to the weakness, expect for the strength.
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<utility>
#include<functional>
#include<map>
#include<cmath>
#include<vector>
#include<assert.h>
#include<set>
using namespace std;
#define reg register
#define endfile fclose(stdin);fclose(stdout);
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef std::pair<int,int> pii;
typedef std::pair<ll,ll> pll;
namespace IO{
char buf[1<<15],*S,*T;
inline char gc(){
if (S==T){
T=(S=buf)+fread(buf,1,1<<15,stdin);
if (S==T)return EOF;
}
return *S++;
}
inline int read(){
reg int x;reg bool f;reg char c;
for(f=0;(c=gc())<'0'||c>'9';f=c=='-');
for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0'));
return f?-x:x;
}
inline ll readll(){
reg ll x;reg bool f;reg char c;
for(f=0;(c=gc())<'0'||c>'9';f=c=='-');
for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0'));
return f?-x:x;
}
}
using namespace IO;
const long long llINF = 9223372036854775807;
const int INF = 2147483647;
/*
ll mul(ll a, ll b, ll p){
asm(
"mul %%ebx\n"
"div %%ecx"
: "=d"(a)
: "a"(a), "b"(b), "c"(p)
);
return a;
}
*/
const int maxn = 1010;
set<int> X, Y;
map<pii, bool> done;
map<pii, int> pots;
int n, a, b, cnt, len, leny1, leny2;
int dx[20] = {1, 1, 1, 1, -1, -1, -1, -1};
int dy[20] = {-1, -1, 1, 1, -1, -1, 1, 1};
int lenxx[20], lenyy[20];
pii pot[maxn];
bool visited[maxn][maxn], used[maxn];
int dis(int u, int v){
return abs(pot[u].first - pot[v].first) + abs(pot[u].second - pot[v].second);
}
void dfs(int a){
for(int i = 1; i <= n; i++){
if(i == a) continue;
if(visited[a][i]) continue;
if(dis(a, i) == len){
//visited[i] = true;
visited[a][i] = visited[i][a] = true;
cnt++;
if(!used[i])
used[i] = true, dfs(i);
}
}
}
void dfs1(int a){
pii tmp;
for(int i = 0; i < 16; i++){
tmp = make_pair(pot[a].first + lenxx[i], pot[a].second + lenyy[i]);
if(pots.count(tmp)){
int id = pots[tmp];
cnt++;
if(!done.count(make_pair(id, a))){
done[make_pair(id, a)] = true;
done[make_pair(a, id)] = true;
dfs1(id);
}
}
}
}
void solve1(){
pii tmp = pot[a];
if(Y.size() == 2){
leny1 = abs(pot[1].second - pot[2].second);
leny2 = 0;
int lenx1 = len - leny1;
int lenx2 = len - leny2;
for(int i = 0; i < 16; i++){
if(i & 1){
lenxx[i] = dx[i] * lenx1;
lenyy[i] = dy[i] * leny1;
}else{
lenxx[i] = dx[i] * lenx2;
lenyy[i] = dy[i] * leny2;
}
}
}else{
int lenx1 = abs(pot[1].first - pot[2].first);
int lenx2 = 0;
leny1 = len - lenx1;
leny2 = len - lenx2;
for(int i = 0; i < 16; i++){
if(i & 1){
lenxx[i] = dx[i] * lenx1;
lenyy[i] = dy[i] * leny1;
}else{
lenxx[i] = dx[i] * lenx2;
lenyy[i] = dy[i] * leny2;
}
}
}
dfs1(a);
}
int main(){
n = read(), a = read(), b =read();
for(int i = 1; i <= n; i++){
pot[i].first = read(), pot[i].second = read();
X.insert(pot[i].first), Y.insert(pot[i].second);
pots[pot[i]] = i;
}
len = abs(pot[a].first - pot[b].first) + abs(pot[a].second - pot[b].second);
used[a] = true;
if(n <= 1000)
dfs(a);
else
solve1();
//else
cout << cnt << endl;
return 0;
}
| 25.025641 | 81 | 0.460553 | AndrewWayne |
6d7a5d7ca8fb3a98fc62d1b31e80fe8379e22aea | 2,624 | hxx | C++ | src/weapon/plasma_burst.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/weapon/plasma_burst.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/weapon/plasma_burst.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | 1 | 2022-01-29T11:54:41.000Z | 2022-01-29T11:54:41.000Z | /**
* @file
* @author Jason Lingle
* @brief Contains the PlasmaBurst weapon
*/
#ifndef PLASMA_BURST_HXX_
#define PLASMA_BURST_HXX_
#include <vector>
#include "src/sim/game_object.hxx"
#include "src/sim/objdl.hxx"
#include "explode_listener.hxx"
class Ship;
#define PLASMA_BURST_RADIUS 0.005f ///< Radius of PlasmaBurst
//Half mass every second
#define PB_DEGREDATION 0.5f ///< Amount to multiply mass by every scond for PlasmaBurst
#define PB_SPEED 0.00125f ///< Launch speed of PlasmaBurst
/** A PlasmaBurst is a very small, unguided projectile that
* expells mass over time (leaving a trail) and inflicts
* medium damage in a very concentrated area.
*
* The actual projectile in only a few pixels across.
*/
class PlasmaBurst : public GameObject {
friend class INO_PlasmaBurst;
friend class ENO_PlasmaBurst;
friend class ExplodeListener<PlasmaBurst>;
private:
ExplodeListener<PlasmaBurst>* explodeListeners;
Ship* parent;
float mass;
float direction;
//Delay arming until 50ms after firing,
//so that we do not collide with the launcher
float timeUntilArm;
/* Don't arm while we are still within our parent's shields. */
bool inParentsShields, hitParentsShields;
float timeSinceLastExplosion;
CollisionRectangle colrect;
bool exploded;
//Pointer to our graphical trail
ObjDL trail;
unsigned blame;
//For the net
PlasmaBurst(GameField*, float x, float y, float vx, float vy, float theta,
float mass);
public:
/**
* Constructs a PlasmaBurst with the given parms.
*
* @param field The field the PlasmaBurst will live in
* @param par The Ship that launched the PlasmaBurst
* @param x Initial X coordinate
* @param y Initial Y coordinate
* @param sourceVX Base X velocity (not including launch speed)
* @param sourceVY Base Y velocity (ont including launch speed)
* @param theta Launch direction
* @param mass Initial mass
*/
PlasmaBurst(GameField* field, Ship* par, float x, float y, float sourceVX,
float sourceVY, float theta, float mass);
virtual ~PlasmaBurst();
virtual bool update(float) noth;
virtual void draw() noth;
virtual CollisionResult checkCollision(GameObject*) noth;
//Default works
//virtual std::vector<CollisionRectangle*>* getCollisionBounds() noth;
virtual bool collideWith(GameObject*) noth;
virtual float getRadius() const noth;
virtual float getRotation() const noth { return direction; }
float getMass() const { return mass; } ///<Returns the mass of the PlasmaBurst
private:
void explode(GameObject*) noth;
};
#endif /*PLASMA_BURST_HXX_*/
| 27.914894 | 87 | 0.728277 | AltSysrq |
6d7a7281785338e4e117a613d7e16f2e6693e57c | 2,127 | cpp | C++ | src/MEL/Communications/MelNet.cpp | mahilab/MEL | b877b2ed9cd265b1ee3c1cc623a339ec1dc73185 | [
"Zlib"
] | 6 | 2018-09-14T05:07:03.000Z | 2021-09-30T17:15:11.000Z | src/MEL/Communications/MelNet.cpp | mahilab/MEL | b877b2ed9cd265b1ee3c1cc623a339ec1dc73185 | [
"Zlib"
] | null | null | null | src/MEL/Communications/MelNet.cpp | mahilab/MEL | b877b2ed9cd265b1ee3c1cc623a339ec1dc73185 | [
"Zlib"
] | 3 | 2018-09-20T00:58:31.000Z | 2022-02-09T06:02:56.000Z | #include <MEL/Communications/MelNet.hpp>
#include <MEL/Core/Console.hpp>
namespace mel {
//==============================================================================
// CLASS DEFINITIONS
//==============================================================================
MelNet::MelNet(unsigned short local_port, unsigned short remote_port,
IpAddress remote_address, bool blocking) :
local_port_(local_port),
remote_port_(remote_port),
remote_address_(remote_address)
{
socket_.bind(local_port_);
set_blocking(blocking);
}
void MelNet::send_data(const std::vector<double>& data) {
packet_send_.clear();
for (std::size_t i = 0; i < data.size(); ++i)
packet_send_ << data[i];
socket_.send(packet_send_, remote_address_, remote_port_);
}
std::vector<double> MelNet::receive_data() {
IpAddress sender;
unsigned short port;
if(socket_.receive(packet_receive_, sender, port) != Socket::NotReady) {
std::size_t bytes = packet_receive_.get_data_size();
std::size_t size = bytes / 8;
std::vector<double> data(size);
for (std::size_t i = 0; i < size; ++i)
packet_receive_ >> data[i];
packet_receive_.clear();
return data;
} else {
return std::vector<double>();
}
}
void MelNet::send_message(const std::string& message) {
packet_send_.clear();
packet_send_ << message;
socket_.send(packet_send_, remote_address_, remote_port_);
}
std::string MelNet::receive_message() {
IpAddress sender;
unsigned short port;
if(socket_.receive(packet_receive_, sender, port) != Socket::NotReady) {
std::string message;
packet_receive_ >> message;
packet_receive_.clear();
return message;
} else {
return std::string();
}
}
void MelNet::request() {
send_message("request");
}
bool MelNet::check_request() {
return receive_message() == "request";
}
void MelNet::set_blocking(bool blocking) {
socket_.set_blocking(blocking);
}
bool MelNet::is_blocking() const {
return socket_.is_blocking();
}
} // namespace mel
| 26.924051 | 80 | 0.606488 | mahilab |
6d7c083d95397910ceb0f10e4e0938a20472ddb4 | 4,982 | cc | C++ | examples/BasisConstruction.cc | edoars/latticetester | 980179abe2da78b8a13d2b912d2215b97509c528 | [
"Apache-2.0"
] | null | null | null | examples/BasisConstruction.cc | edoars/latticetester | 980179abe2da78b8a13d2b912d2215b97509c528 | [
"Apache-2.0"
] | 2 | 2018-07-27T15:41:06.000Z | 2019-06-05T17:41:14.000Z | examples/BasisConstruction.cc | edoars/latticetester | 980179abe2da78b8a13d2b912d2215b97509c528 | [
"Apache-2.0"
] | 1 | 2021-03-24T01:11:53.000Z | 2021-03-24T01:11:53.000Z | /**
* This example showcases the usage of the BasisConstruction module. This reads
* matrices from files and builds a basis and a dual for an `IntLatticeBasis`
* object. The files this is set to use are in the `bench.zip` archive. To
* execute the program, the archive should be unziped and the `bench` folder
* should be put in the same directory from which the executable is called.
*
* This example reads matrices from files and performs the different construction
* algorithms in BasisConstruction on them. The program then prints the execution
* time of the various algorithms. Note that the execution of the program is not
* what you would expect in reality since bench contains random full matrices.
*
* This is a sample output for NTL_TYPES_CODE 2:
* GCD LLL DUAL1 DUAL2
* Dim 5 4418 3074 735 1002
* Dim 10 13497 7900 2647 8151
* Dim 15 38502 20984 9543 19052
* Dim 20 94467 44949 88171 50834
* Dim 25 152712 86751 154730 181654
* Dim 30 594683 137168 2970433 1682890
* Dim 35 21994254 221505 168412442 13860037
* */
// This should always use Types 2 or 3, because we get too big numbers with GCD
// elimination.
#define NTL_TYPES_CODE 2
#include <iostream>
#include <ctime>
#include "latticetester/Types.h"
#include "latticetester/BasisConstruction.h"
#include "latticetester/Util.h"
#include "latticetester/ParamReader.h"
#include "latticetester/IntLatticeBasis.h"
#include "Examples.h"
using namespace LatticeTester;
namespace {
const std::string prime = primes[0];
}
int main() {
clock_t timer = clock();
// The different clocks we will use for benchmarking
// We use ctime for implementation simplicity
int max_dim = 6; // Actual max dim is 5*max_dim
clock_t gcd_time[max_dim], lll_time[max_dim],
dual1_time[max_dim], dual2_time[max_dim], totals[4];
for (int i = 0; i < max_dim; i++) {
gcd_time[i] = 0;
lll_time[i] = 0;
dual1_time[i] = 0;
dual2_time[i] = 0;
}
// Defining constants for the execution of the algorithms
BasisConstruction<BScal> constr; // The basis constructor we will use
BMat bas_mat, dua_mat;
clock_t tmp;
for (int j = 0; j < max_dim; j++) {
for (int k = 0; k < 10; k++) {
//! Reader shenanigans
std::string name = "bench/" + prime + "_" + std::to_string((j+1)*5) + "_" + std::to_string(k);
ParamReader<MScal, BScal, RScal> reader(name + ".dat");
reader.getLines();
int numlines;
unsigned int ln;
reader.readInt(numlines, 0, 0);
BMat bas_mat, dua_mat;
bas_mat.SetDims(numlines, numlines);
dua_mat.SetDims(numlines, numlines);
ln = 1;
//! Filling the matrix
reader.readBMat(bas_mat, ln, 0, numlines);
// Creating a lattice basis
IntLatticeBasis<MScal, BScal, NScal, RScal> lattice(bas_mat, numlines);
//! We want to avoid singular matrix because we can't compute the dual, and
//! IntLatticeBasis only really supports square matrices.
if (NTL::determinant(bas_mat) == 0) {
std::cout << name << " is singular\n";
continue;
}
// Timing GCDConstruction first
tmp = clock();
constr.GCDConstruction(bas_mat);
MScal modulo(1);
gcd_time[j] += clock() - tmp;
// Timing DualConstruction
tmp = clock();
constr.DualConstruction(bas_mat, dua_mat, modulo);
dual1_time[j] += clock() - tmp;
// Timing LLLConstruction next
tmp = clock();
constr.LLLConstruction(lattice.getBasis());
modulo = MScal(1);
lll_time[j] += clock() - tmp;
// The following works, but does not set all the properties of lattice to
// properly work with a dual.
tmp = clock();
constr.DualConstruction(lattice.getBasis(), lattice.getDualBasis(), modulo);
dual2_time[j] += clock() - tmp;
// This sets the lattice to know it has a dual. Computing the norm of the
// vectors in the lattice would also be wise.
lattice.setDualFlag(true);
}
}
std::cout << " ";
int width1 = getWidth(gcd_time, max_dim, "GCD", totals, 0);
int width2 = getWidth(lll_time, max_dim, "LLL", totals, 1);
int width3 = getWidth(dual1_time, max_dim, "DUAL1", totals, 2);
int width4 = getWidth(dual2_time, max_dim, "DUAL2", totals, 3);
std::cout << std::endl;
std::cout << "Total time" << std::setw(width1) << totals[0]
<< std::setw(width2) << totals[1]
<< std::setw(width3) << totals[2]
<< std::setw(width4) << totals[3] << std::endl;
for (int i = 0; i < max_dim; i++) {
std::cout << "Dim" << std::setw(6) << (i+1)*5
<< std::setw(width1) << gcd_time[i] << std::setw(width2) << lll_time[i]
<< std::setw(width3) << dual1_time[i] << std::setw(width4) << dual2_time[i];
std::cout << std::endl;
}
std::cout << "Total time: " << (double)(clock()-timer)/(CLOCKS_PER_SEC*60) << " minutes\n";
return 0;
}
| 35.841727 | 100 | 0.639101 | edoars |
6d7c92142604f62e5fd6bd3eef052833313fcabe | 1,575 | cpp | C++ | hackerrank/30.days.of.code.2016.01/18/main.cpp | seirion/code | 3b8bf79764107255185061cec33decbc2235d03a | [
"Apache-2.0"
] | 13 | 2015-06-07T09:26:26.000Z | 2019-05-01T13:23:38.000Z | hackerrank/30.days.of.code.2016.01/18/main.cpp | seirion/code | 3b8bf79764107255185061cec33decbc2235d03a | [
"Apache-2.0"
] | null | null | null | hackerrank/30.days.of.code.2016.01/18/main.cpp | seirion/code | 3b8bf79764107255185061cec33decbc2235d03a | [
"Apache-2.0"
] | 4 | 2016-03-05T06:21:05.000Z | 2017-02-17T15:34:18.000Z | // hackerrank 30 Days of Code
// https://www.hackerrank.com/contests/30-days-of-code/challenges/day-18-queues-stacks
// Day 18: Queues & Stacks!
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
class Palindrome {
public:
Palindrome() {}
void pushCharacter(char c) { s.push(c); }
char popCharacter() {
char c = s.top();
s.pop();
return c;
}
void enqueueCharacter(char c) { q.push(c); }
char dequeueCharacter() {
char c = q.front();
q.pop();
return c;
}
private:
stack<char> s;
queue<char> q;
};
int main() {
// read the string s.
string s;
getline(cin, s);
// create the Palindrome class object p.
Palindrome p;
// push all the characters of string s to stack.
for (int i = 0; i < s.length(); i++) {
p.pushCharacter(s[i]);
}
// enqueue all the characters of string s to queue.
for (int i = 0; i < s.length(); i++) {
p.enqueueCharacter(s[i]);
}
bool f = true;
// pop the top character from stack.
// dequeue the first character from queue.
// compare both the characters.
for (int i = 0; i < s.length(); i++) {
if (p.popCharacter() != p.dequeueCharacter()) {
f = false;
break;
}
}
// finally print whether string s is palindrome or not.
if (f) {
cout << "The word, " << s << ", is a palindrome.";
} else {
cout << "The word, " << s << ", is not a palindrome.";
}
return 0;
}
| 21.283784 | 86 | 0.545397 | seirion |
6d80f76dc0278e4c0b9eb70de9b7aac5878be607 | 2,044 | cc | C++ | src/Core/Datatypes/Datatype.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 2 | 2021-12-17T05:50:44.000Z | 2021-12-22T21:37:32.000Z | src/Core/Datatypes/Datatype.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | null | null | null | src/Core/Datatypes/Datatype.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 1 | 2020-11-30T04:46:05.000Z | 2020-11-30T04:46:05.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2020 The University of Utah
*
* 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.
*/
/*
* Datatype.cc: The Datatype Data type
*
* Written by:
* David Weinstein
* Department of Computer Science
* University of Utah
* July 1994
*
*/
#include <Core/Datatypes/Datatype.h>
#include <Core/Parallel/MasterLock.h>
#include <Core/Util/Assert.h>
#include <atomic>
namespace Uintah {
static std::atomic<int32_t> current_generation{1};
static Uintah::MasterLock init_lock{};
int
Datatype::compute_new_generation()
{
return current_generation.fetch_add(1, std::memory_order_relaxed);
}
Datatype::Datatype()
: ref_cnt(0),
generation(compute_new_generation())
{
}
Datatype::Datatype(const Datatype&)
: ref_cnt(0),
generation(compute_new_generation())
{
}
Datatype& Datatype::operator=(const Datatype&)
{
ASSERT(ref_cnt == 1);
generation = compute_new_generation();
return *this;
}
Datatype::~Datatype()
{
}
} // End namespace Uintah
| 24.926829 | 79 | 0.734834 | damu1000 |
6d841ced44f8ed4ce512ffca9d898fc30825bf86 | 676 | cpp | C++ | samples/01_programming 101/2016/nestedcycles/nestedcycles.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 32 | 2016-11-24T01:40:21.000Z | 2021-11-01T19:24:22.000Z | samples/01_programming 101/2016/nestedcycles/nestedcycles.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 6 | 2016-10-15T05:57:00.000Z | 2021-08-13T12:29:24.000Z | samples/01_programming 101/2016/nestedcycles/nestedcycles.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 49 | 2016-01-26T13:36:02.000Z | 2022-03-16T10:24:41.000Z | #include <iostream>
using namespace std;
int main ()
{
double doubleM[5][5]={-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1};
cin >> doubleM[0][0];
cin >> doubleM[1][1];
cin >> doubleM[2][2];
cin >> doubleM[3][3];
cin >> doubleM[4][4];
for (int counter = 0; counter < 5; counter++)
cin >> doubleM[counter][counter];
for (int counter = 0; counter < 5; counter++)
cin >> doubleM[counter][4-counter];
for (int counter = 0; counter < 5; counter++)
cin >> doubleM[counter][2];
char stringMatrix [5][5][11];
cin >> stringMatrix[4][4];
//cout << stri
cout << doubleM[4][4];
} | 17.789474 | 46 | 0.519231 | code-hunger |
6d84c3ce7fb3a332a742716b8b567c901e1e67b3 | 1,848 | hpp | C++ | Nacro/SDK/FN_LobbyTimer_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_LobbyTimer_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_LobbyTimer_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function LobbyTimer.LobbyTimer_C.Handle Lobby Timer Updated
struct ULobbyTimer_C_Handle_Lobby_Timer_Updated_Params
{
int Seconds_Remaining; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function LobbyTimer.LobbyTimer_C.Handle Show Lobby Timer
struct ULobbyTimer_C_Handle_Show_Lobby_Timer_Params
{
bool Show; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function LobbyTimer.LobbyTimer_C.Bind Delegates
struct ULobbyTimer_C_Bind_Delegates_Params
{
};
// Function LobbyTimer.LobbyTimer_C.Show Lobby Timer
struct ULobbyTimer_C_Show_Lobby_Timer_Params
{
bool Show; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function LobbyTimer.LobbyTimer_C.Handle Lobby Disconnected
struct ULobbyTimer_C_Handle_Lobby_Disconnected_Params
{
};
// Function LobbyTimer.LobbyTimer_C.Handle Lobby Started
struct ULobbyTimer_C_Handle_Lobby_Started_Params
{
};
// Function LobbyTimer.LobbyTimer_C.Construct
struct ULobbyTimer_C_Construct_Params
{
};
// Function LobbyTimer.LobbyTimer_C.ExecuteUbergraph_LobbyTimer
struct ULobbyTimer_C_ExecuteUbergraph_LobbyTimer_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 28 | 152 | 0.577922 | Milxnor |
6d89a10fcd8756b6c37a65374296790657a488d3 | 64,107 | cpp | C++ | 0.55.402/graysvr/CChar.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | 2 | 2020-12-22T17:03:14.000Z | 2021-07-31T23:59:05.000Z | 0.55.402/graysvr/CChar.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | null | null | null | 0.55.402/graysvr/CChar.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | 4 | 2021-04-21T19:43:48.000Z | 2021-10-07T00:38:23.000Z | //
// CChar.cpp
// Copyright Menace Software (www.menasoft.com).
// CChar is either an NPC or a Player.
//
#include "graysvr.h" // predef header.
#include "CClient.h"
LPCTSTR const CChar::sm_szTrigName[CTRIG_QTY+1] = // static
{
_TEXT("@AAAUNUSED"),
_TEXT("@Attack"), // I am attacking someone (SRC)
_TEXT("@CallGuards"),
_TEXT("@Click"), // I got clicked on by someone.
_TEXT("@Create"), // Newly created (not in the world yet)
_TEXT("@DClick"), // Someone has dclicked on me.
_TEXT("@Death"), //+I just got killed.
_TEXT("@DeathCorpse"),
_TEXT("@Destroy"), // Permanently gone.
_TEXT("@EnvironChange"), // my environment changed somehow (light,weather,season,region)
_TEXT("@FearOfDeath"), // I'm not healthy.
_TEXT("@FightSwing"), // randomly choose to speak while fighting.
_TEXT("@GetHit"), // I just got hit.
_TEXT("@Hit"), // I just hit someone. (TARG)
_TEXT("@HitMiss"), // I just missed.
_TEXT("@HitTry"), // I am trying to hit someone. starting swing.
// ITRIG_QTY
"@itemClick", // I clicked on an item
"@itemCreate_UNUSED",
"@itemDAMAGE", // I have damaged item in some way
"@itemDCLICK", // I have dclicked item
"@itemDestroy_UNUSED",
"@itemDropOn_Char", // I have been dropped on this char
"@itemDropOn_Ground", // I dropped an item on the ground
"@itemDropOn_Item", // I have been dropped on this item
"@itemDropOn_Self", // An item has been dropped on
"@itemEQUIP", // I have equipped an item
"@itemEQUIPTEST",
"@itemPICKUP_GROUND",
"@itemPICKUP_PACK", // picked up from inside some container.
"@itemPICKUP_SELF", // picked up from this container
"@itemSPELL", // cast some spell on the item.
"@itemSTACKON", // stacked item on another item
"@itemSTEP", // stepped on an item
"@itemTARGON_CANCEL",
"@itemTARGON_CHAR",
"@itemTARGON_GROUND",
"@itemTARGON_ITEM", // I am being combined with an item
"@itemTIMER_UNUSED",
"@itemToolTip", // Did tool tips on an item
"@itemUNEQUIP", // i have unequipped (or try to unequip) an item
"@LogIn", // Client logs in
"@LogOut", // Client logs out (21)
"@NPCAcceptItem", // (NPC only) i've been given an item i like (according to DESIRES)
"@NPCActFight",
"@NPCActFollow", // (NPC only) following someone right now
"@NPCHearGreeting", // (NPC only) i have been spoken to for the first time. (no memory of previous hearing)
"@NPCHearNeed", // (NPC only) i heard someone mention something i need. (11)
"@NPCHearUnknown", //+(NPC only) I heard something i don't understand.
"@NPCLookAtChar", // (NPC only) look at a character
"@NPCLookAtItem", // (NPC only) look at a character
"@NPCRefuseItem", // (NPC only) i've been given an item i don't want.
"@NPCRestock", // (NPC only)
"@NPCSeeNewPlayer", //+(NPC only) i see u for the first time. (in 20 minutes) (check memory time)
"@NPCSeeWantItem", // (NPC only) i see something good.
"@PersonalSpace", //+i just got stepped on.
"@Profile", // someone hit the profile button for me.
"@ReceiveItem", // I was just handed an item (Not yet checked if i want it)
"@SeeCrime", // I saw a crime
// SKTRIG_QTY
"@SkillAbort",
"@SkillFail",
"@SkillGain",
"@SkillMakeItem",
"@SkillSelect",
"@SkillStart",
"@SkillStroke",
"@SkillSuccess",
"@SpellBook",
"@SpellCast", //+Char is casting a spell.
"@SpellEffect", //+A spell just hit me.
"@Step", // Very expensive!
"@ToolTip", // someone did tool tips on me.
"@UserChatButton",
"@UserExtCmd",
"@UserExWalkLimit",
"@UserMailBag",
"@UserOverrideRecv",
"@UserOverrideSend",
"@UserSkills",
"@UserStats",
"@UserVirtue",
"@UserWarmode",
// War mode ?
NULL,
};
/////////////////////////////////////////////////////////////////
// -CChar
CChar * CChar::CreateBasic( CREID_TYPE baseID ) // static
{
// Create the "basic" NPC. Not NPC or player yet.
// NOTE: NEVER return NULL
return( new CChar( baseID ));
}
CChar * CChar::CreateNPC( CREID_TYPE baseID ) // static
{
// Create an NPC
// NOTE: NEVER return NULL
CChar * pChar = CreateBasic( baseID );
ASSERT(pChar);
pChar->NPC_LoadScript(true);
return( pChar );
}
CChar::CChar( CREID_TYPE baseID ) : CObjBase( false )
{
g_Serv.StatInc( SERV_STAT_CHARS ); // Count created CChars.
m_pArea = NULL;
m_pParty = NULL;
m_pClient = NULL; // is the char a logged in player ?
m_pPlayer = NULL; // May even be an off-line player !
m_pNPC = NULL;
m_StatFlag = 0;
if ( g_World.m_fSaveParity )
{
StatFlag_Set( STATF_SaveParity ); // It will get saved next time.
}
m_dirFace = DIR_SE;
m_fonttype = FONT_NORMAL;
m_defense = 0;
m_atUnk.m_Arg1 = 0;
m_atUnk.m_Arg2 = 0;
m_atUnk.m_Arg3 = 0;
m_timeLastRegen = m_timeCreate = CServTime::GetCurrentTime();
m_timeLastHitsUpdate = m_timeLastRegen;
m_fHitsUpdate = false;
m_prev_Hue = HUE_DEFAULT;
m_prev_id = CREID_INVALID;
SetID( baseID );
CCharBase* pCharDef = Char_GetDef();
ASSERT(pCharDef);
SetName( pCharDef->GetTypeName()); // set the name in case there is a name template.
Skill_Cleanup();
g_World.m_uidLastNewChar = GetUID(); // for script access.
int i=0;
for ( ; i < STAT_QTY; i++ )
{
Stat_SetBase( (STAT_TYPE) i, 0 );
Stat_SetMod( (STAT_TYPE) i, 0 );
Stat_SetVal( (STAT_TYPE) i, 0 );
Stat_SetMax( (STAT_TYPE) i, 0 );
}
Stat_SetVal( STAT_FOOD, Stat_GetMax(STAT_FOOD) );
for ( i=0;i<MAX_SKILL;i++)
{
m_Skill[i] = 0;
}
m_LocalLight = 0;
m_fClimbUpdated = false;
ASSERT( IsDisconnected());
}
CChar::~CChar() // Delete character
{
DeletePrepare(); // remove me early so virtuals will work.
if ( IsStatFlag( STATF_Ridden ))
{
CItem * pItem = Horse_GetMountItem();
if ( pItem )
{
pItem->m_itFigurine.m_UID.InitUID(); // unlink it first.
pItem->Delete();
}
}
if ( IsClient()) // this should never happen.
{
ASSERT( m_pClient );
m_pClient->m_fClosed = true;
}
if ( m_pParty )
{
m_pParty->RemoveChar( GetUID(), (DWORD) GetUID() );
m_pParty = NULL;
}
DeleteAll(); // remove me early so virtuals will work.
ClearNPC();
ClearPlayer();
g_Serv.StatDec( SERV_STAT_CHARS );
}
void CChar::ClientDetach()
{
// Client is detaching from this CChar.
if ( ! IsClient())
return;
CancelAllTrades();
if ( m_pParty && m_pParty->IsPartyMaster( this ))
{
// Party must disband if the master is logged out.
m_pParty->Disband(GetUID());
m_pParty = NULL;
}
// If this char is on a IT_SHIP then we need to stop the ship !
if ( m_pArea && m_pArea->IsFlag( REGION_FLAG_SHIP ))
{
CItemMulti * pShipItem = dynamic_cast <CItemMulti *>( m_pArea->GetResourceID().ItemFind());
if ( pShipItem )
{
pShipItem->Ship_Stop();
}
}
CSector * pSector = GetTopSector();
pSector->ClientDetach( this );
m_pClient = NULL;
}
void CChar::ClientAttach( CClient * pClient )
{
// Client is Attaching to this CChar.
if ( GetClient() == pClient )
return;
DEBUG_CHECK( ! IsClient());
DEBUG_CHECK( pClient->GetAccount());
if ( ! SetPlayerAccount( pClient->GetAccount())) // i now own this char.
return;
ASSERT(m_pPlayer);
m_pPlayer->m_timeLastUsed = CServTime::GetCurrentTime();
m_pClient = pClient;
GetTopSector()->ClientAttach( this );
FixClimbHeight();
}
void CChar::SetDisconnected()
{
// Client logged out or NPC is dead.
if ( IsClient())
{
GetClient()->m_fClosed = true;
return;
}
if ( m_pParty )
{
m_pParty->RemoveChar( GetUID(), (DWORD) GetUID() );
m_pParty = NULL;
}
if ( IsDisconnected())
return;
DEBUG_CHECK( GetParent());
RemoveFromView(); // Remove from views.
// DEBUG_MSG(( "Disconnect '%s'" DEBUG_CR, (LPCTSTR) GetName()));
MoveToRegion(NULL,false);
GetTopSector()->m_Chars_Disconnect.InsertHead( this );
DEBUG_CHECK( IsDisconnected());
}
int CChar::IsWeird() const
{
// RETURN: invalid code.
int iResultCode = CObjBase::IsWeird();
if ( iResultCode )
return iResultCode;
if ( IsDisconnected())
{
if ( ! GetTopSector()->IsCharDisconnectedIn( this ))
{
iResultCode = 0x1102;
return iResultCode;
}
if ( m_pNPC )
{
if ( IsStatFlag( STATF_Ridden ))
{
if ( Skill_GetActive() != NPCACT_RIDDEN )
{
iResultCode = 0x1103;
return iResultCode;
}
// Make sure we are still linked back to the world.
CItem * pItem = Horse_GetMountItem();
if ( pItem == NULL )
{
iResultCode = 0x1104;
return iResultCode;
}
if ( pItem->m_itFigurine.m_UID != GetUID())
{
iResultCode = 0x1105;
return iResultCode;
}
}
else
{
if ( ! IsStatFlag( STATF_DEAD ))
{
iResultCode = 0x1106;
return iResultCode;
}
}
}
}
if ( ! m_pPlayer && ! m_pNPC )
{
iResultCode = 0x1107;
return iResultCode;
}
if ( ! GetTopPoint().IsValidPoint())
{
iResultCode = 0x1108;
return iResultCode;
}
return( 0 );
}
int CChar::FixWeirdness()
{
// Clean up weird flags.
// fix Weirdness.
// NOTE:
// Deleting a player char is VERY BAD ! Be careful !
//
// RETURN: false = i can't fix this.
int iResultCode = CObjBase::IsWeird();
if ( iResultCode )
// Not recoverable - must try to delete the object.
return( iResultCode );
// NOTE: Stats and skills may go negative temporarily.
CCharBase * pCharDef = Char_GetDef();
if ( g_World.m_iLoadVersion <= 35 )
{
if ( IsStatFlag( STATF_Ridden ))
{
m_atRidden.m_FigurineUID.InitUID();
Skill_Start( NPCACT_RIDDEN );
}
}
if ( g_World.m_iLoadVersion < 54 )
{
StatFlag_Clear( STATF_RespawnNPC ); // meant nothing then
}
// Make sure my flags are good.
if ( IsStatFlag( STATF_Insubstantial ))
{
if ( ! IsStatFlag( STATF_DEAD ) && ! IsPriv(PRIV_GM) && GetPrivLevel() < PLEVEL_Seer )
{
StatFlag_Clear( STATF_Insubstantial );
}
}
if ( IsStatFlag( STATF_HasShield ))
{
CItem * pShield = LayerFind( LAYER_HAND2 );
if ( pShield == NULL )
{
StatFlag_Clear( STATF_HasShield );
}
}
if ( IsStatFlag( STATF_OnHorse ))
{
CItem * pHorse = LayerFind( LAYER_HORSE );
if ( pHorse == NULL )
{
StatFlag_Clear( STATF_OnHorse );
}
}
if ( IsStatFlag( STATF_Spawned ))
{
CItemMemory * pMemory = Memory_FindTypes( MEMORY_ISPAWNED );
if ( pMemory == NULL )
{
StatFlag_Clear( STATF_Spawned );
}
}
if ( IsStatFlag( STATF_Pet ))
{
CItemMemory * pMemory = Memory_FindTypes( MEMORY_IPET );
if ( pMemory == NULL )
{
StatFlag_Clear( STATF_Pet );
}
}
if ( IsStatFlag( STATF_Ridden ))
{
// Move the ridden creature to the same location as it's rider.
if ( m_pPlayer || ! IsDisconnected())
{
StatFlag_Clear( STATF_Ridden );
}
else
{
if ( Skill_GetActive() != NPCACT_RIDDEN )
{
iResultCode = 0x1203;
return iResultCode;
}
CItem * pFigurine = Horse_GetMountItem();
if ( pFigurine == NULL )
{
iResultCode = 0x1204;
return iResultCode;
}
CPointMap pt = pFigurine->GetTopLevelObj()->GetTopPoint();
if ( pt != GetTopPoint())
{
MoveToChar( pt );
SetDisconnected();
}
}
}
if ( IsStatFlag( STATF_Criminal ))
{
// make sure we have a criminal flag timer ?
}
if ( ! IsIndividualName() && pCharDef->GetTypeName()[0] == '#' )
{
SetName( pCharDef->GetTypeName());
}
if ( ! CCharBase::IsValidDispID( GetID()) && CCharBase::IsHumanID( m_prev_id ))
{
// This is strange. (has human body)
m_prev_id = GetID();
}
if ( m_pPlayer ) // Player char.
{
DEBUG_CHECK( ! IsStatFlag( STATF_Pet | STATF_Ridden | STATF_Spawned ));
Memory_ClearTypes(MEMORY_ISPAWNED|MEMORY_IPET);
StatFlag_Clear( STATF_Ridden );
if ( m_pPlayer->GetSkillClass() == NULL ) // this hsould never happen.
{
m_pPlayer->SetSkillClass( this, RESOURCE_ID( RES_SKILLCLASS ));
ASSERT(m_pPlayer->GetSkillClass());
}
// Make sure players don't get ridiculous stats.
if ( GetPrivLevel() <= PLEVEL_Player )
{
for ( int i=0; i<MAX_SKILL; i++ )
{
int iSkillMax = Skill_GetMax( (SKILL_TYPE)i );
int iSkillVal = Skill_GetBase( (SKILL_TYPE)i );
if ( iSkillVal < 0 )
Skill_SetBase( (SKILL_TYPE)i, 0 );
if ( iSkillVal > iSkillMax * 2 )
Skill_SetBase( (SKILL_TYPE)i, iSkillMax );
}
// ??? What if magically enhanced !!!
if ( IsHuman() &&
GetPrivLevel() < PLEVEL_Counsel &&
! IsStatFlag( STATF_Polymorph ))
{
for ( int j=STAT_STR; j<STAT_BASE_QTY; j++ )
{
int iStatMax = Stat_GetLimit((STAT_TYPE)j);
if ( Stat_GetAdjusted((STAT_TYPE)j) > iStatMax*2 )
{
Stat_SetBase((STAT_TYPE)j, iStatMax );
}
}
}
}
}
else
{
if ( ! m_pNPC )
{
// Make it into an NPC ???
iResultCode = 0x1205;
return iResultCode;
}
if ( ! strcmp( GetName(), "ship" ))
{
// version .37 cleanup code.
iResultCode = 0x1206;
return iResultCode;
}
// An NPC. Don't keep track of unused skills.
for ( int i=0; i<MAX_SKILL; i++ )
{
if ( m_Skill[i] && m_Skill[i] <= 10 )
Skill_SetBase( (SKILL_TYPE)i, 0 );
}
}
if ( GetTimerAdjusted() > 60*60 )
{
// unreasonably long for a char?
SetTimeout(1);
}
// FixWeight();
return IsWeird();
}
void CChar::CreateNewCharCheck()
{
// Creating a new char. (Not loading from save file)
// MAke sure things are set to reasonable values.
m_prev_id = GetID();
m_prev_Hue = GetHue();
Stat_SetVal( STAT_STR, Stat_GetMax(STAT_STR) );
Stat_SetVal( STAT_DEX, Stat_GetMax(STAT_DEX) );
Stat_SetVal( STAT_INT, Stat_GetMax(STAT_INT) );
if ( ! m_pPlayer ) // need a starting brain tick.
{
SetTimeout(1);
}
}
bool CChar::ReadScriptTrig( CCharBase * pCharDef, CTRIG_TYPE trig )
{
if ( pCharDef == NULL )
return( false );
if ( ! pCharDef->HasTrigger( trig ))
return( false );
CResourceLock s;
if ( ! pCharDef->ResourceLock(s))
return( false );
if ( ! OnTriggerFind( s, sm_szTrigName[trig] ))
return( false );
return( ReadScript( s ));
}
bool CChar::ReadScript( CResourceLock &s )
{
// If this is a regen they will have a pack already.
// fRestock = this is a vendor restock.
// fNewbie = newbiize all the stuff we get.
// NOTE:
// It would be nice to know the total $ value of items created here !
// RETURN:
// true = default return. (mostly ignored).
bool fFullInterp = false;
bool fIgnoreAttributes = false;
CItem * pItem = NULL;
while ( s.ReadKeyParse())
{
if ( s.IsKeyHead( "ON", 2 ))
break;
int iCmd = FindTableSorted( s.GetKey(), CItem::sm_szTemplateTable, COUNTOF( CItem::sm_szTemplateTable )-1 );
switch ( iCmd )
{
case ITC_FULLINTERP:
{
LPCTSTR pszArgs = s.GetArgStr();
GETNONWHITESPACE( pszArgs );
if ( !*pszArgs )
fFullInterp = true;
else
fFullInterp = s.GetArgVal();
continue;
}
case ITC_NEWBIESWAP:
{
if ( !pItem || fIgnoreAttributes )
continue;
if ( pItem->IsAttr( ATTR_NEWBIE ) )
{
if ( Calc_GetRandVal( s.GetArgVal() ) == 0 )
pItem->ClrAttr(ATTR_NEWBIE);
}
else
{
if ( Calc_GetRandVal( s.GetArgVal() ) == 0 )
pItem->SetAttr(ATTR_NEWBIE);
}
continue;
}
case ITC_ITEM:
case ITC_CONTAINER:
case ITC_ITEMNEWBIE:
{
// Possible loot/equipped item.
fIgnoreAttributes = true;
if ( IsStatFlag( STATF_Conjured ) && iCmd != ITC_ITEMNEWBIE ) // This check is not needed.
break; // conjured creates have no loot.
pItem = CItem::CreateHeader( s.GetArgRaw(), this, iCmd == ITC_ITEMNEWBIE );
if ( pItem == NULL )
continue;
if ( iCmd == ITC_ITEMNEWBIE )
{
pItem->SetAttr(ATTR_NEWBIE);
}
if ( pItem->IsItemInContainer() || pItem->IsItemEquipped())
fIgnoreAttributes = false;
continue;
}
case ITC_BUY:
case ITC_SELL:
{
fIgnoreAttributes = true;
CItemContainer * pCont = GetBank((iCmd == ITC_SELL) ? LAYER_VENDOR_STOCK : LAYER_VENDOR_BUYS );
if ( pCont == NULL )
{
DEBUG_ERR(( "NPC '%s', is not a vendor!" DEBUG_CR, (LPCTSTR) GetResourceName()));
continue;
}
pItem = CItem::CreateHeader( s.GetArgRaw(), pCont, false );
if ( pItem == NULL )
continue;
if ( pItem->IsItemInContainer())
{
fIgnoreAttributes = false;
pItem->SetContainedLayer( pItem->GetAmount()); // set the Restock amount.
}
continue;
}
}
if ( fIgnoreAttributes ) // some item creation failure.
continue;
if ( pItem != NULL )
{
if ( fFullInterp ) // Modify the item.
pItem->r_Verb( s, &g_Serv );
else
pItem->r_LoadVal( s );
}
else
{
TRIGRET_TYPE tRet = OnTriggerRun( s, TRIGRUN_SINGLE_EXEC, &g_Serv, NULL );
if ( (tRet == TRIGRET_RET_FALSE) && fFullInterp )
;
else if ( tRet != TRIGRET_RET_DEFAULT )
{
return (tRet == TRIGRET_RET_FALSE);
}
}
}
return( true );
}
void CChar::NPC_LoadScript( bool fRestock )
{
// Create an NPC from script.
if ( m_pNPC == NULL )
{
// Set a default brian type til we get the real one from scripts.
SetNPCBrain( GetNPCBrain( true ) ); // should have a default brain. watch out for override vendor.
}
CCharBase * pCharDef = Char_GetDef();
ReadScriptTrig( pCharDef, CTRIG_Create );
//Add real on=@create here!!!
if ( fRestock )
{
// OnTrigger( CTRIG_NPCRestock, &g_Serv );
ReadScriptTrig( pCharDef, CTRIG_NPCRestock );
}
if ( NPC_IsVendor())
{
// Restock it now so it can buy/sell stuff immediately
NPC_Vendor_Restock( 15*60 );
}
CreateNewCharCheck();
}
void CChar::OnWeightChange( int iChange )
{
CContainer::OnWeightChange( iChange );
UpdateStatsFlag();
}
bool CChar::SetName( LPCTSTR pszName )
{
return SetNamePool( pszName );
}
void CChar::SetID( CREID_TYPE id )
{
// Just set the base id and not the actual display id.
// NOTE: Never return NULL
CCharBase * pCharDef = CCharBase::FindCharBase( id );
if ( pCharDef == NULL )
{
if ( id != -1 && id != CREID_INVALID )
{
DEBUG_ERR(( "Create Invalid Char 0%x" DEBUG_CR, id ));
}
pCharDef = Char_GetDef();
if ( pCharDef != NULL )
return;
id = (CREID_TYPE) g_Cfg.ResourceGetIndexType( RES_CHARDEF, "DEFAULTCHAR" );
if ( id < 0 )
{
id = CREID_OGRE;
}
pCharDef = CCharBase::FindCharBase(id);
}
if ( pCharDef == Char_GetDef())
return;
m_BaseRef.SetRef( pCharDef );
if ( m_prev_id == CREID_INVALID )
{
m_prev_id = GetID();
}
if ( GetNPCBrain() != NPCBRAIN_HUMAN )
{
// Transfom to non-human (if they ever where human)
// can't ride a horse in this form.
Horse_UnMount();
UnEquipAllItems(); // unequip all items.
}
}
void CChar::InitPlayer( const CEvent * pBin, CClient * pClient )
{
// Create a brand new Player char.
ASSERT(pClient);
ASSERT(pBin);
SetID( (CREID_TYPE) g_Cfg.ResourceGetIndexType( RES_CHARDEF, ( pBin->Create.m_sex == 0 ) ? "c_MAN" : "c_WOMAN" ));
if ( g_Cfg.IsObscene(pBin->Create.m_charname) || Str_Check(pBin->Create.m_charname) || !strnicmp(pBin->Create.m_charname,"lord ", 5) ||
!strnicmp(pBin->Create.m_charname,"lady ", 5) || !strnicmp(pBin->Create.m_charname,"seer ", 5) || !strnicmp(pBin->Create.m_charname,"gm ", 3) || !strnicmp(pBin->Create.m_charname,"admin ", 5)
|| !strnicmp(pBin->Create.m_charname,"counselor ", 10) || !strnicmp(pBin->Create.m_charname,"admin ", 6) ) // Is the name unacceptable?
{
g_Log.Event( LOGL_WARN|LOGM_ACCOUNTS,
"%x:Unacceptable name '%s' for account '%s'" DEBUG_CR,
pClient->m_Socket.GetSocket(), (LPCTSTR) pBin->Create.m_charname, (LPCTSTR) pClient->GetAccount()->GetName() );
SetNamePool( ( pBin->Create.m_sex == 0 ) ? "#HUMANMALE" : "#HUMANFEMALE" );
}
else
{
SetName( pBin->Create.m_charname );
}
HUE_TYPE wHue;
wHue = pBin->Create.m_wSkinHue | HUE_UNDERWEAR;
if ( wHue < (HUE_UNDERWEAR|HUE_SKIN_LOW) || wHue > (HUE_UNDERWEAR|HUE_SKIN_HIGH))
{
wHue = HUE_UNDERWEAR|HUE_SKIN_LOW;
}
SetHue( wHue );
m_fonttype = FONT_NORMAL;
int iStartLoc = pBin->Create.m_startloc-1;
if ( ! g_Cfg.m_StartDefs.IsValidIndex( iStartLoc ))
iStartLoc = 0;
m_ptHome = g_Cfg.m_StartDefs[iStartLoc]->m_pt;
if ( ! m_ptHome.IsValidPoint())
{
if ( g_Cfg.m_StartDefs.GetCount())
{
m_ptHome = g_Cfg.m_StartDefs[0]->m_pt;
}
DEBUG_ERR(( "Invalid start location for character!" DEBUG_CR ));
}
SetUnkPoint( m_ptHome ); // Don't actaully put me in the world yet.
// randomize the skills first.
int i = 0;
for ( ; i < MAX_SKILL; i++ )
{
Skill_SetBase( (SKILL_TYPE)i, Calc_GetRandVal( g_Cfg.m_iMaxBaseSkill ));
}
if ( pBin->Create.m_str + pBin->Create.m_dex + pBin->Create.m_int > 80 )
{
// ! Cheater !
Stat_SetBase( STAT_STR, 10 );
Stat_SetBase( STAT_DEX, 10 );
Stat_SetBase( STAT_INT, 10 );
g_Log.Event( LOGL_WARN|LOGM_CHEAT,
"%x:Cheater '%s' is submitting hacked char stats" DEBUG_CR,
pClient->m_Socket.GetSocket(), (LPCTSTR) pClient->GetAccount()->GetName());
}
else
{
Stat_SetBase( STAT_STR, pBin->Create.m_str + 1 );
Stat_SetBase( STAT_DEX, pBin->Create.m_dex + 1 );
Stat_SetBase( STAT_INT, pBin->Create.m_int + 1 );
}
if ( pBin->Create.m_val1 > 50 ||
pBin->Create.m_val2 > 50 ||
pBin->Create.m_val3 > 50 ||
pBin->Create.m_val1 + pBin->Create.m_val2 + pBin->Create.m_val3 > 101 )
{
// ! Cheater !
g_Log.Event( LOGL_WARN|LOGM_CHEAT,
"%x:Cheater '%s' is submitting hacked char skills" DEBUG_CR,
pClient->m_Socket.GetSocket(), (LPCTSTR) pClient->GetAccount()->GetName());
}
else
{
if ( IsSkillBase((SKILL_TYPE) pBin->Create.m_skill1))
Skill_SetBase( (SKILL_TYPE) pBin->Create.m_skill1, pBin->Create.m_val1*10 );
if ( IsSkillBase((SKILL_TYPE) pBin->Create.m_skill2))
Skill_SetBase( (SKILL_TYPE) pBin->Create.m_skill2, pBin->Create.m_val2*10 );
if ( IsSkillBase((SKILL_TYPE) pBin->Create.m_skill3))
Skill_SetBase( (SKILL_TYPE) pBin->Create.m_skill3, pBin->Create.m_val3*10 );
}
ITEMID_TYPE id = (ITEMID_TYPE)(WORD) pBin->Create.m_hairid;
if ( id )
{
CItem * pHair = CItem::CreateScript( id, this );
ASSERT(pHair);
if ( ! pHair->IsType(IT_HAIR))
{
// Cheater !
pHair->Delete();
}
else
{
wHue = pBin->Create.m_hairHue;
if ( wHue<HUE_HAIR_LOW || wHue > HUE_HAIR_HIGH )
{
wHue = HUE_HAIR_LOW;
}
pHair->SetHue( wHue );
pHair->SetAttr(ATTR_NEWBIE|ATTR_MOVE_NEVER);
LayerAdd( pHair ); // add content
}
}
id = (ITEMID_TYPE)(WORD) pBin->Create.m_beardid;
if ( id )
{
CItem * pBeard = CItem::CreateScript( id, this );
ASSERT(pBeard);
if ( ! pBeard->IsType(IT_BEARD))
{
// Cheater !
pBeard->Delete();
}
else
{
wHue = pBin->Create.m_beardHue;
if ( wHue < HUE_HAIR_LOW || wHue > HUE_HAIR_HIGH )
{
wHue = HUE_HAIR_LOW;
}
pBeard->SetHue( wHue );
pBeard->SetAttr(ATTR_NEWBIE|ATTR_MOVE_NEVER);
LayerAdd( pBeard ); // add content
}
}
// Create the bank box.
CItemContainer * pBankBox = GetBank( LAYER_BANKBOX );
// Create the pack.
CItemContainer * pPack = GetPackSafe();
// Get special equip for the starting skills.
for ( i=0; i<4; i++ )
{
int iSkill;
if (i)
{
switch ( i )
{
case 1: iSkill = pBin->Create.m_skill1; break;
case 2: iSkill = pBin->Create.m_skill2; break;
case 3: iSkill = pBin->Create.m_skill3; break;
}
}
else
{
iSkill = ( pBin->Create.m_sex == 0 ) ? RES_NEWBIE_MALE_DEFAULT : RES_NEWBIE_FEMALE_DEFAULT;
}
CResourceLock s;
if ( ! g_Cfg.ResourceLock( s, RESOURCE_ID( RES_NEWBIE, iSkill )))
continue;
ReadScript( s );
}
// if ( pClient->m_Crypt.GetClientVer() >= 0x126000 )
{
HUE_TYPE wHue = pBin->Create.m_shirtHue;
CItem * pLayer = LayerFind( LAYER_SHIRT );
if ( pLayer )
{
if ( wHue<HUE_BLUE_LOW || wHue>HUE_DYE_HIGH )
wHue = HUE_DYE_HIGH;
pLayer->SetHue( wHue );
}
wHue = pBin->Create.m_pantsHue;
pLayer = LayerFind( LAYER_PANTS );
if ( pLayer )
{
if ( wHue<HUE_BLUE_LOW || wHue>HUE_DYE_HIGH )
wHue = HUE_DYE_HIGH;
pLayer->SetHue( wHue );
}
}
CreateNewCharCheck();
}
enum CHR_TYPE
{
CHR_ACCOUNT,
CHR_ACT,
CHR_FINDEQUIP,
CHR_FINDLAYER,
CHR_FINDUID,
CHR_MEMORYFIND,
CHR_MEMORYFINDTYPE,
CHR_OWNER,
CHR_REGION,
CHR_SPAWNITEM,
CHR_WEAPON,
CHR_QTY,
};
LPCTSTR const CChar::sm_szRefKeys[CHR_QTY+1] =
{
"ACCOUNT",
"ACT",
"FINDEQUIP",
"FINDLAYER",
"FINDUID",
"MEMORYFIND",
"MEMORYFINDTYPE",
"OWNER",
"REGION",
"SPAWNITEM",
"WEAPON",
NULL,
};
bool CChar::r_GetRef( LPCTSTR & pszKey, CScriptObj * & pRef )
{
int i = FindTableHeadSorted( pszKey, sm_szRefKeys, COUNTOF(sm_szRefKeys)-1 );
if ( i >= 0 )
{
pszKey += strlen( sm_szRefKeys[i] );
SKIP_SEPERATORS(pszKey);
switch (i)
{
case CHR_ACCOUNT:
if ( pszKey[-1] != '.' ) // only used as a ref !
break;
if ( m_pPlayer == NULL )
{
pRef = NULL;
}
else
{
pRef = m_pPlayer->GetAccount();
}
return( true );
case CHR_ACT:
if ( pszKey[-1] != '.' ) // only used as a ref !
break;
pRef = m_Act_Targ.ObjFind();
return( true );
case CHR_FINDEQUIP:
case CHR_FINDLAYER: // Find equipped layers.
pRef = LayerFind( (LAYER_TYPE) Exp_GetSingle( pszKey ));
SKIP_SEPERATORS(pszKey);
return( true );
case CHR_FINDUID: { // Find equipped layers.
CGrayUID uid = (DWORD) Exp_GetVal( pszKey );
pRef = uid.ObjFind();
SKIP_SEPERATORS(pszKey);
return( true );
}
case CHR_MEMORYFINDTYPE: // FInd a type of memory.
pRef = Memory_FindTypes( Exp_GetSingle( pszKey ));
SKIP_SEPERATORS(pszKey);
return( true );
case CHR_MEMORYFIND: // Find a memory of a UID
pRef = Memory_FindObj( (CGrayUID) Exp_GetSingle( pszKey ));
SKIP_SEPERATORS(pszKey);
return( true );
case CHR_OWNER:
pRef = NPC_PetGetOwner();
return( true );
case CHR_SPAWNITEM:
{
CItemMemory * pMemory = Memory_FindTypes( MEMORY_ISPAWNED );
if ( !pMemory )
pRef = NULL;
else
pRef = pMemory->m_uidLink.ItemFind();
return( true );
}
case CHR_WEAPON:
{
pRef = m_uidWeapon.ObjFind();
return( true );
}
case CHR_REGION:
pRef = m_pArea;
return( true );
}
}
if ( r_GetRefContainer( pszKey, pRef ))
{
return( true );
}
return( CObjBase::r_GetRef( pszKey, pRef ));
}
enum CHC_TYPE
{
CHC_AC = 0,
CHC_ACCOUNT,
CHC_ACT,
CHC_ACTARG1,
CHC_ACTARG2,
CHC_ACTARG3,
CHC_ACTDIFF,
CHC_ACTION,
CHC_AGE,
CHC_AR,
CHC_BANKBALANCE,
CHC_BODY,
CHC_CANCAST,
CHC_CANMAKE,
CHC_CANMAKESKILL,
CHC_CANMOVE,
CHC_CREATE,
CHC_DIR,
CHC_DISPIDDEC,
CHC_EMOTEACT,
CHC_FAME,
CHC_FLAGS,
CHC_FONT,
CHC_FOOD,
CHC_GUILDABBREV,
CHC_HITPOINTS,
CHC_HITS,
CHC_HOME,
CHC_ID,
CHC_ISGM,
CHC_ISMYPET,
CHC_ISONLINE,
CHC_ISPLAYER,
CHC_ISVENDOR,
CHC_KARMA,
CHC_LOCALLIGHT,
CHC_MANA,
CHC_MAXHITS,
CHC_MAXMANA,
CHC_MAXSTAM,
CHC_MAXWEIGHT,
CHC_MEMORY,
// CHC_MODAC,
// CHC_MODAR,
// CHC_MODMAXWEIGHT,
// CHC_MODWEIGHTMAX,
CHC_MOVE,
CHC_NAME,
CHC_NIGHTSIGHT,
CHC_NOTOGETFLAG,
CHC_NPC,
CHC_OBODY,
CHC_OSKIN,
CHC_P,
CHC_RANGE,
CHC_SEX,
CHC_SKILLBEST,
CHC_SKILLCHECK,
CHC_SKILLTOTAL,
CHC_STAM,
CHC_STAMINA,
CHC_STONE,
CHC_TITLE,
CHC_TOWNABBREV,
CHC_WEIGHTMAX,
CHC_XBODY,
CHC_XSKIN,
CHC_QTY,
};
LPCTSTR const CChar::sm_szLoadKeys[CHC_QTY+1] =
{
"ac",
"ACCOUNT",
"ACT",
"ACTARG1",
"ACTARG2",
"ACTARG3",
"ACTDIFF",
"ACTION",
"AGE",
"AR",
"bankbalance",
"BODY",
"CANCAST",
"CANMAKE",
"CANMAKESKILL",
"CANMOVE",
"CREATE",
"DIR",
"dispiddec", // for properties dialog.
"EMOTEACT",
"FAME",
"FLAGS",
"FONT",
"FOOD",
"GUILDABBREV",
"HITPOINTS",
"HITS",
"HOME",
"ID",
"ISGM",
"ISMYPET",
"ISONLINE",
"ISPLAYER",
"ISVENDOR",
"KARMA",
"LOCALLIGHT",
"MANA",
"MAXHITS",
"MAXMANA",
"MAXSTAM",
"MAXWEIGHT",
"MEMORY",
// "MODAC",
// "MODAR",
// "MODMAXWEIGHT",
// "MODWEIGHTMAX",
"MOVE",
"NAME",
"NIGHTSIGHT",
"NOTOGETFLAG",
"NPC",
"OBODY",
"OSKIN",
"P",
"RANGE",
"SEX",
"SKILLBEST",
"SKILLCHECK",
"SKILLTOTAL",
"STAM",
"STAMINA",
"STONE",
"TITLE",
"TOWNABBREV",
"WEIGHTMAX",
"XBODY",
"XSKIN",
NULL,
};
void CChar::r_DumpLoadKeys( CTextConsole * pSrc )
{
r_DumpKeys(pSrc,sm_szLoadKeys);
CObjBase::r_DumpLoadKeys(pSrc);
}
void CChar::r_DumpVerbKeys( CTextConsole * pSrc )
{
r_DumpKeys(pSrc,sm_szVerbKeys);
CObjBase::r_DumpVerbKeys(pSrc);
}
bool CChar::r_WriteVal( LPCTSTR pszKey, CGString & sVal, CTextConsole * pSrc )
{
static LPCTSTR const sm_szFameGroups[] = // display only type stuff.
{
"ANONYMOUS",
"FAMOUS",
"INFAMOUS", // get rid of this in the future.
"KNOWN",
"OUTLAW",
NULL,
};
static const CValStr sm_KarmaTitles[] =
{
"WICKED", INT_MIN, // -10000 to -6001
"BELLIGERENT", -6000, // -6000 to -2001
"NEUTRAL", -2000, // -2000 to 2000
"KINDLY", 2001, // 2001 to 6000
"GOODHEARTED", 6001, // 6001 to 10000
NULL, INT_MAX,
};
if ( IsClient())
{
if ( GetClient()->r_WriteVal( pszKey, sVal, pSrc ))
return( true );
}
CCharBase * pCharDef = Char_GetDef();
ASSERT(pCharDef);
CChar * pCharSrc = pSrc->GetChar();
CHC_TYPE iKeyNum = (CHC_TYPE) FindTableHeadSorted( pszKey, sm_szLoadKeys, COUNTOF( sm_szLoadKeys )-1 );
if ( iKeyNum < 0 )
{
do_default:
if ( m_pPlayer )
{
if ( m_pPlayer->r_WriteVal( this, pszKey, sVal ))
return( true );
}
if ( m_pNPC )
{
if ( m_pNPC->r_WriteVal( this, pszKey, sVal ))
return( true );
}
if ( r_WriteValContainer( pszKey, sVal ))
{
return( true );
}
// special write values
int i;
// Adjusted stats
i = g_Cfg.FindStatKey( pszKey );
if ( i >= 0 )
{
sVal.FormatVal( Stat_GetAdjusted( (STAT_TYPE) i));
return( true );
}
if ( !strnicmp( pszKey, "O", 1 ) )
{
i = g_Cfg.FindStatKey( pszKey+1 );
if ( i >= 0 )
{
sVal.FormatVal( Stat_GetBase( (STAT_TYPE) i));
return( true );
}
}
if ( !strnicmp( pszKey, "MOD", 3 ) )
{
i = g_Cfg.FindStatKey( pszKey+3 );
if ( i >= 0 )
{
sVal.FormatVal( Stat_GetMod( (STAT_TYPE) i));
return( true );
}
}
i = g_Cfg.FindSkillKey( pszKey );
if ( IsSkillBase((SKILL_TYPE)i))
{
// Check some skill name.
short iVal = Skill_GetBase( (SKILL_TYPE) i );
sVal.Format( "%i.%i", iVal/10, iVal%10 );
return( true );
}
return( CObjBase::r_WriteVal( pszKey, sVal, pSrc ));
}
switch ( iKeyNum )
{
case CHC_RANGE:
sVal.FormatVal( CalcFightRange( m_uidWeapon.ItemFind() ) );
return true;
case CHC_FAME:
// How much respect do i give this person ?
// Fame is never negative !
if ( pszKey[4] != '.' )
goto do_default;
pszKey += 5;
{
int iFame = Stat_GetAdjusted(STAT_FAME);
int iKarma = Stat_GetAdjusted(STAT_KARMA);
switch ( FindTableSorted( pszKey, sm_szFameGroups, COUNTOF( sm_szFameGroups )-1 ))
{
case 0: // "ANONYMOUS"
iFame = ( iFame < 2000 );
break;
case 1: // "FAMOUS"
iFame = ( iFame > 6000 );
break;
case 2: // "INFAMOUS"
iFame = ( iFame > 6000 && iKarma <= -6000 );
break;
case 3: // "KNOWN"
iFame = ( iFame > 2000 );
break;
case 4: // "OUTLAW"
iFame = ( iFame > 2000 && iKarma <= -2000 );
break;
}
sVal = iFame ? "1" : "0";
}
return( true );
case CHC_SKILLCHECK: // odd way to get skills checking into the triggers.
pszKey += 10;
SKIP_SEPERATORS(pszKey);
{
TCHAR * ppArgs[2];
Str_ParseCmds( (TCHAR*) pszKey, ppArgs, COUNTOF( ppArgs ));
SKILL_TYPE iSkill = g_Cfg.FindSkillKey( ppArgs[0] );
if ( iSkill == SKILL_NONE )
return( false );
sVal.FormatVal( Skill_CheckSuccess( iSkill, Exp_GetVal( ppArgs[1] )));
}
return( true );
case CHC_SKILLBEST:
// Get the top skill.
pszKey += 9;
{
int iRank = 0;
if ( pszKey[0] == '.' )
{
SKIP_SEPERATORS(pszKey);
if ( !strnicmp( pszKey, "g.", 2 ) )
{
pszKey += 2;
iRank = Exp_GetSingle( pszKey );
int iBest = 0;
int iBestVal = 0;
int iVal = 0;
CSkillDef * pSkill;
for ( int i = 0; i < MAX_SKILL; i++ )
{
pSkill = g_Cfg.GetSkillDef( (SKILL_TYPE) i );
if ( !pSkill )
continue;
if ( !(pSkill->m_dwGroup & iRank) )
continue;
iVal = Skill_GetBase( (SKILL_TYPE) i );
if ( iVal >= iBestVal )
{
iBestVal = iVal;
iBest = i;
}
}
sVal.FormatVal( iBest );
return true;
}
iRank = Exp_GetSingle( pszKey );
}
sVal.FormatVal( Skill_GetBest( iRank ) );
}
return( true );
case CHC_SEX: // <SEX milord/milady> sep chars are :,/
pszKey += 4;
SKIP_SEPERATORS(pszKey);
{
TCHAR * ppArgs[2];
Str_ParseCmds( (TCHAR*) pszKey, ppArgs, COUNTOF(ppArgs), ":,/" );
sVal = ( pCharDef->IsFemale()) ? ppArgs[1] : ppArgs[0];
}
return( true );
case CHC_KARMA:
// What do i think of this person.
if ( pszKey[5] != '.' )
goto do_default;
pszKey += 6;
sVal = ( ! strcmpi( pszKey, sm_KarmaTitles->FindName( Stat_GetAdjusted(STAT_KARMA)))) ? "1" : "0";
return( true );
case CHC_AR:
case CHC_AC:
sVal.FormatVal( m_defense + pCharDef->m_defense );
return( true );
case CHC_AGE:
sVal.FormatVal(( - g_World.GetTimeDiff(m_timeCreate)) / TICK_PER_SEC );
return( true );
case CHC_BANKBALANCE:
sVal.FormatVal( GetBank()->ContentCount( RESOURCE_ID(RES_TYPEDEF,IT_GOLD)));
return true;
case CHC_CANCAST:
{
pszKey += 7;
SPELL_TYPE spell = (SPELL_TYPE) g_Cfg.ResourceGetIndexType( RES_SPELL, pszKey );
sVal.FormatVal( Spell_CanCast( spell, true, this, false ));
}
return true;
case CHC_CANMAKE:
{
// use m_Act_Targ ?
pszKey += 7;
ITEMID_TYPE id = (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, pszKey );
sVal.FormatVal( Skill_MakeItem( id, UID_CLEAR, SKTRIG_SELECT ) );
}
return true;
case CHC_CANMAKESKILL:
{
pszKey += 12;
ITEMID_TYPE id = (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, pszKey );
sVal.FormatVal( Skill_MakeItem( id, UID_CLEAR, SKTRIG_SELECT, true ) );
}
return true;
case CHC_CANMOVE:
{
pszKey += 7;
GETNONWHITESPACE(pszKey);
CPointBase ptDst = GetTopPoint();
DIR_TYPE dir = GetDirStr( pszKey );
ptDst.Move( dir );
WORD wBlockFlags = 0;
CRegionBase * pArea;
if ( g_Cfg.IsSetEF( EF_WalkCheck ) )
pArea = CheckValidMove_New( ptDst, &wBlockFlags, dir, NULL );
else
pArea = CheckValidMove( ptDst, &wBlockFlags, dir );
sVal.FormatHex( pArea ? pArea->GetResourceID() : 0 );
}
return true;
case CHC_MOVE:
{
pszKey += 4;
GETNONWHITESPACE(pszKey);
CPointBase ptDst = GetTopPoint();
ptDst.Move( GetDirStr( pszKey ) );
CRegionBase * pArea = ptDst.GetRegion( REGION_TYPE_MULTI | REGION_TYPE_AREA );
if ( !pArea )
sVal.FormatHex( -1 );
else
{
WORD wBlockFlags = 0;
signed char z;
if ( g_Cfg.IsSetEF( EF_WalkCheck ) )
z = g_World.GetHeightPoint_New( ptDst, wBlockFlags, true );
else
z = g_World.GetHeightPoint( ptDst, wBlockFlags, true );
sVal.FormatHex( wBlockFlags );
}
}
return true;
case CHC_DISPIDDEC: // for properties dialog.
sVal.FormatVal( pCharDef->m_trackID );
return true;
case CHC_GUILDABBREV:
{
LPCTSTR pszAbbrev = Guild_Abbrev(MEMORY_GUILD);
sVal = ( pszAbbrev ) ? pszAbbrev : "";
}
return true;
case CHC_ID:
sVal = g_Cfg.ResourceGetName( pCharDef->GetResourceID());
return true;
case CHC_ISGM:
sVal.FormatVal( IsPriv(PRIV_GM));
return( true );
case CHC_ISMYPET:
sVal = NPC_IsOwnedBy( pCharSrc, true ) ? "1" : "0";
return( true );
case CHC_ISONLINE:
if ( m_pPlayer != NULL )
{
sVal = IsClient() ? "1" : "0";
return ( true );
}
if ( m_pNPC != NULL )
{
sVal = IsDisconnected() ? "0" : "1";
return ( true );
}
sVal = 0;
return( true );
case CHC_ISPLAYER:
sVal = (m_pPlayer != NULL) ? "1" : "0";
return( true );
case CHC_ISVENDOR:
sVal = ( NPC_IsVendor()) ? "1" : "0";
return( true );
case CHC_MEMORY:
// What is our memory flags about this pSrc person.
{
DWORD dwFlags = 0;
CItemMemory * pMemory;
pszKey += 6;
if ( *pszKey == '.' )
{
pszKey++;
CGrayUID uid = Exp_GetVal( pszKey );
pMemory = Memory_FindObj( uid );
}
else
pMemory = Memory_FindObj( pCharSrc );
if ( pMemory != NULL )
{
dwFlags = pMemory->GetMemoryTypes();
}
sVal.FormatHex( dwFlags );
}
return( true );
// case CHC_MODAR:
// case CHC_MODAC:
// sVal.FormatVal( m_ModAr );
// break;
case CHC_NAME:
sVal = GetName( false );
break;
case CHC_SKILLTOTAL:
{
pszKey += 10;
SKIP_SEPERATORS(pszKey);
GETNONWHITESPACE(pszKey);
int iVal = 0;
bool fComp = true;
if ( *pszKey == '\0' )
;
else if ( *pszKey == '+' )
iVal = Exp_GetVal( ++pszKey );
else if ( *pszKey == '-' )
iVal = - Exp_GetVal( ++pszKey );
else
{
iVal = Exp_GetVal( pszKey );
fComp = false;
}
int iTotal = 0;
int iBase;
for ( int i=0; i < g_Cfg.m_iMaxSkill; i++ )
{
iBase = Skill_GetBase((SKILL_TYPE) i);
if ( fComp )
{
if ( iVal < 0 )
{
if ( iBase >= -iVal )
continue;
}
else if ( iBase < iVal )
continue;
}
else
{
// check group flags
CSkillDef * pSkill = g_Cfg.GetSkillDef( (SKILL_TYPE) i );
if ( !pSkill )
continue;
if ( !( pSkill->m_dwGroup & iVal ) )
continue;
}
iTotal += iBase;
}
sVal.FormatVal( iTotal );
}
return( true );
case CHC_TOWNABBREV:
{
LPCTSTR pszAbbrev = Guild_Abbrev(MEMORY_TOWN);
sVal = ( pszAbbrev ) ? pszAbbrev : "";
}
return true;
case CHC_MAXWEIGHT:
case CHC_WEIGHTMAX: // use WEIGHT_UNITS ?
sVal.FormatVal( g_Cfg.Calc_MaxCarryWeight(this));
return( true );
// case CHC_MODWEIGHTMAX:
// case CHC_MODMAXWEIGHT:
// sVal.FormatVal( m_ModMaxWeight );
// return( true );
case CHC_ACCOUNT:
if ( pszKey[7] == '.' ) // used as a ref ?
{
if ( m_pPlayer != NULL )
{
pszKey += 7;
SKIP_SEPERATORS(pszKey);
CScriptObj * pRef = m_pPlayer->GetAccount();
if ( pRef )
{
if ( pRef->r_WriteVal( pszKey, sVal, pSrc ) )
break;
return ( false );
}
}
}
if ( m_pPlayer == NULL )
sVal.Empty();
else
sVal = m_pPlayer->GetAccount()->GetName();
break;
case CHC_ACT:
if ( pszKey[3] == '.' ) // used as a ref ?
goto do_default;
sVal.FormatHex( m_Act_Targ.GetObjUID()); // uid
break;
case CHC_ACTDIFF:
sVal.FormatVal( m_Act_Difficulty * 10 );
break;
case CHC_ACTARG1:
sVal.FormatHex( m_atUnk.m_Arg1);
break;
case CHC_ACTARG2:
sVal.FormatHex( m_atUnk.m_Arg2 );
break;
case CHC_ACTARG3:
sVal.FormatHex( m_atUnk.m_Arg3 );
break;
case CHC_ACTION:
sVal = g_Cfg.ResourceGetName( RESOURCE_ID( RES_SKILL, Skill_GetActive()));
break;
case CHC_BODY:
sVal = g_Cfg.ResourceGetName( RESOURCE_ID( RES_CHARDEF, GetDispID()));
break;
case CHC_CREATE:
sVal.FormatHex( -( g_World.GetTimeDiff( m_timeCreate ) / TICK_PER_SEC ));
break;
case CHC_DIR:
sVal.FormatVal( m_dirFace );
break;
case CHC_EMOTEACT:
sVal.FormatVal( IsStatFlag( STATF_EmoteAction ));
break;
case CHC_FLAGS:
sVal.FormatHex( m_StatFlag );
break;
case CHC_FONT:
sVal.FormatVal( m_fonttype );
break;
case CHC_FOOD:
sVal.FormatVal( Stat_GetVal( STAT_FOOD ) );
break;
case CHC_HITPOINTS:
case CHC_HITS:
sVal.FormatVal( Stat_GetVal(STAT_STR) );
break;
case CHC_STAM:
case CHC_STAMINA:
sVal.FormatVal( Stat_GetVal(STAT_DEX) );
break;
case CHC_MANA:
sVal.FormatVal( Stat_GetVal(STAT_INT) );
break;
case CHC_MAXHITS:
sVal.FormatVal( Stat_GetMax(STAT_STR) );
break;
case CHC_MAXMANA:
sVal.FormatVal( Stat_GetMax(STAT_INT) );
break;
case CHC_MAXSTAM:
sVal.FormatVal( Stat_GetMax(STAT_DEX) );
break;
case CHC_HOME:
sVal = m_ptHome.WriteUsed();
break;
case CHC_NIGHTSIGHT:
sVal.FormatVal( IsStatFlag( STATF_NightSight ));
break;
case CHC_NOTOGETFLAG:
{
pszKey += 11;
GETNONWHITESPACE(pszKey);
CGrayUID uid = Exp_GetVal( pszKey );
SKIP_ARGSEP( pszKey );
bool fAllowIncog = ( Exp_GetVal( pszKey ) >= 1 );
CChar * pChar;
if ( ! uid.IsValidUID() )
pChar = pCharSrc;
else
{
pChar = uid.CharFind();
if ( ! pChar )
pChar = pCharSrc;
}
sVal.FormatVal( Noto_GetFlag( pChar, fAllowIncog ) );
}
break;
case CHC_NPC:
goto do_default;
case CHC_OBODY:
case CHC_XBODY: // not used anymore.
sVal = g_Cfg.ResourceGetName( RESOURCE_ID( RES_CHARDEF, m_prev_id ));
break;
case CHC_OSKIN:
case CHC_XSKIN: // not used anymore.
sVal.FormatHex( m_prev_Hue );
break;
case CHC_P:
goto do_default;
case CHC_STONE:
sVal.FormatVal( IsStatFlag( STATF_Stone ));
break;
case CHC_TITLE:
sVal = m_sTitle;
break;
case CHC_LOCALLIGHT:
sVal.FormatHex(m_LocalLight);
break;
default:
DEBUG_CHECK(0);
return( false );
}
return( true );
}
bool CChar::r_LoadVal( CScript & s )
{
CHC_TYPE iKeyNum = (CHC_TYPE) FindTableHeadSorted( s.GetKey(), sm_szLoadKeys, COUNTOF( sm_szLoadKeys )-1 );
if ( iKeyNum < 0 )
{
do_default:
if ( m_pPlayer )
{
if ( m_pPlayer->r_LoadVal( this, s ))
return( true );
}
if ( m_pNPC )
{
if ( m_pNPC->r_LoadVal( this, s ))
return( true );
}
{
LPCTSTR pszKey = s.GetKey();
int i = g_Cfg.FindSkillKey( pszKey );
if ( i != SKILL_NONE )
{
// Check some skill name.
Skill_SetBase( (SKILL_TYPE) i, s.GetArgVal() );
return true;
}
i = g_Cfg.FindStatKey( pszKey );
if ( i >= 0 )
{
// if ( g_Serv.IsLoading() || (m_Stat[i].m_base == 0) )
// m_Stat[i].m_base = s.GetArgVal();
// else
Stat_SetBase( (STAT_TYPE) i, s.GetArgVal() - Stat_GetMod( (STAT_TYPE) i ) );
// - Stat_GetAdjusted((STAT_TYPE)i)
return true;
}
if ( !strnicmp( pszKey, "O", 1 ) )
{
i = g_Cfg.FindStatKey( pszKey+1 );
if ( i >= 0 )
{
Stat_SetBase( (STAT_TYPE) i, s.GetArgVal() );
return true;
}
}
if ( !strnicmp( pszKey, "MOD", 3 ) )
{
i = g_Cfg.FindStatKey( pszKey+3 );
if ( i >= 0 )
{
Stat_SetMod( (STAT_TYPE) i, s.GetArgVal() );
return true;
}
}
}
return( CObjBase::r_LoadVal( s ));
}
switch (iKeyNum)
{
case CHC_MAXHITS:
Stat_SetMax(STAT_STR, s.HasArgs() ? (s.GetArgVal() - Stat_GetMod(STAT_STR)) : 0 );
return true;
case CHC_MAXMANA:
Stat_SetMax(STAT_INT, s.HasArgs() ? (s.GetArgVal() - Stat_GetMod(STAT_INT)) : 0 );
return true;
case CHC_MAXSTAM:
Stat_SetMax(STAT_DEX, s.HasArgs() ? (s.GetArgVal() - Stat_GetMod(STAT_DEX)) : 0 );
return true;
case CHC_ACCOUNT:
return SetPlayerAccount( s.GetArgStr());
case CHC_ACT:
m_Act_Targ = s.GetArgVal();
return true;
case CHC_ACTDIFF:
m_Act_Difficulty = (s.GetArgVal() / 10);
return true;
case CHC_ACTARG1:
m_atUnk.m_Arg1 = s.GetArgVal();
return true;
case CHC_ACTARG2:
m_atUnk.m_Arg2 = s.GetArgVal();
return true;
case CHC_ACTARG3:
m_atUnk.m_Arg3 = s.GetArgVal();
return true;
case CHC_ACTION:
return Skill_Start( g_Cfg.FindSkillKey( s.GetArgStr()));
case CHC_BODY:
SetID( (CREID_TYPE) g_Cfg.ResourceGetIndexType( RES_CHARDEF, s.GetArgStr()));
return true;
case CHC_CREATE:
m_timeCreate = CServTime::GetCurrentTime() - ( s.GetArgVal() * TICK_PER_SEC );
return true;
case CHC_DIR:
m_dirFace = (DIR_TYPE) s.GetArgVal();
if ( m_dirFace < 0 || m_dirFace >= DIR_QTY )
m_dirFace = DIR_SE;
return true;
case CHC_EMOTEACT:
{
bool fSet = IsStatFlag(STATF_EmoteAction);
if ( s.HasArgs())
{
fSet = s.GetArgVal() ? true : false;
}
else
{
fSet = ! fSet;
}
StatFlag_Mod(STATF_EmoteAction,fSet);
}
return true;
case CHC_FLAGS: // DO NOT MODIFY STATF_SaveParity, STATF_Spawned, STATF_Pet
m_StatFlag = ( s.GetArgVal() &~ (STATF_SaveParity|STATF_Pet|STATF_Spawned)) | ( m_StatFlag & (STATF_SaveParity|STATF_Pet|STATF_Spawned) );
return true;
case CHC_FONT:
m_fonttype = (FONT_TYPE) s.GetArgVal();
if ( m_fonttype < 0 || m_fonttype >= FONT_QTY )
m_fonttype = FONT_NORMAL;
return true;
case CHC_FOOD:
Stat_SetVal(STAT_FOOD, s.GetArgVal());
return true;
case CHC_HITPOINTS:
case CHC_HITS:
Stat_SetVal(STAT_STR, s.GetArgVal() );
UpdateHitsFlag();
return true;
case CHC_MANA:
Stat_SetVal(STAT_INT, s.GetArgVal() );
UpdateManaFlag();
return true;
// case CHC_MODAR:
// case CHC_MODAC:
// {
// m_ModAr = s.GetArgVal();
// m_defense = CalcArmorDefense();
// UpdateStatsFlag();
// }
// return( true );
// case CHC_MODWEIGHTMAX:
// case CHC_MODMAXWEIGHT:
// m_ModMaxWeight = s.GetArgVal();
// return( true );
case CHC_STAM:
case CHC_STAMINA:
Stat_SetVal(STAT_DEX, s.GetArgVal() );
UpdateStamFlag();
return true;
case CHC_HOME:
if ( ! s.HasArgs())
m_ptHome = GetTopPoint();
else
m_ptHome.Read( s.GetArgStr());
return true;
case CHC_NAME:
case CHC_FAME:
case CHC_KARMA:
goto do_default;
case CHC_MEMORY:
{
int piCmd[2];
int iArgQty = Str_ParseCmds( s.GetArgStr(), piCmd, COUNTOF(piCmd) );
if ( iArgQty < 2 )
return( false );
CGrayUID uid = piCmd[0];
DWORD dwFlags = piCmd[1];
CItemMemory * pMemory = Memory_FindObj( uid );
if ( pMemory != NULL )
pMemory->SetMemoryTypes( piCmd[1] );
else
pMemory = Memory_AddObjTypes( uid, piCmd[1] );
}
return( true );
case CHC_NIGHTSIGHT:
{
bool fNightsight;
if ( s.HasArgs())
{
fNightsight = s.GetArgVal();
}
else
{
fNightsight = ! IsStatFlag(STATF_NightSight);
}
StatFlag_Mod( STATF_NightSight, fNightsight );
Update();
}
return true;
case CHC_NPC:
return SetNPCBrain( (NPCBRAIN_TYPE) s.GetArgVal());
case CHC_OBODY:
scp_obody:
{
CREID_TYPE id = (CREID_TYPE) g_Cfg.ResourceGetIndexType( RES_CHARDEF, s.GetArgStr());
if ( ! CCharBase::FindCharBase( id ))
{
DEBUG_ERR(( "OBODY Invalid Char 0%x" DEBUG_CR, id ));
return( false );
}
m_prev_id = id;
}
return true;
case CHC_OSKIN:
scp_oskin:
m_prev_Hue = s.GetArgVal();
return true;
case CHC_P:
{
CPointMap pt;
pt.Read(s.GetArgStr());
m_fClimbUpdated = false; // update climb height
MoveToChar(pt);
}
return true;
case CHC_STONE:
{
bool fSet;
bool fChange = IsStatFlag(STATF_Stone);
if ( s.HasArgs())
{
fSet = s.GetArgVal() ? true : false;
fChange = ( fSet != fChange );
}
else
{
fSet = ! fChange;
fChange = true;
}
StatFlag_Mod(STATF_Stone,fSet);
if ( fChange )
{
RemoveFromView();
Update();
}
}
return true;
case CHC_TITLE:
m_sTitle = s.GetArgStr();
return true;
case CHC_XBODY:
goto scp_obody;
case CHC_XSKIN:
goto scp_oskin;
case CHC_LOCALLIGHT:
m_LocalLight = s.GetArgVal();
return true;
default:
DEBUG_CHECK(0);
return( false );
}
return( true );
}
void CChar::r_Serialize( CGFile & a )
{
// Read and write binary.
CObjBase::r_Serialize(a);
if ( m_pPlayer )
{
m_pPlayer->r_SerializeChar(this, a);
}
if ( m_pNPC )
{
m_pNPC->r_SerializeChar(this, a);
}
// ...
r_SerializeContent(a);
}
void CChar::r_Write( CScript & s )
{
s.WriteSection( "WORLDCHAR %s", GetResourceName());
s.WriteKeyHex( "CREATE", -( g_World.GetTimeDiff( m_timeCreate ) / TICK_PER_SEC ) );
CObjBase::r_Write( s );
if ( m_pPlayer )
{
m_pPlayer->r_WriteChar(this, s);
}
if ( m_pNPC )
{
m_pNPC->r_WriteChar(this, s);
}
if ( GetTopPoint().IsValidPoint())
{
s.WriteKey( "P", GetTopPoint().WriteUsed());
}
if ( ! m_sTitle.IsEmpty())
{
s.WriteKey( "TITLE", m_sTitle );
}
if ( m_fonttype != FONT_NORMAL )
{
s.WriteKeyVal( "FONT", m_fonttype );
}
if ( m_dirFace != DIR_SE )
{
s.WriteKeyVal( "DIR", m_dirFace );
}
if ( m_prev_id != GetID())
{
s.WriteKey( "OBODY", g_Cfg.ResourceGetName( RESOURCE_ID( RES_CHARDEF, m_prev_id )));
}
if ( m_prev_Hue != HUE_DEFAULT )
{
s.WriteKeyHex( "OSKIN", m_prev_Hue );
}
if ( m_StatFlag )
{
s.WriteKeyHex( "FLAGS", m_StatFlag );
}
if ( m_LocalLight )
{
s.WriteKeyHex( "LOCALLIGHT", m_LocalLight );
}
if ( Skill_GetActive() != SKILL_NONE )
{
s.WriteKey( "ACTION", g_Cfg.ResourceGetName( RESOURCE_ID( RES_SKILL, Skill_GetActive())));
if ( m_atUnk.m_Arg1 )
{
s.WriteKeyHex( "ACTARG1", m_atUnk.m_Arg1 );
}
if ( m_atUnk.m_Arg2 )
{
s.WriteKeyHex( "ACTARG2", m_atUnk.m_Arg2 );
}
if ( m_atUnk.m_Arg3 )
{
s.WriteKeyHex( "ACTARG3", m_atUnk.m_Arg3 );
}
}
s.WriteKeyVal( "HITS", Stat_GetVal(STAT_STR) );
s.WriteKeyVal( "STAM", Stat_GetVal(STAT_DEX) );
s.WriteKeyVal( "MANA", Stat_GetVal(STAT_INT) );
s.WriteKeyVal( "FOOD", Stat_GetVal(STAT_FOOD) );
if ( Stat_GetAdjusted(STAT_STR) != Stat_GetMax(STAT_STR) )
s.WriteKeyVal( "MAXHITS", Stat_GetMax(STAT_STR) );
if ( Stat_GetAdjusted(STAT_DEX) != Stat_GetMax(STAT_DEX) )
s.WriteKeyVal( "MAXSTAM", Stat_GetMax(STAT_DEX) );
if ( Stat_GetAdjusted(STAT_INT) != Stat_GetMax(STAT_INT) )
s.WriteKeyVal( "MAXMANA", Stat_GetMax(STAT_INT) );
if ( m_ptHome.IsValidPoint())
{
s.WriteKey( "HOME", m_ptHome.WriteUsed());
}
TCHAR szTmp[100];
int j=0;
for ( j=0;j<STAT_QTY;j++)
{
// this is VERY important, saving the MOD first
if ( Stat_GetMod( (STAT_TYPE) j ) )
{
sprintf( szTmp, "MOD%s", g_Stat_Name[j] );
s.WriteKeyVal( szTmp, Stat_GetMod( (STAT_TYPE) j ) );
}
if ( Stat_GetBase( (STAT_TYPE) j ) )
{
sprintf( szTmp, "O%s", g_Stat_Name[j] );
s.WriteKeyVal( szTmp, Stat_GetBase( (STAT_TYPE) j ) );
}
}
for ( j=0;j<MAX_SKILL;j++)
{
if ( ! m_Skill[j] )
continue;
s.WriteKeyVal( g_Cfg.GetSkillDef( (SKILL_TYPE) j )->GetKey(), Skill_GetBase( (SKILL_TYPE) j ));
}
r_WriteContent(s);
}
void CChar::r_WriteParity( CScript & s )
{
// overload virtual for world save.
// if ( GetPrivLevel() <= PLEVEL_Guest ) return;
if ( g_World.m_fSaveParity == IsStatFlag(STATF_SaveParity))
{
return; // already saved.
}
StatFlag_Mod( STATF_SaveParity, g_World.m_fSaveParity );
int iRet = IsWeird();
if ( iRet )
{
DEBUG_MSG(( "Weird char %x,'%s' rejected from save %d." DEBUG_CR, (DWORD) GetUID(), (LPCTSTR) GetName(), iRet ));
return;
}
r_WriteSafe(s);
}
bool CChar::r_Load( CScript & s ) // Load a character from script
{
CScriptObj::r_Load(s);
// Init the STATF_SaveParity flag.
// StatFlag_Mod( STATF_SaveParity, g_World.m_fSaveParity );
// Make sure everything is ok.
if (( m_pPlayer && ! IsClient()) ||
( m_pNPC && IsStatFlag( STATF_DEAD | STATF_Ridden ))) // dead npc
{
DEBUG_CHECK( ! IsClient());
SetDisconnected();
}
int iResultCode = CObjBase::IsWeird();
if ( iResultCode )
{
DEBUG_ERR(( "Char 0%x Invalid, id='%s', code=0%x" DEBUG_CR, (DWORD) GetUID(), (LPCTSTR) GetResourceName(), iResultCode ));
Delete();
}
return( true );
}
enum CHV_TYPE
{
CHV_AFK,
CHV_ALLSKILLS,
CHV_ANIM, // "Bow, "Salute"
CHV_ATTACK,
CHV_BANK,
CHV_BARK,
CHV_BOUNCE,
CHV_BOW,
CHV_CONSUME,
CHV_CONTROL,
CHV_CRIMINAL,
CHV_DBG,
CHV_DISCONNECT,
CHV_DRAWMAP,
CHV_DROP,
CHV_DUPE,
CHV_EQUIP, // engage the equip triggers.
CHV_EQUIPARMOR,
CHV_EQUIPHALO,
CHV_EQUIPLIGHT,
CHV_EQUIPWEAPON,
CHV_FACE,
CHV_FORGIVE,
CHV_GO,
CHV_GOCHAR,
CHV_GOCHARID,
CHV_GOCLI,
CHV_GOITEMID,
CHV_GONAME,
CHV_GOPLACE,
CHV_GOSOCK,
CHV_GOTYPE,
CHV_GOUID,
CHV_HEAR,
CHV_HUNGRY,
CHV_INVIS,
CHV_INVISIBLE,
CHV_INVUL,
CHV_INVULNERABLE,
CHV_JAIL,
CHV_KILL,
CHV_MAKEITEM,
CHV_NEWBIESKILL,
CHV_NEWDUPE,
CHV_NEWITEM,
CHV_NEWNPC,
CHV_PACK,
CHV_PARDON,
CHV_POISON,
CHV_POLY,
CHV_PRIVSET,
CHV_RELEASE,
CHV_REMOVE,
CHV_RESURRECT,
CHV_SALUTE, // salute to player
CHV_SKILL,
CHV_SLEEP,
CHV_SUICIDE,
CHV_SUMMONCAGE,
CHV_SUMMONTO,
CHV_SYSMESSAGE,
CHV_SYSMESSAGEUA,
CHV_UNDERWEAR,
CHV_UNEQUIP, // engage the unequip triggers.
CHV_WHERE,
CHV_QTY,
};
LPCTSTR const CChar::sm_szVerbKeys[CHV_QTY+1] =
{
"AFK",
"ALLSKILLS",
"ANIM", // "Bow", "Salute"
"ATTACK",
"BANK",
"BARK",
"BOUNCE",
"BOW",
"CONSUME",
"CONTROL",
"CRIMINAL",
"DBG",
"DISCONNECT",
"DRAWMAP",
"DROP",
"DUPE",
"EQUIP", // engage the equip triggers.
"EQUIPARMOR",
"EQUIPHALO",
"EQUIPLIGHT",
"EQUIPWEAPON",
"FACE",
"FORGIVE",
"GO",
"GOCHAR",
"GOCHARID",
"GOCLI",
"GOITEMID",
"GONAME",
"GOPLACE",
"GOSOCK",
"GOTYPE",
"GOUID",
"HEAR",
"HUNGRY",
"INVIS",
"INVISIBLE",
"INVUL",
"INVULNERABLE",
"JAIL",
"KILL",
"MAKEITEM",
"NEWBIESKILL",
"NEWDUPE",
"NEWITEM",
"NEWNPC",
"PACK",
"PARDON",
"POISON",
"POLY",
"PRIVSET",
"RELEASE",
"REMOVE",
"RESURRECT",
"SALUTE", // salute to player
"SKILL",
"SLEEP",
"SUICIDE",
"SUMMONCAGE",
"SUMMONTO",
"SYSMESSAGE",
"SYSMESSAGEUA",
"UNDERWEAR",
"UNEQUIP", // engage the unequip triggers.
"WHERE",
NULL,
};
bool CChar::r_Verb( CScript &s, CTextConsole * pSrc ) // Execute command from script
{
if ( pSrc == NULL )
{
return( false );
}
if ( IsClient()) // I am a client so i get an expanded verb set. Things only clients can do.
{
if ( GetClient()->r_Verb( s, pSrc ))
return( true );
}
int index = FindTableSorted( s.GetKey(), sm_szVerbKeys, COUNTOF(sm_szVerbKeys)-1 );
bool fNewAct = false;
switch( index )
{
case CHV_NEWDUPE: // uid
case CHV_NEWITEM: // just add an item but don't put it anyplace yet..
case CHV_NEWNPC:
fNewAct = true;
index = -1;
break;
}
if ( index < 0 )
{
if ( m_pNPC )
{
if ( NPC_OnVerb( s, pSrc ))
return( true );
}
if ( m_pPlayer )
{
if ( Player_OnVerb( s, pSrc ))
return( true );
}
bool fRet = ( CObjBase::r_Verb( s, pSrc ));
if ( fNewAct )
m_Act_Targ = g_World.m_uidNew;
return fRet;
}
CChar * pCharSrc = pSrc->GetChar();
switch ( index )
{
case CHV_AFK:
// toggle ?
{
bool fAFK = ( Skill_GetActive() == NPCACT_Napping );
bool fMode;
if ( s.HasArgs())
{
fMode = s.GetArgVal();
}
else
{
fMode = ! fAFK;
}
if ( fMode != fAFK )
{
if ( fMode )
{
SysMessageDefault( "cmdafk_enter" );
m_Act_p = GetTopPoint();
Skill_Start( NPCACT_Napping );
}
else
{
SysMessageDefault( "cmdafk_leave" );
Skill_Start( SKILL_NONE );
}
}
}
break;
case CHV_ALLSKILLS:
{
int iVal = s.GetArgVal();
for ( int i=0; i<MAX_SKILL; i++ )
{
Skill_SetBase( (SKILL_TYPE)i, iVal );
}
}
break;
case CHV_ANIM:
// ANIM, ANIM_TYPE action, bool fBackward = false, BYTE iFrameDelay = 1
{
int Arg_piCmd[3]; // Maximum parameters in one line
int Arg_Qty = Str_ParseCmds( s.GetArgRaw(), Arg_piCmd, COUNTOF(Arg_piCmd));
return UpdateAnimate( (ANIM_TYPE) Arg_piCmd[0], false,
( Arg_Qty > 1 ) ? Arg_piCmd[1] : false,
( Arg_Qty > 2 ) ? Arg_piCmd[2] : 1 );
}
break;
case CHV_ATTACK:
{
CChar * pSrc = pCharSrc;
int piCmd[1];
if ( Str_ParseCmds( s.GetArgRaw(), piCmd, COUNTOF(piCmd)) )
{
CGrayUID uid = piCmd[0];
pSrc = uid.CharFind();
}
if ( pSrc )
Fight_Attack( pSrc );
}
break;
case CHV_BANK:
// Open the bank box for this person
if ( pCharSrc == NULL || ! pCharSrc->IsClient() )
return( false );
pCharSrc->GetClient()->addBankOpen( this, (LAYER_TYPE)((s.HasArgs()) ? s.GetArgVal() : LAYER_BANKBOX ));
break;
case CHV_BARK:
SoundChar( (CRESND_TYPE) ( s.HasArgs() ? s.GetArgVal() : ( Calc_GetRandVal(2) ? CRESND_RAND1 : CRESND_RAND2 )));
break;
case CHV_BOUNCE: // uid
return ItemBounce( CGrayUID( s.GetArgVal()).ItemFind());
case CHV_BOW:
UpdateDir( pCharSrc );
UpdateAnimate( ANIM_BOW, false );
break;
case CHV_CONTROL: // Possess
if ( pCharSrc == NULL || ! pCharSrc->IsClient())
return( false );
return( pCharSrc->GetClient()->Cmd_Control( this ));
case CHV_CONSUME:
{
CResourceQtyArray Resources;
Resources.Load( s.GetArgStr() );
ResourceConsume( &Resources, 1, false );
}
break;
case CHV_DBG: //Torfo: Removed
{
// try to do something nasty on purpose, see how it handles it
//CChar * pChar = NULL;
//SysMessage( "DBG..." );
//SysMessagef( "Name: %d", pChar->GetName() );
}
break;
case CHV_CRIMINAL:
if ( s.HasArgs() && ! s.GetArgVal())
{
StatFlag_Clear( STATF_Criminal );
}
else
{
Noto_Criminal();
}
break;
case CHV_DISCONNECT:
// Push a player char off line. CLIENTLINGER thing
if ( IsClient())
{
return GetClient()->addKick( pSrc, false );
}
SetDisconnected();
break;
case CHV_DRAWMAP:
// Use the cartography skill to draw a map.
// Already did the skill check.
m_atCartography.m_Dist = s.GetArgVal();
Skill_Start( SKILL_CARTOGRAPHY );
break;
case CHV_DROP: // uid
return ItemDrop( CGrayUID( s.GetArgVal()).ItemFind(), GetTopPoint());
case CHV_DUPE: // = dupe a creature !
CChar::CreateNPC( GetID())->MoveNearObj( this, 1 );
break;
case CHV_EQUIP: // uid
return ItemEquip( CGrayUID( s.GetArgVal()).ItemFind());
case CHV_EQUIPHALO:
{
// equip a halo light
CItem * pItem = CItem::CreateScript(ITEMID_LIGHT_SRC, this);
ASSERT( pItem);
if ( s.HasArgs()) // how long to last ?
{
}
LayerAdd( pItem, LAYER_LIGHT );
}
return( true );
case CHV_EQUIPLIGHT:
{
// equip a light from my pack.
}
return( true );
case CHV_EQUIPARMOR:
return ItemEquipArmor(false);
case CHV_EQUIPWEAPON:
// find my best waepon for my skill and equip it.
return ItemEquipWeapon(false);
case CHV_FACE:
UpdateDir( pCharSrc );
break;
case CHV_FORGIVE:
goto do_pardon;
case CHV_GOCHAR: // uid
return TeleportToObj( 1, s.GetArgStr());
case CHV_GOCHARID:
return TeleportToObj( 3, s.GetArgStr());
case CHV_GOCLI: // enum clients
return TeleportToCli( 1, s.GetArgVal());
case CHV_GOITEMID:
return TeleportToObj( 4, s.GetArgStr());
case CHV_GONAME:
return TeleportToObj( 0, s.GetArgStr());
case CHV_GO:
case CHV_GOPLACE:
Spell_Teleport( g_Cfg.GetRegionPoint( s.GetArgStr()), true, false );
break;
case CHV_GOSOCK: // sockid
return TeleportToCli( 0, s.GetArgVal());
case CHV_GOTYPE:
return TeleportToObj( 2, s.GetArgStr());
case CHV_GOUID: // uid
if ( s.HasArgs())
{
CGrayUID uid( s.GetArgVal());
CObjBaseTemplate * pObj = uid.ObjFind();
if ( pObj == NULL )
return( false );
pObj = pObj->GetTopLevelObj();
Spell_Teleport( pObj->GetTopPoint(), true, false );
return( true );
}
return( false );
case CHV_HEAR:
// NPC will hear this command but no-one else.
if ( m_pPlayer )
{
SysMessage( s.GetArgStr());
}
else
{
ASSERT( m_pNPC );
NPC_OnHear( s.GetArgStr(), pSrc->GetChar());
}
break;
case CHV_HUNGRY: // How hungry are we ?
if ( pCharSrc )
{
CGString sMsg;
sMsg.Format( "%s %s %s",
( pCharSrc == this ) ? "You" : (LPCTSTR) GetName(),
( pCharSrc == this ) ? "are" : "looks",
Food_GetLevelMessage( false, false ));
pCharSrc->ObjMessage( sMsg, this );
}
break;
case CHV_INVIS:
case CHV_INVISIBLE:
if ( pSrc )
{
m_StatFlag = s.GetArgFlag( m_StatFlag, STATF_Insubstantial );
pSrc->SysMessagef( "Invis %s", ( IsStatFlag( STATF_Insubstantial )) ? "ON" : "OFF" );
UpdateMode( NULL, true ); // invis used by GM bug requires this
}
break;
case CHV_INVUL:
case CHV_INVULNERABLE:
if ( pSrc )
{
m_StatFlag = s.GetArgFlag( m_StatFlag, STATF_INVUL );
pSrc->SysMessagef( "Invulnerability %s", ( IsStatFlag( STATF_INVUL )) ? "ON" : "OFF" );
}
break;
case CHV_JAIL: // i am being jailed
Jail( pSrc, true, s.GetArgVal() );
break;
case CHV_KILL:
{
Effect( EFFECT_LIGHTNING, ITEMID_NOTHING, pCharSrc );
OnTakeDamage( 10000, pCharSrc, DAMAGE_GOD );
Stat_SetVal( STAT_STR, 0 );
g_Log.Event( LOGL_EVENT|LOGM_KILLS|LOGM_GM_CMDS, "'%s' was KILLed by '%s'" DEBUG_CR, (LPCTSTR) GetName(), (LPCTSTR) pSrc->GetName());
}
break;
case CHV_MAKEITEM:
return Skill_MakeItem(
(ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, s.GetArgRaw()),
m_Act_Targ, SKTRIG_START );
case CHV_NEWBIESKILL:
{
CResourceLock s;
if ( ! g_Cfg.ResourceLock( s, RES_NEWBIE, s.GetArgStr()))
return( false );
ReadScript( s );
}
break;
case CHV_PACK:
if ( pCharSrc == NULL || ! pCharSrc->IsClient())
return( false );
pCharSrc->m_pClient->addBankOpen( this, LAYER_PACK ); // Send Backpack (with items)
break;
case CHV_POISON:
{
int iSkill = s.GetArgVal();
SetPoison( iSkill, iSkill/50, pSrc->GetChar());
}
break;
case CHV_PARDON:
do_pardon:
Jail( pSrc, false, 0 );
break;
case CHV_POLY: // result of poly spell script choice. (casting a spell)
m_atMagery.m_Spell = SPELL_Polymorph;
m_atMagery.m_SummonID = (CREID_TYPE) g_Cfg.ResourceGetIndexType( RES_CHARDEF, s.GetArgStr());
if ( m_pClient != NULL )
{
m_Act_Targ = m_pClient->m_Targ_UID;
m_Act_TargPrv = m_pClient->m_Targ_PrvUID;
}
else
{
m_Act_Targ = GetUID();
m_Act_TargPrv = GetUID();
}
Skill_Start( SKILL_MAGERY );
break;
case CHV_PRIVSET:
return( SetPrivLevel( pSrc, s.GetArgStr()));
case CHV_RELEASE:
Skill_Start( SKILL_NONE );
NPC_PetClearOwners();
SoundChar( CRESND_RAND2 ); // No noise
return( true );
case CHV_REMOVE: // remove this char from the world instantly.
if ( m_pPlayer )
{
if ( s.GetArgRaw()[0] != '1' ||
pSrc->GetPrivLevel() < PLEVEL_Admin )
{
pSrc->SysMessage( "Can't remove players this way, Try 'kill','kick' or 'remove 1'" );
return( false );
}
}
//Torfo: Disconnect Client before delete Char
if ( IsClient() )
{
GetClient()->addKick( pSrc, false );
}
SetDisconnected();
Delete();
break;
case CHV_RESURRECT:
return OnSpellEffect( SPELL_Resurrection, pCharSrc, 1000, NULL );
case CHV_SALUTE: // salute to player
UpdateDir( pCharSrc );
UpdateAnimate( ANIM_SALUTE, false );
break;
case CHV_SKILL:
Skill_Start( g_Cfg.FindSkillKey( s.GetArgStr()));
break;
case CHV_SLEEP:
SleepStart( s.GetArgVal());
break;
case CHV_SUICIDE:
Memory_ClearTypes( MEMORY_FIGHT ); // Clear the list of people who get credit for your death
UpdateAnimate( ANIM_SALUTE );
Stat_SetVal( STAT_STR, 0 );
break;
case CHV_SUMMONCAGE: // i just got summoned
if ( pCharSrc != NULL )
{
// Let's make a cage to put the player in
ITEMID_TYPE id = (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, "i_multi_cage" );
if ( id < 0 )
return( false );
CItemMulti * pItem = dynamic_cast <CItemMulti*>( CItem::CreateBase( id ));
if ( pItem == NULL )
return( false );
CPointMap pt = pCharSrc->GetTopPoint();
pt.MoveN( pCharSrc->m_dirFace, 3 );
pItem->MoveToDecay( pt, 10*60*TICK_PER_SEC ); // make the cage vanish after 10 minutes.
pItem->Multi_Create( NULL, UID_CLEAR );
Spell_Teleport( pt, true, false );
break;
}
return( false );
case CHV_SUMMONTO: // i just got summoned
if ( pCharSrc != NULL )
{
Spell_Teleport( pCharSrc->GetTopPoint(), true, false );
}
break;
case CHV_SYSMESSAGE:
case CHV_SYSMESSAGEUA:
// just eat this if it's not a client.
break;
case CHV_UNDERWEAR:
if ( ! IsHuman())
return( false );
SetHue( GetHue() ^ HUE_UNDERWEAR );
RemoveFromView();
Update();
break;
case CHV_UNEQUIP: // uid
return ItemBounce( CGrayUID( s.GetArgVal()).ItemFind());
case CHV_WHERE:
if ( pCharSrc )
{
// pCharSrc->Skill_UseQuick( SKILL_CARTOGRAPHY, 10 );
CGString sMsg;
if ( m_pArea )
{
if ( m_pArea->GetResourceID().IsItem())
{
basicform:
sMsg.Format( "I am in %s (%s)",
(LPCTSTR) m_pArea->GetName(), (LPCTSTR) GetTopPoint().WriteUsed());
}
else
{
const CRegionBase * pRoom = GetTopPoint().GetRegion( REGION_TYPE_ROOM );
if ( ! pRoom )
goto basicform;
sMsg.Format( "I am in %s in %s (%s)",
(LPCTSTR) m_pArea->GetName(), (LPCTSTR) pRoom->GetName(), (LPCTSTR) GetTopPoint().WriteUsed());
}
}
else
{
// This should not happen.
sMsg.Format( "I am at %s.", (LPCTSTR) GetTopPoint().WriteUsed());
}
pCharSrc->ObjMessage( sMsg, this );
}
break;
default:
DEBUG_CHECK(0);
return( false );
}
return( true );
}
CItemBase * CChar::GetKeyItemBase( LPCTSTR pszKey )
{
const char * sID = GetKeyStr( pszKey );
if ( sID && *sID )
{
ITEMID_TYPE id = (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, sID );
return CItemBase::FindItemBase( id );
}
return NULL;
}
bool CChar::OnTriggerSpeech( LPCTSTR pszName, LPCTSTR pszText, CChar * pSrc, TALKMODE_TYPE & mode )
{
CScriptObj * pDef = g_Cfg.ResourceGetDefByName( RES_SPEECH, pszName );
if ( !pDef )
{
DEBUG_ERR( ("OnTriggerSpeech: couldn't find speech resource %s" DEBUG_CR, pszName ) );
return false;
}
CResourceLink * pLink = dynamic_cast <CResourceLink *>( pDef );
if ( !pLink )
{
DEBUG_ERR( ("OnTriggerSpeech: couldn't find speech %s" DEBUG_CR, pszName ) );
return false;
}
CResourceLock s;
if ( !pLink->ResourceLock(s) )
return false;
if ( ! pLink->HasTrigger(XTRIG_UNKNOWN))
return false;
if ( OnHearTrigger( s, pszText, pSrc, mode ) == TRIGRET_RET_TRUE )
return true;
return false;
}
| 22.541139 | 199 | 0.640944 | Jhobean |
6d8a765baa7362b2798093330359711daa77da74 | 2,630 | cpp | C++ | list/138 CopyListwithRandomPointer.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | list/138 CopyListwithRandomPointer.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | list/138 CopyListwithRandomPointer.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | //
// Copy List with Random Pointer.cpp
// Leetcode
//
// Created by Quinn on 2020/7/15.
// Copyright © 2020 Quinn. All rights reserved.
//
#include <stdio.h>
#include <map>
#include <unordered_map>
using namespace std;
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
/*
提示:
-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。
*/
// 思路1:迭代的思路,空间复杂度O(n),时间复杂度O(n)
class Solution01 {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
map<Node*, Node*> visited_map;
map<Node*, Node*> &map = visited_map;
Node *reslut = new Node(head->val);
Node *old_node = head;
Node *new_node = reslut;
visited_map[old_node] = new_node;
while (old_node) {
new_node->next = cloneNode(old_node->next,map);
new_node->random = cloneNode(old_node->random, map);
old_node = old_node->next;
new_node = new_node->next;
}
return reslut;
}
private:
Node *cloneNode(Node *node, map<Node*, Node*> &map)
{
if (!node) return nullptr;
if (!map.count(node)) {
Node *add_node = new Node(node->val);
map[node] = add_node;
}
return map[node];
}
};
// 思路2:递归的思路:空间复杂度O(n),时间复杂度O(n)
class Solution1 {
public:
unordered_map<Node *, Node *> hash;
Node* copyRandomList(Node* head) {
if(!head) {
return nullptr;
}
if(hash.count(head))
return hash[head];
Node *ans = new Node(head->val);
hash[head] = ans;
ans->next = copyRandomList(head->next);
ans->random = copyRandomList(head->random);
return ans;
}
};
class Solution {
public:
Node* copyRandomList(Node* head) {
for(auto p = head; p; p = p->next->next) {
Node *q = new Node(p->val);
q->next = p->next;
p->next = q;
}
for(auto p = head; p; p = p->next->next) {
if(p->random) {
p->next->random = p->random->next;
}
}
Node *dummy = new Node(-1), *curr = dummy;
for(auto p = head; p; p = p->next) {
auto q = p->next;
curr->next = q;
curr = curr->next;
p->next = q->next;
}
return dummy->next;
}
};
| 21.735537 | 64 | 0.490875 | CoderQuinnYoung |
6d8b4261bd7dc7fb9d4598f984fa2b17c6d5ff19 | 4,850 | cpp | C++ | 07. Raytracing */Old_version/main.cpp | Hollbrok/Ilab-2020-21 | 819a30dc4485ad874c273e9a01ca4adcf8bb2ea0 | [
"MIT"
] | 3 | 2021-12-06T20:39:29.000Z | 2022-02-04T14:59:33.000Z | 07. Raytracing */Old_version/main.cpp | Hollbrok/Ilab-2020-21 | 819a30dc4485ad874c273e9a01ca4adcf8bb2ea0 | [
"MIT"
] | null | null | null | 07. Raytracing */Old_version/main.cpp | Hollbrok/Ilab-2020-21 | 819a30dc4485ad874c273e9a01ca4adcf8bb2ea0 | [
"MIT"
] | null | null | null | #include "vector.h"
#include "Header.h"
bool UseTxPixel = false;
int main()
{
Vector vec1(1, 1, 1);
Vector vec2(23, -1, 0);
Vector vec3 = vec1 ^ vec2;
Vector vec4 = vec1 - vec2;
PRINT_VEC(vec3);
PRINT_VEC(vec4);
vec1.print();
vec1 += vec2;
vec1.print();
double r = 200;
txCreateWindow(800, 600);
txTextCursor(false);
txBegin();
//printf("1 cycle\n");
static double perf = txQueryPerformance();
//printf("2 cycle\n");
txSetTextAlign(TA_CENTER);
txSetColor(TX_DARKGRAY);
txSelectFont("Lucida Console", 15, 0);
txTextOut(txGetExtentX() / 2, txGetExtentY() * 19 / 20, "Press Z, R, X, H to bump, T to use txSetPixel(), "
"ESC to exit");
//printf("start cycle\n");
int counter = 0;
for (double t = txPI / 2; ; t += 0.1)
{
//printf("counter = %d\n", counter++);
DrawScene(Vector(-2 * r * (1 + cos(t)),
- 2 * r * cos(t),
+ 2 * r * sin(t)), r);
txSleep();
if (GetAsyncKeyState(VK_ESCAPE) && GetForegroundWindow() == txWindow()) break;
/* For FPS testing only: */
if (GetAsyncKeyState(VK_SPACE)) continue;
UseTxPixel = GetAsyncKeyState('T');
static char s[128] = "";
sprintf(s, "tx[Q]ueryPerformance(): %.2f. FPS %.2f. Using %s",
perf, txGetFPS(), (UseTxPixel ? "txSetPixel" : "direct memory access"));
SetWindowText(txWindow(), s);
}
//printf("end cycle\n");
txEnd();
return 0;
}
//--------------------------------------------------------------------------------------
void DrawScene(const Vector& lightPos, double r)
{
const Vector viewPos(0, 0, +5 * r);
const Vector materialColor(0.0, 1.0, 0.0);
const Vector lightColor(1.0, 0.7, 0.0);
const Vector ambientColor(0.2, 0.2, 0.2);
for (double y = +r; y >= -r; y--)
for (double x = -r; x <= +r; x++)
{
if (x * x + y * y > r * r) continue;
Vector p(x, y, 0);
p = p + Bump(p, r) * 100;
if (p.x_ * p.x_ + p.y_ * p.y_ > r * r) { DrawPixel(x, y, Vector()); continue; }
p.z_ = sqrt(r * r - p.x_ * p.x_ - p.y_ * p.y_);
Vector N = p.normalize() + Bump(p, r);
Vector V = (viewPos - p).normalize();
Vector L = (lightPos - p).normalize();
double diffuse = N.dot(L);
if (diffuse < 0) diffuse = 0;
Vector Lr = 2 * (N.dot(L)) * N - L;
double spec = Lr.dot(V);
if (spec < 0) spec = 0;
double specular = pow(spec, 25);
Vector color = ambientColor * materialColor +
diffuse * materialColor * lightColor +
specular * lightColor +
PhongLightning(p, N, V,
Vector(+2 * r, -1 * r, 0),
Vector(0.5, 0.5, 0.5),
materialColor);
DrawPixel(x, y, color);
}
}
//----------------------------------------------------------------------------
inline void DrawPixel(double x, double y, Vector color)
{
static POINT scr = txGetExtent();
POINT p = { (int)(x + scr.x / 2 + 0.5),
(int)(y + scr.y / 2 + 0.5) };
RGBQUAD rgb = { (BYTE)(Clamp(color.x_, 0, 1) * 255 + 0.5),
(BYTE)(Clamp(color.y_, 0, 1) * 255 + 0.5),
(BYTE)(Clamp(color.z_, 0, 1) * 255 + 0.5) };
if (UseTxPixel)
txSetPixel(p.x, p.y, RGB(rgb.rgbRed, rgb.rgbGreen, rgb.rgbBlue));
else
*(txVideoMemory() + p.x + (-p.y + scr.y) * scr.x) = rgb;
}
//----------------------------------------------------------------------------
Vector PhongLightning(const Vector& p, const Vector& N, const Vector& V,
const Vector& lightPos, const Vector& lightColor,
const Vector& materialColor,
const Vector& ambientColor)
{
Vector L = (lightPos - p).normalize();
double diffuse = sc_dot(N, L); //N.dot(L);
if (diffuse < 0) return ambientColor;
Vector Lr = 2 * diffuse * N - L;
double specular = pow(Lr.dot(V), 25);
return diffuse * lightColor * materialColor +
specular * lightColor + ambientColor;
}
//----------------------------------------------------------------------------
Vector Bump(const Vector& p, double r)
{
bool bXY = (GetAsyncKeyState('X') != 0),
bXY2 = (GetAsyncKeyState('H') != 0),
bZ = (GetAsyncKeyState('Z') != 0),
bRnd = (GetAsyncKeyState('R') != 0);
if (!bXY && !bXY2 && !bZ && !bRnd) return Vector();
const int sz = 100;
static Vector env[sz][sz] = {};
static bool init = false;
if (!init)
{
for (int y = 0; y < sz; y++) for (int x = 0; x < sz; x++)
env[y][x] = Vector(Random(-1, +1), Random(-1, +1), Random(-1, +1));
init = true;
}
Vector bump(0, 0, 0);
if (bXY) bump += p * ((sin(p.x_ / 4) + cos(p.y_ / 4)) / 4 + 1.5) / 5000.0;
if (bXY2) bump += p * ((cos(p.x_ / 4) + sin(p.y_ / 4)) / 2 + 1.0) / 3000.0;
if (bZ) bump += p * (sin(p.z_ * p.z_ / 500) / 2 + 1.5) / 5000.0;
if (bRnd) bump += env[(unsigned)ROUND(p.y_ + r) % sz][(unsigned)ROUND(p.x_ + r) % sz] / 100.0;
return bump;
}
inline double Random(double min, double max)
{
return min + (max - min) * rand() / RAND_MAX;
}
inline double Clamp(double value, double min, double max)
{
return (value < min) ? min : (value > max) ? max : value;
}
| 24.744898 | 108 | 0.539175 | Hollbrok |
6d8e89c686387fcf2dcceae129fe11fc3de109d9 | 3,245 | cpp | C++ | Sources/simdlib/SimdNeonStretchGray2x2.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | 6 | 2017-10-13T04:29:38.000Z | 2018-05-10T13:52:20.000Z | Sources/simdlib/SimdNeonStretchGray2x2.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | Sources/simdlib/SimdNeonStretchGray2x2.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* 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 "Simd/SimdMemory.h"
#include "Simd/SimdStore.h"
namespace Simd
{
#ifdef SIMD_NEON_ENABLE
namespace Neon
{
template<bool align> SIMD_INLINE void StretchGray2x2(const uint8_t * src, uint8_t * dst, size_t stride)
{
uint8x16x2_t _src;
_src.val[0] = Load<align>(src);
_src.val[1] = _src.val[0];
Store2<align>(dst, _src);
Store2<align>(dst + stride, _src);
}
template <bool align> void StretchGray2x2(
const uint8_t * src, size_t srcWidth, size_t srcHeight, size_t srcStride,
uint8_t * dst, size_t dstWidth, size_t dstHeight, size_t dstStride)
{
assert(srcWidth*2 == dstWidth && srcHeight*2 == dstHeight && srcWidth >= A);
if(align)
{
assert(Aligned(src) && Aligned(srcStride));
assert(Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(srcWidth, A);
for(size_t row = 0; row < srcHeight; ++row)
{
for(size_t srcCol = 0, dstCol = 0; srcCol < alignedWidth; srcCol += A, dstCol += DA)
StretchGray2x2<align>(src + srcCol, dst + dstCol, dstStride);
if(alignedWidth != srcWidth)
StretchGray2x2<false>(src + srcWidth - A, dst + dstWidth - DA, dstStride);
src += srcStride;
dst += 2*dstStride;
}
}
void StretchGray2x2(const uint8_t * src, size_t srcWidth, size_t srcHeight, size_t srcStride,
uint8_t * dst, size_t dstWidth, size_t dstHeight, size_t dstStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
StretchGray2x2<true>(src, srcWidth, srcHeight, srcStride, dst, dstWidth, dstHeight, dstStride);
else
StretchGray2x2<false>(src, srcWidth, srcHeight, srcStride, dst, dstWidth, dstHeight, dstStride);
}
}
#endif// SIMD_NEON_ENABLE
}
| 43.266667 | 113 | 0.634206 | aestesis |
6d902353e7eb14530215ac2d514319281e8a8c5c | 2,846 | cpp | C++ | server/src/streams/tests/ServerTestsWriter.cpp | PolyProgrammist/UTBotCpp | 4886622f21c92e3b73daa553008e541be9d82f21 | [
"Apache-2.0"
] | null | null | null | server/src/streams/tests/ServerTestsWriter.cpp | PolyProgrammist/UTBotCpp | 4886622f21c92e3b73daa553008e541be9d82f21 | [
"Apache-2.0"
] | null | null | null | server/src/streams/tests/ServerTestsWriter.cpp | PolyProgrammist/UTBotCpp | 4886622f21c92e3b73daa553008e541be9d82f21 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved.
*/
#include "ServerTestsWriter.h"
#include <utils/FileSystemUtils.h>
void ServerTestsWriter::writeTestsWithProgress(tests::TestsMap &testMap,
std::string const &message,
const fs::path &testDirPath,
std::function<void(tests::Tests &)> &&functor) {
size_t size = testMap.size();
writeProgress(message);
int totalTestsCounter = 0;
for (auto it = testMap.begin(); it != testMap.end(); it++) {
tests::Tests &tests = it.value();
ExecUtils::throwIfCancelled();
functor(tests);
if (writeFileAndSendResponse(tests, testDirPath, message, 100.0 / size, false)) {
totalTestsCounter += 1;
}
}
writeCompleted(testMap, totalTestsCounter);
}
void ServerTestsWriter::writeStubs(const vector<Stubs> &synchronizedStubs) {
testsgen::TestsResponse response;
auto stubsResponse = std::make_unique<testsgen::StubsResponse>();
for (auto const &synchronizedStub : synchronizedStubs) {
auto sData = stubsResponse->add_stubsources();
sData->set_filepath(synchronizedStub.filePath);
if (synchronizeCode) {
sData->set_code(synchronizedStub.code);
}
}
response.set_allocated_stubs(stubsResponse.release());
}
bool ServerTestsWriter::writeFileAndSendResponse(const tests::Tests &tests,
const fs::path &testDirPath,
const string &message,
double percent,
bool isCompleted) const {
fs::path testFilePath = testDirPath / tests.relativeFileDir / tests.testFilename;
FileSystemUtils::writeToFile(testFilePath, tests.code);
if (!hasStream()) {
return false;
}
testsgen::TestsResponse response;
LOG_S(DEBUG) << "Creating final response.";
bool isAnyTestsGenerated = false;
if (!tests.code.empty()) {
isAnyTestsGenerated = true;
auto testSource = response.add_testsources();
testSource->set_filepath(tests.testSourceFilePath);
if (synchronizeCode) {
testSource->set_code(tests.code);
}
auto testHeader = response.add_testsources();
testHeader->set_filepath(tests.testHeaderFilePath);
if (synchronizeCode) {
testHeader->set_code(tests.headerCode);
}
}
LOG_S(INFO) << message;
auto progress = GrpcUtils::createProgress(message, percent, isCompleted);
response.set_allocated_progress(progress.release());
writeMessage(response);
return isAnyTestsGenerated;
}
| 37.946667 | 95 | 0.601546 | PolyProgrammist |
6d9139e3c5860296da18e7907059fbfc9d0aef8c | 6,965 | cpp | C++ | Algorithms on Strings/Suffix tree/non_shared_substring.cpp | OssamaEls/Data-Structures-and-Algorithms | b6affc28a792f577010e666d565ec6cc7f0ecbfa | [
"MIT"
] | null | null | null | Algorithms on Strings/Suffix tree/non_shared_substring.cpp | OssamaEls/Data-Structures-and-Algorithms | b6affc28a792f577010e666d565ec6cc7f0ecbfa | [
"MIT"
] | null | null | null | Algorithms on Strings/Suffix tree/non_shared_substring.cpp | OssamaEls/Data-Structures-and-Algorithms | b6affc28a792f577010e666d565ec6cc7f0ecbfa | [
"MIT"
] | null | null | null | //Input Format.Strings Text1and Text2.
//Constraints. 1 ≤ | Text1 | , | Text2 | ≤ 2 000; strings have equal length(| Text1 | = | Text2 | ), are not equal
//(Text1 ̸ = Text2), and contain symbols A, C, G, T only.
//Output Format.The shortest(non - empty) substring of Text1 that does not appear in Text2. (Multiple
// solutions may exist, in which case you may return any one.)
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
struct Edge
{
int child;
int start;
int length;
Edge(int child_, int start_, int length_) :
child(child_), start(start_), length(length_) {}
Edge(const Edge& e) : child(e.child), start(e.start), length(e.length) {}
};
typedef map<int, vector<Edge>> tree;
struct NodeEdge {
tree t;
map<int, int> lengths;
map<int, bool> r_node;
};
NodeEdge ComputeSuffixTreeEdges(const string& text) {
const int n = text.size();
tree t;
map<int, int> lengths;
map<int, bool> r_node;
int current_node = 0;
int new_node = 1;
int k;
int match_length;
int idx;
t[current_node].push_back({ new_node, 0, n });
lengths[0] = 0;
lengths[1] = n;
for (size_t i = 1; i < n / 2 - 1; i++)
{
current_node = 0;
idx = 0;
while (!t[current_node].empty())
{
bool match = false;
int offset = 0;
for (size_t j = 0; j < t[current_node].size(); j++)
{
if (text[t[current_node][j].start] == text[i + idx])
{
match = true;
k = j;
break;
}
}
if (match)
{
match_length = t[current_node][k].length < n - i - idx ? t[current_node][k].length : n - i - idx;
++idx;
++offset;
for (size_t j = 1; j < match_length; j++)
{
if (text[t[current_node][k].start + j] != text[i + idx]) break;
++idx;
++offset;
}
if (offset == match_length)
{
current_node = t[current_node][k].child;
}
else
{
++new_node;
int adjusted = i + idx - offset;
Edge broken = Edge(t[current_node][k]);
t[current_node][k] = Edge(new_node, adjusted, offset);
t[new_node].push_back(Edge(broken.child, broken.start + offset, broken.length - offset));
t[new_node].push_back(Edge(new_node + 1, i + idx, n - i - idx));
lengths[new_node] = lengths[current_node] + offset;
lengths[new_node + 1] = lengths[new_node] + n - i - idx;
r_node[new_node] = false;
r_node[new_node + 1] = false;
++new_node;
current_node = new_node;
}
}
else
{
++new_node;
t[current_node].push_back(Edge(new_node, i + idx, n - i - idx));
lengths[new_node] = lengths[current_node] + n - i - idx;
r_node[new_node] = false;
current_node = new_node;
}
}
}
for (size_t i = n / 2 - 1; i < n; i++)
{
current_node = 0;
idx = 0;
while (!t[current_node].empty())
{
bool match = false;
int offset = 0;
for (size_t j = 0; j < t[current_node].size(); j++)
{
if (text[t[current_node][j].start] == text[i + idx])
{
match = true;
k = j;
break;
}
}
if (match)
{
match_length = t[current_node][k].length < n - i - idx ? t[current_node][k].length : n - i - idx;
++idx;
++offset;
for (size_t j = 1; j < match_length; j++)
{
if (text[t[current_node][k].start + j] != text[i + idx]) break;
++idx;
++offset;
}
if (offset == match_length)
{
current_node = t[current_node][k].child;
r_node[current_node] = true;
}
else
{
++new_node;
int adjusted = i + idx - offset;
Edge broken = Edge(t[current_node][k]);
t[current_node][k] = Edge(new_node, adjusted, offset);
t[new_node].push_back(Edge(broken.child, broken.start + offset, broken.length - offset));
t[new_node].push_back(Edge(new_node + 1, i + idx, n - i - idx));
lengths[new_node] = lengths[current_node] + offset;
lengths[new_node + 1] = lengths[new_node] + n - i - idx;
r_node[new_node] = true;
r_node[new_node + 1] = true;
++new_node;
current_node = new_node;
}
}
else
{
++new_node;
t[current_node].push_back(Edge(new_node, i + idx, n - i - idx));
lengths[new_node] = lengths[current_node] + n - i - idx;
r_node[new_node] = true;
current_node = new_node;
}
}
}
r_node[0] = true;
return { t, lengths, r_node };
}
string solve(string p, string q)
{
string pq = "";
pq.append(p).append("#").append(q).append("$");
const int n = p.size();
NodeEdge ne = ComputeSuffixTreeEdges(pq);
tree& t = ne.t;
map<int, int>& lengths = ne.lengths;
map<int, bool>& r_node = ne.r_node;
int shortest_length = n;
int start = 0;
int current_node;
for (auto it = t.begin(); it != t.end(); it++)
{
if (r_node[it->first] && lengths[it->first] + 1 < shortest_length)
{
for (Edge& edge : it->second)
{
if (!r_node[edge.child] && edge.length != n + 2)
{
shortest_length = lengths[it->first] + 1;
start = edge.start - lengths[it->first];
break;
}
}
}
}
return p.substr(start, shortest_length);
}
int main(void)
{
string p;
cin >> p;
string q;
cin >> q;
string ans = solve(p, q);
cout << ans << endl;
return 0;
} | 30.151515 | 115 | 0.429146 | OssamaEls |
6d9924a06208b34422676369dbb5715a16f0e7d0 | 830 | hpp | C++ | projects/engine/extern/rendering/opengl/ri_opengl4.hpp | zCubed3/Tilt | e9c68b96eb8dea47b70ba734bc2ef4cffc30a2af | [
"MIT"
] | null | null | null | projects/engine/extern/rendering/opengl/ri_opengl4.hpp | zCubed3/Tilt | e9c68b96eb8dea47b70ba734bc2ef4cffc30a2af | [
"MIT"
] | null | null | null | projects/engine/extern/rendering/opengl/ri_opengl4.hpp | zCubed3/Tilt | e9c68b96eb8dea47b70ba734bc2ef4cffc30a2af | [
"MIT"
] | null | null | null | #ifndef TILT_OPENGL_INTERFACE_HPP
#define TILT_OPENGL_INTERFACE_HPP
#include "../render_interface.hpp"
class RI_OpenGL4 : public RI_Impl {
public:
//
// Metadata
//
const char * get_ApiName() override;
const char * get_Signature() override;
//
// Setup
//
void setup_Initial() override;
void setup_BeforeWindowCreate() override;
void setup_AfterWindowCreate(GLFWwindow* window) override;
// Drawing
void draw_Clear() override;
void draw_Present(GLFWwindow *window) override;
//
// ImGui
//
void imgui_Setup(GLFWwindow *window) override;
void imgui_Begin() override;
void imgui_End() override;
//
// Features
//
void feature_SetCullMode(CullMode mode) override;
void feature_SetDepthMode(DepthMode mode) override;
};
#endif
| 20.75 | 62 | 0.678313 | zCubed3 |
6d9abe0bf8bd4827fc3a7d53cbd28ec73702d748 | 310 | cpp | C++ | src/JumpGameII.cpp | harborn/LeetCode | 8488c0bcf306b8672492fd6220e496e335e2b9fe | [
"MIT"
] | null | null | null | src/JumpGameII.cpp | harborn/LeetCode | 8488c0bcf306b8672492fd6220e496e335e2b9fe | [
"MIT"
] | 1 | 2021-12-14T15:56:11.000Z | 2021-12-14T15:56:11.000Z | src/JumpGameII.cpp | harborn/LeetCode | 8488c0bcf306b8672492fd6220e496e335e2b9fe | [
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int jump(int A[], int n) {
int maxPos = 0, lastMaxPos = 0;
int res = 0;
for (int i = 0; i < n; i++) {
if (i > lastMaxPos) {
res++;
lastMaxPos = maxPos;
}
if (i + A[i] > maxPos)
maxPos = i + A[i];
}
return res;
}
int main(void) {
return 0;
}
| 11.923077 | 32 | 0.532258 | harborn |
6d9b5206c1ca53bcdb0d51e417b69f5fd8ecf432 | 8,528 | cpp | C++ | src/Core/Input/InputXML.cpp | tgcy210/cyclus | b9402710be94403d33aa5a9b9aa546cdcca1cb86 | [
"Unlicense"
] | 1 | 2018-07-29T16:10:02.000Z | 2018-07-29T16:10:02.000Z | src/Core/Input/InputXML.cpp | tgcy210/cyclus | b9402710be94403d33aa5a9b9aa546cdcca1cb86 | [
"Unlicense"
] | null | null | null | src/Core/Input/InputXML.cpp | tgcy210/cyclus | b9402710be94403d33aa5a9b9aa546cdcca1cb86 | [
"Unlicense"
] | null | null | null | // InputXML.cpp
// Implements XML input handling class
#include <iostream>
#include <string>
#include <sys/stat.h>
#include "InputXML.h"
#include "Timer.h"
#include "Env.h"
#include "RecipeLibrary.h"
#include "CycException.h"
#include "Model.h"
//#include "Material.h"
#include "Logger.h"
InputXML* InputXML::instance_ = 0;
using namespace std;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string InputXML::main_schema_ = "/share/cyclus.rng";
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
InputXML::InputXML() {
cur_ns_ = "";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
InputXML* InputXML::Instance() {
main_schema_ = Env::getInstallPath() + "/share/cyclus.rng";
if (0 == instance_)
instance_ = new InputXML();
return instance_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
xmlDocPtr InputXML::validate_file(xmlFileInfo *fileInfo) {
xmlRelaxNGParserCtxtPtr ctxt = xmlRelaxNGNewParserCtxt(fileInfo->schema->c_str());
if (NULL == ctxt)
throw CycParseException("Failed to generate parser from schema: " + *(fileInfo->schema));
xmlRelaxNGPtr schema = xmlRelaxNGParse(ctxt);
xmlRelaxNGValidCtxtPtr vctxt = xmlRelaxNGNewValidCtxt(schema);
xmlDocPtr doc = xmlReadFile(fileInfo->filename.c_str(), NULL,0);
if (NULL == doc) {
throw CycParseException("Failed to parse: " + fileInfo->filename);
}
if (xmlRelaxNGValidateDoc(vctxt,doc))
throw CycParseException("Invalid XML file; file: "
+ fileInfo->filename
+ " does not validate against schema "
+ *(fileInfo->schema));
/// free up some data
return doc;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::stripCurNS() {
if ("" == cur_ns_)
throw CycParseException("Unable to strip tokens from an empty namespace.");
string::iterator pos = cur_ns_.end();
cur_ns_.erase(--pos);
size_t delimeter_pos = cur_ns_.rfind(':');
if (string::npos != delimeter_pos)
cur_ns_.erase(delimeter_pos);
else
cur_ns_.erase();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::load_file(std::string filename) {
// double check that the file exists
if(filename=="") {
throw CycIOException("No input filename was given");
} else {
FILE* file = fopen(filename.c_str(),"r");
if (file == NULL) {
throw CycIOException("The file '" + filename
+ "' cannot be loaded because it has not been found.");
}
fclose(file);
}
curFilePtr = new xmlFileInfo;
xmlFileInfo &inputFile = *curFilePtr;
inputFile.filename = filename;
inputFile.schema = &main_schema_;
inputFile.doc = validate_file(&inputFile);
/* Create xpath evaluation context */
inputFile.xpathCtxt = xmlXPathNewContext(inputFile.doc);
if (inputFile.xpathCtxt == NULL) {
fprintf(stderr,"Error: unable to create new xpath context \n");
}
// timer sets data
initializeSimulationTimeData();
// recipes, markets, converters, prototypes
loadGlobalSimulationElements();
// regions, institutions
loadSimulationEntities();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::loadGlobalSimulationElements() {
// Recipes
LOG(LEV_DEBUG3, "none!") << "Begin loading recipes";
RecipeLibrary::load_recipes();
LOG(LEV_DEBUG3, "none!") << "End loading recipes";
//Models
LOG(LEV_DEBUG3, "none!") << "Begin loading elements";
Model::loadGlobalElements();
LOG(LEV_DEBUG3, "none!") << "End loading elements";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::loadSimulationEntities() {
LOG(LEV_DEBUG3, "none!") << "Begin loading entities";
Model::loadEntities();
LOG(LEV_DEBUG3, "none!") << "End loading entities";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::initializeSimulationTimeData() {
TI->load_simulation();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::load_recipebook(std::string filename) {
/// store parent file info
fileStack_.push(curFilePtr);
curFilePtr = new xmlFileInfo;
xmlFileInfo &recipebook = *curFilePtr;
recipebook.filename = filename;
recipebook.schema = &main_schema_;
recipebook.doc = validate_file(&recipebook);
recipebook.xpathCtxt = xmlXPathNewContext(recipebook.doc);
RecipeLibrary::load_recipes();
// get rid of recipebook, freeing memory
delete curFilePtr;
/// restore parent file info
curFilePtr = fileStack_.top();
fileStack_.pop();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void InputXML::load_facilitycatalog(std::string filename) {
/// store parent file info
fileStack_.push(curFilePtr);
curFilePtr = new xmlFileInfo;
xmlFileInfo &facilitycatalog = *curFilePtr;
facilitycatalog.filename = filename;
facilitycatalog.schema = &main_schema_;
facilitycatalog.doc = validate_file(&facilitycatalog);
facilitycatalog.xpathCtxt = xmlXPathNewContext(facilitycatalog.doc);
/// load here???
LOG(LEV_DEBUG3, "none!") << "Begin loading models - facilities";
Model::load_facilities();
LOG(LEV_DEBUG3, "none!") << "End loading models - facilities";
// get rid of facilitycatalog, freeing memory
delete curFilePtr;
/// restore parent file info
curFilePtr = fileStack_.top();
fileStack_.pop();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
xmlNodeSetPtr InputXML::get_xpath_elements(xmlXPathContextPtr& context,
xmlNodePtr& cur,
const char* expression) {
context->node = cur;
/* Evaluate xpath expression */
xmlXPathObjectPtr xpathObj =
xmlXPathEvalExpression((const xmlChar*)expression, context);
if(xmlXPathNodeSetIsEmpty(xpathObj->nodesetval)) {
stringstream ss("");
ss << "Error: unable to evaluate xpath expression "
<< expression;
throw CycNullXPathException(ss.str());
}
return xpathObj->nodesetval;
// when and how to cleanup memory allocation?
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
xmlNodePtr InputXML::get_xpath_element(xmlXPathContextPtr& context,
xmlNodePtr& cur,
const char* expression) {
context->node = cur;
/* Evaluate xpath expression */
xmlXPathObjectPtr xpathObj =
xmlXPathEvalExpression((const xmlChar*)expression,context);
if(xmlXPathNodeSetIsEmpty(xpathObj->nodesetval)) {
stringstream ss("");
ss << "Error: unable to evaluate xpath expression "
<< expression;
throw CycNullXPathException(ss.str());
}
return xpathObj->nodesetval->nodeTab[0];
// when and how to cleanup memory allocation?
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const char* InputXML::get_xpath_content(xmlXPathContextPtr& context,
xmlNodePtr& cur,
const char* expression) {
context->node = cur;
/* Evaluate xpath expression */
xmlXPathObjectPtr xpathObj =
xmlXPathEvalExpression((const xmlChar*)expression, context);
if(xmlXPathNodeSetIsEmpty(xpathObj->nodesetval)) {
stringstream ss("");
ss << "Error: unable to evaluate xpath expression "
<< expression;
throw CycNullXPathException(ss.str());
}
return (const char*)(xpathObj->nodesetval->
nodeTab[0]->children->content);
// when and how to cleanup memory allocation?
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const char* InputXML::get_xpath_name(xmlXPathContextPtr& context,
xmlNodePtr& cur,
const char* expression) {
context->node = cur;
/* Evaluate xpath expression */
xmlXPathObjectPtr xpathObj =
xmlXPathEvalExpression((const xmlChar*)expression, context);
if(xmlXPathNodeSetIsEmpty(xpathObj->nodesetval)) {
stringstream ss("");
ss << "Error: unable to evaluate xpath expression "
<< expression;
throw CycNullXPathException(ss.str());
}
return (const char*)(xpathObj->nodesetval->nodeTab[0]->name);
// when and how to cleanup memory allocation?
}
| 29.006803 | 91 | 0.576923 | tgcy210 |
6d9da3bc285ea7c86bd981949c817d65a5b6c9e5 | 7,980 | cpp | C++ | TerraFighterDev/2DFont.cpp | cjburchell/terrafighter | debc9b7563de05263d9159fbff15407a2dcb0fe9 | [
"Apache-2.0"
] | null | null | null | TerraFighterDev/2DFont.cpp | cjburchell/terrafighter | debc9b7563de05263d9159fbff15407a2dcb0fe9 | [
"Apache-2.0"
] | null | null | null | TerraFighterDev/2DFont.cpp | cjburchell/terrafighter | debc9b7563de05263d9159fbff15407a2dcb0fe9 | [
"Apache-2.0"
] | null | null | null | // 2DFont.cpp: implementation of the C2DFont class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "2DFont.h"
#include "dxutil.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define D3DFVF_FONTVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)
struct FONTVERTEX
{
D3DXVECTOR4 position; // The position.
D3DCOLOR color; // The color.
FLOAT tu, tv; // The texture coordinates.
};
C2DFont::C2DFont( TCHAR* strFontName, FLOAT dwHeight, FLOAT dwWidth)
{
_tcscpy( m_strFontName, strFontName );
m_fFontHeight = dwHeight;
m_fFontWidth = dwWidth;
m_pd3dDevice = NULL;
m_pTexture = NULL;
m_VertexBuffer = NULL;
}
C2DFont::~C2DFont()
{
SAFE_RELEASE( m_VertexBuffer);
SAFE_RELEASE( m_pTexture );
m_pd3dDevice = NULL;
}
HRESULT C2DFont::Init(LPDIRECT3DDEVICE8 pd3dDevice)
{
HRESULT hr;
m_pd3dDevice = pd3dDevice;
DWORD dwTexWidth, dwTexHeight;
dwTexHeight = dwTexWidth = 256;
hr = m_pd3dDevice->CreateTexture( dwTexWidth, dwTexHeight, 1,
0, D3DFMT_A4R4G4B4,
D3DPOOL_MANAGED, &m_pTexture );
if( FAILED(hr) )
{
DEBUG_MSG_HR("CreateTexture",hr);
return hr;
}
// Prepare to create a bitmap
DWORD* pBitmapBits;
BITMAPINFO bmi;
ZeroMemory( &bmi.bmiHeader, sizeof(BITMAPINFOHEADER) );
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = (int)dwTexWidth;
bmi.bmiHeader.biHeight = -(int)dwTexHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biBitCount = 32;
// Create a DC and a bitmap for the font
HDC hDC = CreateCompatibleDC( NULL );
HBITMAP hbmBitmap = CreateDIBSection( hDC, &bmi, DIB_RGB_COLORS,
(VOID**)&pBitmapBits, NULL, 0 );
SetMapMode( hDC, MM_TEXT );
// Create a font. By specifying ANTIALIASED_QUALITY, we might get an
// antialiased font, but this is not guaranteed.
INT nHeight = 12;
DWORD dwBold = FW_NORMAL;
DWORD dwItalic = FALSE;
HFONT hFont = CreateFont( nHeight, 0, 0, 0, dwBold, dwItalic,
FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,
VARIABLE_PITCH, m_strFontName );
if( NULL==hFont )
return E_FAIL;
SelectObject( hDC, hbmBitmap );
SelectObject( hDC, hFont );
// Set text properties
SetTextColor( hDC, D3DCOLOR_XRGB(255,255,255) );
SetBkColor( hDC, 0x00000000 );
SetTextAlign( hDC, TA_TOP );
// Loop through all printable character and output them to the bitmap..
// Meanwhile, keep track of the corresponding tex coords for each character.
DWORD x = 0;
DWORD y = 0;
TCHAR str[2] = _T("x");
SIZE size;
for( TCHAR c=32; c<127; c++ )
{
str[0] = c;
GetTextExtentPoint32( hDC, str, 1, &size );
if( (DWORD)(x+size.cx+1) > dwTexWidth )
{
x = 0;
y += size.cy+1;
}
ExtTextOut( hDC, x+0, y+0, ETO_OPAQUE, NULL, str, 1, NULL );
m_fTexCoords[c-32][0] = ((FLOAT)(x+0))/dwTexWidth;
m_fTexCoords[c-32][1] = ((FLOAT)(y+0))/dwTexHeight;
m_fTexCoords[c-32][2] = ((FLOAT)(x+0+size.cx))/dwTexWidth;
m_fTexCoords[c-32][3] = ((FLOAT)(y+0+size.cy))/dwTexHeight;
x += size.cx+1;
}
// Lock the surface and write the alpha values for the set pixels
D3DLOCKED_RECT d3dlr;
m_pTexture->LockRect( 0, &d3dlr, 0, 0 );
WORD* pDst16 = (WORD*)d3dlr.pBits;
BYTE bAlpha; // 4-bit measure of pixel intensity
for( y=0; y < dwTexHeight; y++ )
{
for( x=0; x < dwTexWidth; x++ )
{
bAlpha = (BYTE)((pBitmapBits[dwTexWidth*y + x] & 0xff) >> 4);
if (bAlpha > 0)
{
*pDst16++ = (bAlpha << 12) | 0x0fff;
}
else
{
*pDst16++ = 0x0000;
}
}
}
// Done updating texture, so clean up used objects
m_pTexture->UnlockRect(0);
DeleteObject( hbmBitmap );
DeleteDC( hDC );
DeleteObject( hFont );
if( FAILED( hr = m_pd3dDevice->CreateVertexBuffer( 4*sizeof(FONTVERTEX), D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC, D3DFVF_FONTVERTEX, D3DPOOL_DEFAULT, &m_VertexBuffer ) ) )
{
SAFE_RELEASE( m_pTexture );
return hr;
}
return S_OK;
}
HRESULT C2DFont::DrawText( FLOAT sx, FLOAT sy, DWORD dwColor, TCHAR* strText)
{
// Set diffuse blending for alpha set in vertices.
m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
// Enable alpha testing (skips pixels with less than a certain alpha.)
//if( m_d3dCaps.AlphaCmpCaps & D3DPCMPCAPS_GREATEREQUAL )
{
m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_ALPHAREF, 0x08 );
m_pd3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );
}
// m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
// m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_POINT );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_POINT );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MIPFILTER, D3DTEXF_NONE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
m_pd3dDevice->SetVertexShader( D3DFVF_FONTVERTEX );
m_pd3dDevice->SetStreamSource(0, m_VertexBuffer, sizeof(FONTVERTEX));
m_pd3dDevice->SetTexture( 0, m_pTexture );
FLOAT w = m_fFontWidth;
FLOAT h = m_fFontHeight;
FONTVERTEX* pVertices;
while( *strText )
{
TCHAR c = *strText++;
if( c < _T(' ') )
{
sx += w;
continue;
}
FLOAT tx1 = m_fTexCoords[c-32][0];
FLOAT ty1 = m_fTexCoords[c-32][1];
FLOAT tx2 = m_fTexCoords[c-32][2];
FLOAT ty2 = m_fTexCoords[c-32][3];
m_VertexBuffer->Lock( 0, 4*sizeof(FONTVERTEX), (BYTE**)&pVertices, D3DLOCK_DISCARD );
pVertices[0].position = D3DXVECTOR4(sx,sy,0.0f,1.0f); //topleft
pVertices[0].color = dwColor;
pVertices[0].tu=tx1;
pVertices[0].tv=ty1;
pVertices[1].position = D3DXVECTOR4(sx+w,sy,0.0f,1.0f); //topright
pVertices[1].color = dwColor;
pVertices[1].tu=tx2;
pVertices[1].tv=ty1;
pVertices[2].position = D3DXVECTOR4(sx,sy-h,0.0f,1.0f); //bottom left
pVertices[2].color = dwColor;
pVertices[2].tu=tx1;
pVertices[2].tv=ty2;
pVertices[3].position = D3DXVECTOR4(sx+w,sy-h,0.0f,1.0f); //bottom right
pVertices[3].color = dwColor;
pVertices[3].tu=tx2;
pVertices[3].tv=ty2;
m_VertexBuffer->Unlock();
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 );
sx += w;
}
m_pd3dDevice->SetTexture( 0, NULL );
m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
return S_OK;
}
void C2DFont::DeleteDeviceObjects()
{
m_pd3dDevice = NULL;
SAFE_RELEASE( m_VertexBuffer );
SAFE_RELEASE( m_pTexture );
}
| 31.666667 | 168 | 0.629699 | cjburchell |
6d9e9ae225f903da0f3266f456b0ad7c1f3ee6b2 | 7,532 | tcc | C++ | include/DataFrame/Vectors/HeteroPtrView.tcc | wtom76/DataFrame | 5302254fab329310b09d1efcb2e860c71e25b5c3 | [
"BSD-3-Clause"
] | null | null | null | include/DataFrame/Vectors/HeteroPtrView.tcc | wtom76/DataFrame | 5302254fab329310b09d1efcb2e860c71e25b5c3 | [
"BSD-3-Clause"
] | null | null | null | include/DataFrame/Vectors/HeteroPtrView.tcc | wtom76/DataFrame | 5302254fab329310b09d1efcb2e860c71e25b5c3 | [
"BSD-3-Clause"
] | null | null | null | // Hossein Moein
// June 24, 2019
// Copyright (C) 2018-2019 Hossein Moein
// Distributed under the BSD Software License (see file License)
#include <algorithm>
// ----------------------------------------------------------------------------
namespace hmdf
{
template<typename T>
HeteroPtrView::HeteroPtrView(T *begin_ptr, T *end_ptr)
: clear_function_([](HeteroPtrView &hv) { views_<T>.erase(&hv); }),
copy_function_([](const HeteroPtrView &from, HeteroPtrView &to) {
views_<T>[&to] = views_<T>[&from]; }),
move_function_([](HeteroPtrView &from, HeteroPtrView &to) {
views_<T>[&to] = std::move(views_<T>[&from]); }) {
views_<T>.emplace(this, VectorPtrView<T>(begin_ptr, end_ptr));
}
// ----------------------------------------------------------------------------
template<typename T>
HeteroPtrView::HeteroPtrView(VectorPtrView<T> &vec)
: clear_function_([](HeteroPtrView &hv) { views_<T>.erase(&hv); }),
copy_function_([](const HeteroPtrView &from, HeteroPtrView &to) {
views_<T>[&to] = views_<T>[&from]; }),
move_function_([](HeteroPtrView &from, HeteroPtrView &to) {
views_<T>[&to] = std::move(views_<T>[&from]); }) {
views_<T>.push_back(this, vec);
}
// ----------------------------------------------------------------------------
template<typename T>
HeteroPtrView::HeteroPtrView(VectorPtrView<T> &&vec)
: clear_function_([](HeteroPtrView &hv) { views_<T>.erase(&hv); }),
copy_function_([](const HeteroPtrView &from, HeteroPtrView &to) {
views_<T>[&to] = views_<T>[&from]; }),
move_function_([](HeteroPtrView &from, HeteroPtrView &to) {
views_<T>[&to] = std::move(views_<T>[&from]); }) {
views_<T>.emplace(this, std::move(vec));
}
// ----------------------------------------------------------------------------
template<typename T>
VectorPtrView<T> &HeteroPtrView::get_vector() {
auto iter = views_<T>.find (this);
if (iter == views_<T>.end())
throw std::runtime_error("HeteroPtrView::get_vector(): ERROR: "
"Cannot find view");
return (iter->second);
}
// ----------------------------------------------------------------------------
template<typename T>
const VectorPtrView<T> &HeteroPtrView::get_vector() const {
return (const_cast<HeteroPtrView *>(this)->get_vector<T>());
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroPtrView::visit_impl_help_ (T &visitor) {
auto iter = views_<U>.find (this);
if (iter != views_<U>.end()) {
#ifndef _WIN32
for (auto &&element : iter->second)
visitor(element);
#else
const size_type vec_size = iter->second.size();
for (size_type i = 0; i < vec_size; ++i)
visitor(iter->second[i]);
#endif // _WIN32
}
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroPtrView::visit_impl_help_ (T &visitor) const {
const auto citer = views_<U>.find (this);
if (citer != views_<U>.end()) {
#ifndef _WIN32
for (auto &&element : citer->second)
visitor(element);
#else
const size_type vec_size = citer->second.size();
for (size_type i = 0; i < vec_size; ++i)
visitor(citer->second[i]);
#endif // _WIN32
}
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroPtrView::sort_impl_help_ (T &functor) {
auto iter = views_<U>.find (this);
if (iter != views_<U>.end())
std::sort (iter->second.begin(), iter->second.end(), functor);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroPtrView::change_impl_help_ (T &functor) {
auto iter = views_<U>.find (this);
if (iter != views_<U>.end())
functor(iter->second);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroPtrView::change_impl_help_ (T &functor) const {
const auto citer = views_<U>.find (this);
if (citer != views_<U>.end())
functor(citer->second);
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroPtrView::visit_impl_ (T &&visitor, TLIST<TYPES...>) {
// (..., visit_impl_help_<std::decay_t<T>, TYPES>(visitor)); // C++17
using expander = int[];
(void) expander { 0, (visit_impl_help_<T, TYPES>(visitor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroPtrView::visit_impl_ (T &&visitor, TLIST<TYPES...>) const {
// (..., visit_impl_help_<std::decay_t<T>, TYPES>(visitor)); // C++17
using expander = int[];
(void) expander { 0, (visit_impl_help_<T, TYPES>(visitor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroPtrView::sort_impl_ (T &&functor, TLIST<TYPES...>) {
using expander = int[];
(void) expander { 0, (sort_impl_help_<T, TYPES>(functor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroPtrView::change_impl_ (T &&functor, TLIST<TYPES...>) {
using expander = int[];
(void) expander { 0, (change_impl_help_<T, TYPES>(functor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroPtrView::change_impl_ (T &&functor, TLIST<TYPES...>) const {
using expander = int[];
(void) expander { 0, (change_impl_help_<T, TYPES>(functor), 0) ... };
}
// ----------------------------------------------------------------------------
template<typename T>
bool HeteroPtrView::empty() const noexcept {
return (get_vector<T>().empty ());
}
// ----------------------------------------------------------------------------
template<typename T>
T &HeteroPtrView::at(size_type idx) {
return (get_vector<T>()[idx]);
}
// ----------------------------------------------------------------------------
template<typename T>
const T &HeteroPtrView::at(size_type idx) const {
return (get_vector<T>()[idx]);
}
// ----------------------------------------------------------------------------
template<typename T>
T &HeteroPtrView::back() { return (get_vector<T>().back ()); }
// ----------------------------------------------------------------------------
template<typename T>
const T &HeteroPtrView::back() const { return (get_vector<T>().back ()); }
// ----------------------------------------------------------------------------
template<typename T>
T &HeteroPtrView::front() { return (get_vector<T>().front ()); }
// ----------------------------------------------------------------------------
template<typename T>
const T &HeteroPtrView::front() const { return (get_vector<T>().front ()); }
} // namespace hmdf
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
| 30.742857 | 79 | 0.471588 | wtom76 |
6da02d37893ff3aa0535cfe25955cb53af692d44 | 11,794 | hpp | C++ | include/caffe/data_layers.hpp | xiaomi646/caffe_2d_mlabel | 912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65 | [
"BSD-2-Clause"
] | 1 | 2015-07-08T15:30:06.000Z | 2015-07-08T15:30:06.000Z | include/caffe/data_layers.hpp | xiaomi646/caffe_2d_mlabel | 912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65 | [
"BSD-2-Clause"
] | null | null | null | include/caffe/data_layers.hpp | xiaomi646/caffe_2d_mlabel | 912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2014 BVLC and contributors.
#ifndef CAFFE_DATA_LAYERS_HPP_
#define CAFFE_DATA_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "leveldb/db.h"
#include "lmdb.h"
#include "pthread.h"
#include "hdf5.h"
#include "boost/scoped_ptr.hpp"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
#define HDF5_DATA_DATASET_NAME "data"
#define HDF5_DATA_LABEL_NAME "label"
// TODO: DataLayer, ImageDataLayer, and WindowDataLayer all have the
// same basic structure and a lot of duplicated code.
// This function is used to create a pthread that prefetches the data.
template <typename Dtype>
void* DataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class DataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* DataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit DataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~DataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
virtual void ProcessLabelSelectParam();
virtual void ReadLabelProbMappingFile(const string& file_name);
virtual void compute_label_skip_rate();
virtual bool accept_given_label(const int label);
virtual int get_converted_label(const int label);
shared_ptr<Caffe::RNG> prefetch_rng_;
// LEVELDB
shared_ptr<leveldb::DB> db_;
shared_ptr<leveldb::Iterator> iter_;
// LMDB
MDB_env* mdb_env_;
MDB_dbi mdb_dbi_;
MDB_txn* mdb_txn_;
MDB_cursor* mdb_cursor_;
MDB_val mdb_key_, mdb_value_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
bool output_labels_;
Caffe::Phase phase_;
// These are parameters for labels select/balance functions.
std::map <int, float> label_prob_map_;
std::map <int, unsigned int> label_skip_rate_map_;
std::map <int, int> label_mapping_map_;
unsigned int num_labels_;
unsigned int num_labels_with_prob_ ;
bool balancing_label_;
unsigned int num_top_label_balance_;
bool rest_of_label_mapping_;
bool map2order_label_;
bool ignore_rest_of_label_;
int rest_of_label_mapping_label_;
float rest_of_label_prob_;
};
template <typename Dtype>
class DummyDataLayer : public Layer<Dtype> {
public:
explicit DummyDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_DUMMY_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
vector<shared_ptr<Filler<Dtype> > > fillers_;
vector<bool> refill_;
};
template <typename Dtype>
class HDF5DataLayer : public Layer<Dtype> {
public:
explicit HDF5DataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~HDF5DataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HDF5_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void LoadHDF5FileData(const char* filename);
std::vector<std::string> hdf_filenames_;
unsigned int num_files_;
unsigned int current_file_;
hsize_t current_row_;
Blob<Dtype> data_blob_;
Blob<Dtype> label_blob_;
};
template <typename Dtype>
class HDF5OutputLayer : public Layer<Dtype> {
public:
explicit HDF5OutputLayer(const LayerParameter& param);
virtual ~HDF5OutputLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {}
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HDF5_OUTPUT;
}
// TODO: no limit on the number of blobs
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 0; }
inline std::string file_name() const { return file_name_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void SaveBlobs();
std::string file_name_;
hid_t file_id_;
Blob<Dtype> data_blob_;
Blob<Dtype> label_blob_;
};
// This function is used to create a pthread that prefetches the data.
template <typename Dtype>
void* ImageDataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class ImageDataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* ImageDataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit ImageDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~ImageDataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_IMAGE_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void ShuffleImages();
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
vector<std::pair<std::string, vector<int> > > lines_;
int lines_id_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
Caffe::Phase phase_;
bool output_labels_;
};
/* MemoryDataLayer
*/
template <typename Dtype>
class MemoryDataLayer : public Layer<Dtype> {
public:
explicit MemoryDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_MEMORY_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
// Reset should accept const pointers, but can't, because the memory
// will be given to Blob, which is mutable
void Reset(Dtype* data, Dtype* label, int n);
int datum_channels() { return datum_channels_; }
int datum_height() { return datum_height_; }
int datum_width() { return datum_width_; }
int batch_size() { return batch_size_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
Dtype* data_;
Dtype* labels_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
int batch_size_;
int n_;
int pos_;
};
// This function is used to create a pthread that prefetches the window data.
template <typename Dtype>
void* WindowDataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class WindowDataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* WindowDataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit WindowDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~WindowDataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_WINDOW_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
vector<std::pair<std::string, vector<int> > > image_database_;
enum WindowField { IMAGE_INDEX, LABEL, OVERLAP, X1, Y1, X2, Y2, NUM };
vector<vector<float> > fg_windows_;
vector<vector<float> > bg_windows_;
};
} // namespace caffe
#endif // CAFFE_DATA_LAYERS_HPP_
| 33.410765 | 77 | 0.731643 | xiaomi646 |
6da09a04593bd6e18afd7ad1b3f79b8d5d0e9e27 | 3,261 | hpp | C++ | xlib/include/Host/Classes/impl/Collection.i.hpp | divyegala/hornet | 7c4cbc3b9a56ce208e35d7733aeeda18d0c9ff93 | [
"BSD-3-Clause"
] | 61 | 2017-10-09T01:26:35.000Z | 2022-03-18T12:39:18.000Z | xlib/include/Host/Classes/impl/Collection.i.hpp | divyegala/hornet | 7c4cbc3b9a56ce208e35d7733aeeda18d0c9ff93 | [
"BSD-3-Clause"
] | 37 | 2017-10-18T14:01:57.000Z | 2022-02-18T18:23:30.000Z | xlib/include/Host/Classes/impl/Collection.i.hpp | divyegala/hornet | 7c4cbc3b9a56ce208e35d7733aeeda18d0c9ff93 | [
"BSD-3-Clause"
] | 32 | 2017-10-11T15:33:01.000Z | 2020-12-11T17:41:19.000Z | /*------------------------------------------------------------------------------
Copyright © 2016 by Nicola Bombieri
XLib is provided under the terms of The MIT License (MIT):
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.
------------------------------------------------------------------------------*/
/**
* @author Federico Busato
* Univerity of Verona, Dept. of Computer Science
* federico.busato@univr.it
*/
/**
* @version 1.3
*/
#include "Base/Host/Basic.hpp"
#include <cassert>
#include <stdexcept>
namespace xlib {
template<typename T>
Collection<T>::Collection(size_t max_size) noexcept : _max_size(max_size) {
try {
_array = new T[max_size];
} catch (const std::bad_alloc&) {
ERROR_LINE
}
}
template<typename T>
Collection<T>::~Collection() noexcept {
delete[] _array;
}
template<typename T>
inline const T Collection<T>::operator[](size_t index) const noexcept {
assert(index < _size && "Collection::operator[]");
return _array[index];
}
template<typename T>
inline void Collection<T>::operator+=(const Collection& collection) noexcept {
assert(_size + collection._size < _max_size && "Collection::operator+=");
for (const auto& it : collection)
_array[_size++] = it;
}
template<typename T>
inline void Collection<T>::operator+=(const T& element) noexcept {
assert(_size < _max_size && "Collection::operator+=");
_array[_size++] = element;
}
template<typename T>
inline Collection<T>& Collection<T>::operator=(const Collection& collection)
noexcept {
assert(collection._size < _max_size && "Collection::operator=");
for (size_t i = 0; i < collection._size; i++)
_array[i] = collection._array[i];
_size = collection._size;
return *this;
}
template<typename T>
inline size_t Collection<T>::size() const noexcept {
return _size;
}
template<typename T>
inline ArrayIterator<T> Collection<T>::begin() const noexcept {
return ArrayIterator<T>(_array);
}
template<typename T>
inline ArrayIterator<T> Collection<T>::end() const noexcept {
return ArrayIterator<T>(_array + _size);
}
template<typename T>
inline void Collection<T>::reverse() noexcept {
std::reverse(_array, _array + _size);
}
} // namespace xlib
| 32.287129 | 80 | 0.681079 | divyegala |
6da5cde680606e912901fc8ffe79da6cba576d61 | 12,225 | cpp | C++ | 3rdparty/opencl-miner/ufoStratum.cpp | XziimP/ufochain | d6cda5b6df82c7ef662a780dc8b918c1ca7f9d4c | [
"MIT"
] | 38 | 2020-02-16T02:06:50.000Z | 2021-07-14T04:49:10.000Z | 3rdparty/opencl-miner/ufoStratum.cpp | XziimP/ufochain | d6cda5b6df82c7ef662a780dc8b918c1ca7f9d4c | [
"MIT"
] | 21 | 2020-03-02T08:33:12.000Z | 2020-05-26T04:07:25.000Z | 3rdparty/opencl-miner/ufoStratum.cpp | XziimP/ufochain | d6cda5b6df82c7ef662a780dc8b918c1ca7f9d4c | [
"MIT"
] | 12 | 2020-01-16T09:32:53.000Z | 2021-04-16T15:54:18.000Z | // UFO OpenCL Miner
// Stratum interface class
// Copyright 2018 The Ufo Team
// Copyright 2018 Wilke Trei
#include "ufoStratum.h"
#include "crypto/sha256.c"
namespace ufoMiner {
// This one ensures that the calling thread can work on immediately
void ufoStratum::queueDataSend(string data) {
io_service.post(boost::bind(&ufoStratum::syncSend,this, data));
}
// Function to add a string into the socket write queue
void ufoStratum::syncSend(string data) {
writeRequests.push_back(data);
activateWrite();
}
// Got granted we can write to our connection, lets do so
void ufoStratum::activateWrite() {
if (!activeWrite && writeRequests.size() > 0) {
activeWrite = true;
string json = writeRequests.front();
writeRequests.pop_front();
std::ostream os(&requestBuffer);
os << json;
if (debug) cout << "Write to connection: " << json;
boost::asio::async_write(*socket, requestBuffer, boost::bind(&ufoStratum::writeHandler,this, boost::asio::placeholders::error));
}
}
// Once written check if there is more to write
void ufoStratum::writeHandler(const boost::system::error_code& err) {
activeWrite = false;
activateWrite();
if (err) {
if (debug) cout << "Write to stratum failed: " << err.message() << endl;
}
}
// Called by main() function, starts the stratum client thread
void ufoStratum::startWorking(){
std::thread (&ufoStratum::connect,this).detach();
}
// This function will be used to establish a connection to the API server
void ufoStratum::connect() {
while (true) {
tcp::resolver::query q(host, port);
cout << "Connecting to " << host << ":" << port << endl;
try {
tcp::resolver::iterator endpoint_iterator = res.resolve(q);
tcp::endpoint endpoint = *endpoint_iterator;
socket.reset(new boost::asio::ssl::stream<tcp::socket>(io_service, context));
socket->set_verify_mode(boost::asio::ssl::verify_none);
socket->set_verify_callback(boost::bind(&ufoStratum::verifyCertificate, this, _1, _2));
socket->lowest_layer().async_connect(endpoint,
boost::bind(&ufoStratum::handleConnect, this, boost::asio::placeholders::error, ++endpoint_iterator));
io_service.run();
} catch (std::exception const& _e) {
cout << "Stratum error: " << _e.what() << endl;
}
workId = -1;
io_service.reset();
socket->lowest_layer().close();
cout << "Lost connection to API server" << endl;
cout << "Trying to connect in 5 seconds"<< endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
// Once the physical connection is there start a TLS handshake
void ufoStratum::handleConnect(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) {
if (!err) {
cout << "Connected to node. Starting TLS handshake." << endl;
// The connection was successful. Do the TLS handshake
socket->async_handshake(boost::asio::ssl::stream_base::client,boost::bind(&ufoStratum::handleHandshake, this, boost::asio::placeholders::error));
} else if (err != boost::asio::error::operation_aborted) {
if (endpoint_iterator != tcp::resolver::iterator()) {
// The endpoint did not work, but we can try the next one
tcp::endpoint endpoint = *endpoint_iterator;
socket->lowest_layer().async_connect(endpoint,
boost::bind(&ufoStratum::handleConnect, this, boost::asio::placeholders::error, ++endpoint_iterator));
}
}
}
// Dummy function: we will not verify if the endpoint is verified at the moment,
// still there is a TLS handshake, so connection is encrypted
bool ufoStratum::verifyCertificate(bool preverified, boost::asio::ssl::verify_context& ctx){
return true;
}
void ufoStratum::handleHandshake(const boost::system::error_code& error) {
if (!error) {
// Listen to receive stratum input
boost::asio::async_read_until(*socket, responseBuffer, "\n",
boost::bind(&ufoStratum::readStratum, this, boost::asio::placeholders::error));
cout << "TLS Handshake sucess" << endl;
// The connection was successful. Send the login request
std::stringstream json;
json << "{\"method\":\"login\", \"api_key\":\"" << apiKey << "\", \"id\":\"login\",\"jsonrpc\":\"2.0\"} \n";
queueDataSend(json.str());
} else {
cout << "Handshake failed: " << error.message() << "\n";
}
}
// Simple helper function that casts a hex string into byte array
vector<uint8_t> parseHex (string input) {
vector<uint8_t> result ;
result.reserve(input.length() / 2);
for (uint32_t i = 0; i < input.length(); i += 2){
uint32_t byte;
std::istringstream hex_byte(input.substr(i, 2));
hex_byte >> std::hex >> byte;
result.push_back(static_cast<unsigned char>(byte));
}
return result;
}
// Main stratum read function, will be called on every received data
void ufoStratum::readStratum(const boost::system::error_code& err) {
if (!err) {
// We just read something without problem.
std::istream is(&responseBuffer);
std::string response;
getline(is, response);
if (debug) cout << "Incoming Stratum: " << response << endl;
// Parse the input to a property tree
pt::iptree jsonTree;
try {
istringstream jsonStream(response);
pt::read_json(jsonStream,jsonTree);
// This should be for any valid stratum
if (jsonTree.count("method") > 0) {
string method = jsonTree.get<string>("method");
// Result to a node request
if (method.compare("result") == 0) {
// A login reply
if (jsonTree.get<string>("id").compare("login") == 0) {
int32_t code = jsonTree.get<int32_t>("code");
if (code >= 0) {
cout << "Login at node accepted \n" << endl;
} else {
cout << "Error: Login at node not accepted. Closing miner." << endl;
exit(0);
}
} else { // A share reply
int32_t code = jsonTree.get<int32_t>("code");
if (code == 1) {
cout << "Solution for work id " << jsonTree.get<string>("id") << "accepted" << endl;
} else {
cout << "Warning: Solution for work id " << jsonTree.get<string>("id") << "not accepted" << endl;
}
}
}
// A new job decription;
if (method.compare("job") == 0) {
updateMutex.lock();
// Get new work load
string work = jsonTree.get<string>("input");
serverWork = parseHex(work);
// Get jobId of new job
workId = jsonTree.get<uint64_t>("id");
// Get the target difficulty
uint32_t stratDiff = jsonTree.get<uint32_t>("difficulty");
powDiff = ufo::Difficulty(stratDiff);
updateMutex.unlock();
cout << "New work received with id " << workId << " at difficulty " << powDiff.ToFloat() << endl;
}
// Cancel a running job
if (method.compare("cancel") == 0) {
updateMutex.lock();
// Get jobId of canceled job
uint64_t id = jsonTree.get<uint64_t>("id");
// Set it to an unlikely value;
if (id == (uint64_t)workId) workId = -1;
updateMutex.unlock();
}
}
} catch(const pt::ptree_error &e) {
cout << "Json parse error: " << e.what() << endl;
}
// Prepare to continue reading
boost::asio::async_read_until(*socket, responseBuffer, "\n",
boost::bind(&ufoStratum::readStratum, this, boost::asio::placeholders::error));
}
}
// Checking if we have valid work, else the GPUs will pause
bool ufoStratum::hasWork() {
return (workId >= 0);
}
// function the clHost class uses to fetch new work
void ufoStratum::getWork(int64_t* workOut, uint64_t* nonceOut, uint8_t* dataOut, uint32_t*) {
*workOut = workId;
// nonce is atomic, so every time we call this will get a nonce increased by one
*nonceOut = nonce.fetch_add(1);
memcpy(dataOut, serverWork.data(), 32);
}
void CompressArray(const unsigned char* in, size_t in_len,
unsigned char* out, size_t out_len,
size_t bit_len, size_t byte_pad) {
assert(bit_len >= 8);
assert(8*sizeof(uint32_t) >= bit_len);
size_t in_width { (bit_len+7)/8 + byte_pad };
assert(out_len == (bit_len*in_len/in_width + 7)/8);
uint32_t bit_len_mask { ((uint32_t)1 << bit_len) - 1 };
// The acc_bits least-significant bits of acc_value represent a bit sequence
// in big-endian order.
size_t acc_bits = 0;
uint32_t acc_value = 0;
size_t j = 0;
for (size_t i = 0; i < out_len; i++) {
// When we have fewer than 8 bits left in the accumulator, read the next
// input element.
if (acc_bits < 8) {
if (j < in_len) {
acc_value = acc_value << bit_len;
for (size_t x = byte_pad; x < in_width; x++) {
acc_value = acc_value | (
(
// Apply bit_len_mask across byte boundaries
in[j + x] & ((bit_len_mask >> (8 * (in_width - x - 1))) & 0xFF)
) << (8 * (in_width - x - 1))); // Big-endian
}
j += in_width;
acc_bits += bit_len;
}
else {
acc_value <<= 8 - acc_bits;
acc_bits += 8 - acc_bits;;
}
}
acc_bits -= 8;
out[i] = (acc_value >> acc_bits) & 0xFF;
}
}
#ifdef WIN32
inline uint32_t htobe32(uint32_t x)
{
return (((x & 0xff000000U) >> 24) | ((x & 0x00ff0000U) >> 8) |
((x & 0x0000ff00U) << 8) | ((x & 0x000000ffU) << 24));
}
#endif // WIN32
// Big-endian so that lexicographic array comparison is equivalent to integer comparison
void EhIndexToArray(const uint32_t i, unsigned char* array) {
static_assert(sizeof(uint32_t) == 4, "");
uint32_t bei = htobe32(i);
memcpy(array, &bei, sizeof(uint32_t));
}
// Helper function that compresses the solution from 32 unsigned integers (128 bytes) to 104 bytes
std::vector<unsigned char> GetMinimalFromIndices(std::vector<uint32_t> indices, size_t cBitLen) {
assert(((cBitLen+1)+7)/8 <= sizeof(uint32_t));
size_t lenIndices { indices.size()*sizeof(uint32_t) };
size_t minLen { (cBitLen+1)*lenIndices/(8*sizeof(uint32_t)) };
size_t bytePad { sizeof(uint32_t) - ((cBitLen+1)+7)/8 };
std::vector<unsigned char> array(lenIndices);
for (size_t i = 0; i < indices.size(); i++) {
EhIndexToArray(indices[i], array.data()+(i*sizeof(uint32_t)));
}
std::vector<unsigned char> ret(minLen);
CompressArray(array.data(), lenIndices, ret.data(), minLen, cBitLen+1, bytePad);
return ret;
}
void ufoStratum::testAndSubmit(int64_t wId, uint64_t nonceIn, vector<uint32_t> indices) {
// First check if the work fits the current work
if (wId == workId) {
// get the compressed representation of the solution and check against target
vector<uint8_t> compressed;
compressed = GetMinimalFromIndices(indices,25);
ufo::uintBig_t<32> hv;
Sha256_Onestep(compressed.data(), compressed.size(), hv.m_pData);
if (powDiff.IsTargetReached(hv)) {
// The solutions target is low enough, lets submit it
vector<uint8_t> nonceBytes;
nonceBytes.assign(8,0);
*((uint64_t*) nonceBytes.data()) = nonceIn;
stringstream nonceHex;
for (int c=0; c<nonceBytes.size(); c++) {
nonceHex << std::setfill('0') << std::setw(2) << std::hex << (unsigned) nonceBytes[c];
}
stringstream solutionHex;
for (int c=0; c<compressed.size(); c++) {
solutionHex << std::setfill('0') << std::setw(2) << std::hex << (unsigned) compressed[c];
}
// Line the stratum msg up
std::stringstream json;
json << "{\"method\" : \"solution\", \"id\": \"" << wId << "\", \"nonce\": \"" << nonceHex.str()
<< "\", \"output\": \"" << solutionHex.str() << "\", \"jsonrpc\":\"2.0\" } \n";
queueDataSend(json.str());
cout << "Submitting solution to job " << wId << " with nonce " << nonceHex.str() << endl;
}
}
}
// Will be called by clHost class for check & submit
void ufoStratum::handleSolution(int64_t &workIdVar, uint64_t &nonceVar, vector<uint32_t> &indices, uint32_t) {
std::thread (&ufoStratum::testAndSubmit,this, workIdVar, nonceVar,indices).detach();
}
ufoStratum::ufoStratum(string hostIn, string portIn, string apiKeyIn, bool debugIn) : res(io_service), context(boost::asio::ssl::context::sslv23) {
host = hostIn;
port = portIn;
apiKey = apiKeyIn;
debug = debugIn;
// Assign the work field and nonce
serverWork.assign(32,(uint8_t) 0);
random_device rd;
default_random_engine generator(rd());
uniform_int_distribution<uint64_t> distribution(0,0xFFFFFFFFFFFFFFFF);
// We pick a random start nonce
nonce = distribution(generator);
// No work in the beginning
workId = -1;
}
} // End namespace ufoMiner
| 30.5625 | 148 | 0.657505 | XziimP |
6da8e81c069b82cab547e818fb4212f135ae64d6 | 436 | cpp | C++ | strings/redundantBraces.cpp | archit-1997/InterviewB | 6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7 | [
"MIT"
] | 1 | 2021-01-27T16:37:38.000Z | 2021-01-27T16:37:38.000Z | strings/redundantBraces.cpp | archit-1997/InterviewBit | 6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7 | [
"MIT"
] | null | null | null | strings/redundantBraces.cpp | archit-1997/InterviewBit | 6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7 | [
"MIT"
] | null | null | null | int Solution::braces(string A) {
stack<char> s;
auto size = A.length();
int i = 0;
while (i < size) {
char c = A[i];
if (c == '(' || c == '+' || c == '*' || c == '-' || c == '/') {
s.push(c);
} else if (c == ')') {
if (s.top() == '(') {
return 1;
} else {
while (!s.empty() && s.top() != '(') {
s.pop();
}
s.pop();
}
}
++i;
}
return 0;
}
| 18.956522 | 67 | 0.318807 | archit-1997 |
6daf5f6f42a2749c5d7f78cc9186486563fb7282 | 4,356 | cpp | C++ | src/managers/keys.cpp | BerilBBJ/beryldb | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 206 | 2021-04-27T21:44:24.000Z | 2022-02-23T12:01:20.000Z | src/managers/keys.cpp | BerilBBJ/beryldb | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 10 | 2021-05-04T19:46:59.000Z | 2021-10-01T23:43:07.000Z | src/managers/keys.cpp | berylcorp/beryl | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 7 | 2021-04-28T16:17:56.000Z | 2021-12-10T01:14:42.000Z | /*
* BerylDB - A lightweight database.
* http://www.beryldb.com
*
* Copyright (C) 2021 - Carlos F. Ferry <cferry@beryldb.com>
*
* This file is part of BerylDB. BerylDB is free software: you can
* redistribute it and/or modify it under the terms of the BSD License
* version 3.
*
* More information about our licensing can be found at https://docs.beryl.dev
*/
#include "beryl.h"
#include "helpers.h"
#include "extras.h"
#include "managers/keys.h"
void KeyHelper::HeshVal(User* user, std::shared_ptr<QueryBase> query, const std::string& key, const std::string& val1, const std::string& val2)
{
Helpers::make_geo_query(user, query, key);
query->value = val1;
query->hesh = val2;
Kernel->Store->Push(query);
}
void KeyHelper::AddPub(User* user, std::shared_ptr<QueryBase> query, const std::string& chan, const std::string& key, const std::string& val1, const std::string& val2)
{
Helpers::make_geo_query(user, query, key);
query->newkey = chan;
query->value = val1;
query->hesh = val2;
Kernel->Store->Push(query);
}
void KeyHelper::Simple(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, const std::string& value, bool do_stripe)
{
Helpers::make_query(user, query, entry);
if (do_stripe)
{
query->value = stripe(value);
}
else
{
query->value = value;
}
Kernel->Store->Push(query);
}
void KeyHelper::Quick(User* user, std::shared_ptr<QueryBase> query)
{
Helpers::make_query(user, query);
Kernel->Store->Push(query);
}
void KeyHelper::SimpleType(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, QUERY_TYPE type)
{
Helpers::make_query(user, query, entry);
query->type = type;
Kernel->Store->Push(query);
}
void KeyHelper::RetroFunc(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, STR_FUNCTION func, bool allow)
{
Helpers::make_query(user, query, entry, allow);
query->function = func;
Kernel->Store->Push(query);
}
void KeyHelper::Retro(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, bool allow)
{
Helpers::make_query(user, query, entry, allow);
Kernel->Store->Push(query);
}
void KeyHelper::HeshLimits(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, const std::string& value, signed int offset, signed int limit, bool allow)
{
Helpers::make_query(user, query, entry, allow);
query->value = stripe(value);
query->offset = offset;
query->limit = limit;
Kernel->Store->Push(query);
}
void KeyHelper::RetroLimits(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, signed int offset, signed int limit, bool allow)
{
Helpers::make_query(user, query, entry, allow);
query->offset = offset;
query->limit = limit;
Kernel->Store->Push(query);
}
void KeyHelper::SimpleRetro(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, const std::string& value)
{
Helpers::make_query(user, query, entry);
query->value = value;
Kernel->Store->Push(query);
}
void KeyHelper::SimpleHesh(User* user, std::shared_ptr<QueryBase> query, const std::string& kmap, const std::string& entry, const std::string& value)
{
Helpers::make_map(user, query, kmap, entry);
query->value = stripe(value);
Kernel->Store->Push(query);
}
void KeyHelper::HeshRetro(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, const std::string& value)
{
Helpers::make_map(user, query, entry, value);
Kernel->Store->Push(query);
}
void KeyHelper::IDRetro(User* user, std::shared_ptr<QueryBase> query, const std::string& entry, const std::string& seconds)
{
Helpers::make_query(user, query, entry);
query->id = Kernel->Now() + convto_num<unsigned int>(seconds);
Kernel->Store->Push(query);
}
void KeyHelper::Operation(User* user, const std::string& key, OP_TYPE type, const std::string& oper)
{
std::shared_ptr<op_query> query = std::make_shared<op_query>();
Helpers::make_query(user, query, key);
query->value = oper;
query->operation = type;
Kernel->Store->Push(query);
}
| 32.029412 | 173 | 0.652893 | BerilBBJ |
6db098004a6bfc479175022e182c8676d3d42ba8 | 2,662 | hpp | C++ | ScrPlayer/Decoder.hpp | darrennong/scrcpy | 1f205369d8af6133f6787c7c9314f8885c353c6f | [
"Apache-2.0"
] | null | null | null | ScrPlayer/Decoder.hpp | darrennong/scrcpy | 1f205369d8af6133f6787c7c9314f8885c353c6f | [
"Apache-2.0"
] | null | null | null | ScrPlayer/Decoder.hpp | darrennong/scrcpy | 1f205369d8af6133f6787c7c9314f8885c353c6f | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "ScrPlayer.h"
#include <libavformat/avformat.h>
#include <libavutil/time.h>
#include "compat.h"
#include "events.h"
#include "videoBuffer.hpp"
#include "util/buffer_util.h"
#include "util/log.h"
#define EVENT_NEW_SESSION SDL_USEREVENT
#define EVENT_NEW_FRAME (SDL_USEREVENT + 1)
#define EVENT_STREAM_STOPPED (SDL_USEREVENT + 2)
class Decoder
{
private:
VideoBuffer* videoBuffer;
AVCodecContext* codec_ctx;
public:
// set the decoded frame as ready for rendering, and notify
void push_frame() {
if (videoBuffer->offer_decoded_frame()) {
// the previous EVENT_NEW_FRAME will consume this frame
return;
}
SDL_Event new_frame_event;
new_frame_event.type = EVENT_NEW_FRAME;
SDL_PushEvent(&new_frame_event);
}
void init(VideoBuffer* vb) {
videoBuffer = vb;
}
bool open(const AVCodec* codec) {
codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
LOGC("Could not allocate decoder context");
return false;
}
if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
LOGE("Could not open codec");
avcodec_free_context(&codec_ctx);
return false;
}
return true;
}
void close() {
avcodec_close(codec_ctx);
avcodec_free_context(&codec_ctx);
}
bool push(const AVPacket* packet) {
// the new decoding/encoding API has been introduced by:
// <http://git.videolan.org/?p=ffmpeg.git;a=commitdiff;h=7fc329e2dd6226dfecaa4a1d7adf353bf2773726>
#ifdef SCRCPY_LAVF_HAS_NEW_ENCODING_DECODING_API
int ret;
if ((ret = avcodec_send_packet(codec_ctx, packet)) < 0) {
LOGE("Could not send video packet: %d", ret);
return false;
}
ret = avcodec_receive_frame(codec_ctx,videoBuffer->decoding_frame);
if (!ret) {
// a frame was received
push_frame();
}
else if (ret != AVERROR(EAGAIN)) {
LOGE("Could not receive video frame: %d", ret);
return false;
}
#else
int got_picture;
int len = avcodec_decode_video2(codec_ctx,videoBuffer->decoding_frame,&got_picture,
packet);
if (len < 0) {
LOGE("Could not decode video packet: %d", len);
return false;
}
if (got_picture) {
push_frame();
}
#endif
return true;
}
void interrupt() {
videoBuffer->interrupt();
}
};
| 28.623656 | 107 | 0.581142 | darrennong |
6db36bf248c4e9af168fdd1ffd4894219327bc1c | 1,303 | cpp | C++ | equalize.cpp | mtctr/ufrn-pdi | 55c2de9d6ad574d50d05b864b85acf253c4048cf | [
"MIT"
] | null | null | null | equalize.cpp | mtctr/ufrn-pdi | 55c2de9d6ad574d50d05b864b85acf253c4048cf | [
"MIT"
] | null | null | null | equalize.cpp | mtctr/ufrn-pdi | 55c2de9d6ad574d50d05b864b85acf253c4048cf | [
"MIT"
] | null | null | null | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv){
Mat image, equalized;
int width, height;
vector<Mat> planes;
Mat hist;
int nbins = 256;
float range[] = {0, 256};
const float *histrange = { range };
bool uniform = true;
bool acummulate = false;
image= imread("img/gabi.jpg",CV_LOAD_IMAGE_GRAYSCALE);
if(!image.data){
cout << "imagem não encontrada" << endl;
} else{
//resize(image, image, Size(720,480));
}
width = image.cols;
height = image.rows;
cout << "largura = " << width << endl;
cout << "altura = " << height << endl;
imshow("original", image);
calcHist(&image, 1, 0, Mat(), hist, 1, &nbins, &histrange, uniform, acummulate);
int histw = nbins, histh = nbins/2;
Mat histImg(histh, histw, CV_8UC3, Scalar(0));
normalize(hist, hist, 0, histImg.rows, NORM_MINMAX, -1, Mat());
histImg.setTo(Scalar(0));
for(int i=0; i<nbins; i++){
line(histImg,
Point(i, histh),
Point(i, histh-cvRound(hist.at<float>(i))),
Scalar(0), 1, 8, 0);
}
//histImg.copyTo(image(Rect(0, 0 ,nbins, histh)));
equalizeHist(image, equalized);
imwrite("img/eq.jpg", equalized);
imshow("equalized", equalized);
waitKey();
return 0;
}
| 22.465517 | 82 | 0.61627 | mtctr |
6db690ee60364436c175690f01d1ec4ccfb8d611 | 61,738 | cpp | C++ | Source/CQOR/math.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/CQOR/math.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/CQOR/math.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //math.cpp
// Copyright Querysoft Limited 2013
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Generic math implementation
#include "CQOR/CQORPolicy.h"
#include <math.h>
#include <errno.h>
#include "SystemQOR.h"
#include QOR_SYS_PLATFORMHEADER(math.h)
#include "CodeQOR/Tracing/FunctionContextBase.h"
#include "CodeQOR/ErrorSystem/Error.h"
#include "CQOR.h"
//--------------------------------------------------------------------------------
namespace
{
nsPlatform::Cmath _math;
}//anonymous
__QCMP_STARTLINKAGE_C
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int fpclassify( long double x )
{
__QCS_FCONTEXT( "fpclassify" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.fpclassify( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isfinite( long double x )
{
__QCS_FCONTEXT( "isfinite" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isfinite( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isinf( long double x )
{
__QCS_FCONTEXT( "isinf" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isinf( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isnan( long double x )
{
__QCS_FCONTEXT( "isnan" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isnan( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isnormal( long double x )
{
__QCS_FCONTEXT( "isnormal" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isnormal( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int signbit( long double x )
{
__QCS_FCONTEXT( "signbit" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.signbit( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
#pragma function( acos )
/*
__QOR_INTERFACE( __CQOR ) double acos( double x )
{
__QCS_FCONTEXT( "acos" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.acos( x );
}__QCS_ENDPROTECT
return dResult;
}
*/
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float acosf( float x )
{
__QCS_FCONTEXT( "acosf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.acosf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double acosl( long double x )
{
__QCS_FCONTEXT( "acosl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.acosl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( asin )
/*__QOR_INTERFACE( __CQOR )*/ double asin( double x )
{
__QCS_FCONTEXT( "asin" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.asin( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float asinf( float x )
{
__QCS_FCONTEXT( "asinf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.asinf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double asinl( long double x )
{
__QCS_FCONTEXT( "asinl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.asinl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( atan )
__QOR_INTERFACE( __CQOR ) double atan( double x )
{
__QCS_FCONTEXT( "atan" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.atan( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float atanf( float x )
{
__QCS_FCONTEXT( "atanf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.atanf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double atanl( long double x )
{
__QCS_FCONTEXT( "atanl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.atanl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( atan2 )
__QOR_INTERFACE( __CQOR ) double atan2( double y, double x )
{
__QCS_FCONTEXT( "atan2" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.atan2( y, x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float atan2f( float y, float x )
{
__QCS_FCONTEXT( "atan2f" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.atan2f( y, x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double atan2l( long double y, long double x )
{
__QCS_FCONTEXT( "atan2l" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.atan2l( y, x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( cos )
/*__QOR_INTERFACE( __CQOR )*/ double cos( double x )
{
__QCS_FCONTEXT( "cos" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.cos( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float cosf( float x )
{
__QCS_FCONTEXT( "cosf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.cosf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double cosl( long double x )
{
__QCS_FCONTEXT( "cosl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.cosl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( sin )
/*__QOR_INTERFACE( __CQOR )*/ double sin( double x )
{
__QCS_FCONTEXT( "cosl" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.sin( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float sinf( float x )
{
__QCS_FCONTEXT( "sinf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.sinf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double sinl( long double x )
{
__QCS_FCONTEXT( "sinl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.sinl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( tan )
/*__QOR_INTERFACE( __CQOR )*/ double tan( double x )
{
__QCS_FCONTEXT( "tan" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.tan( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float tanf( float x )
{
__QCS_FCONTEXT( "tanf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.tanf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double tanl( long double x )
{
__QCS_FCONTEXT( "tanl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.tanl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double acosh( double x )
{
__QCS_FCONTEXT( "acosh" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.acosh( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float acoshf( float x )
{
__QCS_FCONTEXT( "acoshf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.acoshf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double acoshl( long double x )
{
__QCS_FCONTEXT( "acoshl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.acoshl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double asinh( double x )
{
__QCS_FCONTEXT( "asinh" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.asinh( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float asinhf( float x )
{
__QCS_FCONTEXT( "asinhf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.asinhf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double asinhl( long double x )
{
__QCS_FCONTEXT( "asinhl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.asinhl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double atanh( double x )
{
__QCS_FCONTEXT( "atanh" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.atanh( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float atanhf( float x )
{
__QCS_FCONTEXT( "atanhf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.atanhf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double atanhl( long double x )
{
__QCS_FCONTEXT( "atanhl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.atanhl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( cosh )
/*__QOR_INTERFACE( __CQOR )*/ double cosh( double x )
{
__QCS_FCONTEXT( "cosh" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.cosh( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float coshf( float x )
{
__QCS_FCONTEXT( "coshf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.coshf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double coshl( long double x )
{
__QCS_FCONTEXT( "coshl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.coshl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( sinh )
/*__QOR_INTERFACE( __CQOR )*/ double sinh( double x )
{
__QCS_FCONTEXT( "sinh" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.sinh( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float sinhf( float x )
{
__QCS_FCONTEXT( "sinhf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.sinhf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double sinhl( long double x )
{
__QCS_FCONTEXT( "sinhl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.sinhl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( tanh )
/*__QOR_INTERFACE( __CQOR )*/ double tanh( double x )
{
__QCS_FCONTEXT( "tanh" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.tanh( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float tanhf( float x )
{
__QCS_FCONTEXT( "tanhf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.tanhf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double tanhl( long double x )
{
__QCS_FCONTEXT( "tanhl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.tanhl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( exp )
/*__QOR_INTERFACE( __CQOR )*/ double exp( double x )
{
__QCS_FCONTEXT( "exp" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.exp( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float expf( float x )
{
__QCS_FCONTEXT( "expf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.expf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double expl( long double x )
{
__QCS_FCONTEXT( "expl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.expl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double exp2( double x )
{
__QCS_FCONTEXT( "exp2" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.exp2( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float exp2f( float x )
{
__QCS_FCONTEXT( "exp2f" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.exp2f( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double exp2l( long double x )
{
__QCS_FCONTEXT( "exp2l" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.exp2l( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double expm1( double x )
{
__QCS_FCONTEXT( "expm1" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.expm1( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float expm1f( float x )
{
__QCS_FCONTEXT( "expm1f" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.expm1f( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double expm1l( long double x )
{
__QCS_FCONTEXT( "expm1l" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.expm1l( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double frexp( double value, int *exp )
{
__QCS_FCONTEXT( "frexp" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.frexp( value, exp );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float frexpf( float value, int* exp )
{
__QCS_FCONTEXT( "frexpf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.frexpf( value, exp );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double frexpl( long double value, int* exp )
{
__QCS_FCONTEXT( "frexpl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.frexpl( value, exp );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int ilogb( double x )
{
__QCS_FCONTEXT( "ilogb" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.ilogb( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int ilogbf( float x )
{
__QCS_FCONTEXT( "ilogbf" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.ilogbf( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int ilogbl( long double x )
{
__QCS_FCONTEXT( "ilogbl" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.ilogbl( x );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double ldexp( double x, int exp )
{
__QCS_FCONTEXT( "ldexp" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.ldexp( x, exp );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float ldexpf( float x, int exp )
{
__QCS_FCONTEXT( "ldexpf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.ldexpf( x, exp );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double ldexpl( long double x, int exp )
{
__QCS_FCONTEXT( "ldexpl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.ldexpl( x, exp );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( log )
/*__QOR_INTERFACE( __CQOR )*/ double log( double x )
{
__QCS_FCONTEXT( "log" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.log( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float logf( float x )
{
__QCS_FCONTEXT( "logf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.logf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double logl(long double x)
{
__QCS_FCONTEXT( "logl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.logl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( log10 )
/*__QOR_INTERFACE( __CQOR )*/ double log10( double x )
{
__QCS_FCONTEXT( "log10" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.log10( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float log10f( float x )
{
__QCS_FCONTEXT( "log10f" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.log10f( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double log10l( long double x )
{
__QCS_FCONTEXT( "log10l" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.log10l( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double log1p( double x )
{
__QCS_FCONTEXT( "log1p" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.log1p( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float log1pf( float x )
{
__QCS_FCONTEXT( "log1pf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.log1pf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double log1pl( long double x )
{
__QCS_FCONTEXT( "log1pl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.log1pl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double log2( double x )
{
__QCS_FCONTEXT( "log2" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.log2( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float log2f( float x )
{
__QCS_FCONTEXT( "log2f" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.log2f( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double log2l( long double x )
{
__QCS_FCONTEXT( "log2l" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.log2l( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double logb( double x )
{
__QCS_FCONTEXT( "logb" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.logb( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float logbf( float x )
{
__QCS_FCONTEXT( "logbf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.logbf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double logbl( long double x )
{
__QCS_FCONTEXT( "logbl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.logbl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double modf( double value, double* iptr )
{
__QCS_FCONTEXT( "modf" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.modf( value, iptr );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float modff( float value, float* iptr )
{
__QCS_FCONTEXT( "modff" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.modff( value, iptr );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double modfl( long double value, long double* iptr )
{
__QCS_FCONTEXT( "modfl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.modfl( value, iptr );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double scalbn( double x, int n )
{
__QCS_FCONTEXT( "scalbn" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.scalbn( x, n );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float scalbnf( float x, int n )
{
__QCS_FCONTEXT( "scalbnf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.scalbnf( x, n );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double scalbnl( long double x, int n )
{
__QCS_FCONTEXT( "scalbnl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.scalbnl( x, n );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double scalbln( double x, long int n )
{
__QCS_FCONTEXT( "scalbln" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.scalbln( x, n );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float scalblnf( float x, long int n )
{
__QCS_FCONTEXT( "scalblnf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.scalblnf( x, n );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double scalblnl( long double x, long int n )
{
__QCS_FCONTEXT( "scalblnl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.scalblnl( x, n );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double cbrt( double x )
{
__QCS_FCONTEXT( "cbrt" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.cbrt( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float cbrtf( float x )
{
__QCS_FCONTEXT( "cbrtf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.cbrtf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double cbrtl( long double x )
{
__QCS_FCONTEXT( "cbrtl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.cbrtl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( fabs )
/*__QOR_INTERFACE( __CQOR )*/ double fabs( double x )
{
__QCS_FCONTEXT( "fabs" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.fabs( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float fabsf( float x )
{
__QCS_FCONTEXT( "fabsf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.fabsf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double fabsl( long double x )
{
__QCS_FCONTEXT( "fabsl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.fabsl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double hypot( double x, double y )
{
__QCS_FCONTEXT( "hypot" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.hypot( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float hypotf( float x, float y )
{
__QCS_FCONTEXT( "hypotf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.hypotf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double hypotl( long double x, long double y )
{
__QCS_FCONTEXT( "hypotl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.hypotl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( pow )
/*__QOR_INTERFACE( __CQOR )*/ double pow( double x, double y )
{
__QCS_FCONTEXT( "pow" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.pow( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float powf( float x, float y )
{
__QCS_FCONTEXT( "powf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.powf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double powl( long double x, long double y )
{
__QCS_FCONTEXT( "powl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.powl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( sqrt )
/*__QOR_INTERFACE( __CQOR )*/ double sqrt( double x )
{
__QCS_FCONTEXT( "sqrt" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.sqrt( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float sqrtf( float x )
{
__QCS_FCONTEXT( "sqrtf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.sqrtf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double sqrtl( long double x )
{
__QCS_FCONTEXT( "sqrtl" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.sqrtl( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double erf( double x )
{
__QCS_FCONTEXT( "erf" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.erf( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float erff( float x )
{
__QCS_FCONTEXT( "erff" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.erff( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double erfl( long double x )
{
__QCS_FCONTEXT( "erfl" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.erfl( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double erfc( double x )
{
__QCS_FCONTEXT( "erfc" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.erfc( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float erfcf( float x )
{
__QCS_FCONTEXT( "erfcf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.erfcf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double erfcl( long double x )
{
__QCS_FCONTEXT( "erfcl" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.erfcl( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double lgamma( double x )
{
__QCS_FCONTEXT( "lgamma" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.lgamma( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float lgammaf( float x )
{
__QCS_FCONTEXT( "lgammaf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.lgammaf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double lgammal( long double x )
{
__QCS_FCONTEXT( "lgammal" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.lgammal( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double tgamma( double x )
{
__QCS_FCONTEXT( "tgamma" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.tgamma( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float tgammaf( float x )
{
__QCS_FCONTEXT( "tgammaf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.tgammaf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double tgammal( long double x )
{
__QCS_FCONTEXT( "tgammal" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.tgammal( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double ceil( double x )
{
__QCS_FCONTEXT( "ceil" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.ceil( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float ceilf( float x )
{
__QCS_FCONTEXT( "ceilf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.ceilf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double ceill( long double x )
{
__QCS_FCONTEXT( "ceill" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.ceill( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
#pragma function( floor )
/*__QOR_INTERFACE( __CQOR )*/ double floor( double x )
{
__QCS_FCONTEXT( "floor" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.floor( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float floorf( float x )
{
__QCS_FCONTEXT( "floorf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.floorf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double floorl( long double x )
{
__QCS_FCONTEXT( "floorl" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.floorl( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double nearbyint( double x )
{
__QCS_FCONTEXT( "nearbyint" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.nearbyint( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float nearbyintf( float x )
{
__QCS_FCONTEXT( "nearbyintf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.nearbyintf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double nearbyintl( long double x )
{
__QCS_FCONTEXT( "nearbyintl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.nearbyintl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double rint( double x )
{
__QCS_FCONTEXT( "rint" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.rint( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float rintf( float x )
{
__QCS_FCONTEXT( "rintf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.rintf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double rintl( long double x )
{
__QCS_FCONTEXT( "rintl" );
long double dResult = 0;
__QCS_PROTECT
{
dResult = _math.rintl( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long int lrint( double x )
{
__QCS_FCONTEXT( "lrint" );
long int lResult = 0;
__QCS_PROTECT
{
lResult = _math.lrint( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long int lrintf( float x )
{
__QCS_FCONTEXT( "lrintf" );
long int lResult = 0;
__QCS_PROTECT
{
lResult = _math.lrintf( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long int lrintl( long double x )
{
__QCS_FCONTEXT( "lrintl" );
long int lResult = 0;
__QCS_PROTECT
{
lResult = _math.lrintl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long long int llrint( double x )
{
__QCS_FCONTEXT( "llrint" );
long long int llResult = 0;
__QCS_PROTECT
{
llResult = _math.llrint( x );
}__QCS_ENDPROTECT
return llResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long long int llrintf( float x )
{
__QCS_FCONTEXT( "llrintf" );
long long int llResult = 0;
__QCS_PROTECT
{
llResult = _math.llrintf( x );
}__QCS_ENDPROTECT
return llResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long long int llrintl( long double x )
{
__QCS_FCONTEXT( "llrintl" );
long long int llResult = 0;
__QCS_PROTECT
{
llResult = _math.llrintl( x );
}__QCS_ENDPROTECT
return llResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double round( double x )
{
__QCS_FCONTEXT( "round" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.round( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float roundf( float x )
{
__QCS_FCONTEXT( "roundf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.roundf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double roundl( long double x )
{
__QCS_FCONTEXT( "roundl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.roundl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long int lround( double x )
{
__QCS_FCONTEXT( "lround" );
long int lResult = 0;
__QCS_PROTECT
{
lResult = _math.lround( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long int lroundf( float x )
{
__QCS_FCONTEXT( "lroundf" );
long int lResult = 0;
__QCS_PROTECT
{
lResult = _math.lroundf( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long int lroundl( long double x )
{
__QCS_FCONTEXT( "lroundl" );
long int lResult = 0;
__QCS_PROTECT
{
lResult = _math.lroundl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long long int llround( double x )
{
__QCS_FCONTEXT( "llround" );
long long int llResult = 0;
__QCS_PROTECT
{
llResult = _math.llround( x );
}__QCS_ENDPROTECT
return llResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long long int llroundf( float x )
{
__QCS_FCONTEXT( "llroundf" );
long long int llResult = 0;
__QCS_PROTECT
{
llResult = _math.llroundf( x );
}__QCS_ENDPROTECT
return llResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long long int llroundl( long double x )
{
__QCS_FCONTEXT( "llroundl" );
long long int llResult = 0;
__QCS_PROTECT
{
llResult = _math.llroundl( x );
}__QCS_ENDPROTECT
return llResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double trunc( double x )
{
__QCS_FCONTEXT( "trunc" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.trunc( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float truncf( float x )
{
__QCS_FCONTEXT( "truncf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.truncf( x );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double truncl( long double x )
{
__QCS_FCONTEXT( "truncl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.truncl( x );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
#pragma function( fmod )
/*__QOR_INTERFACE( __CQOR )*/ double fmod( double x, double y )
{
__QCS_FCONTEXT( "fmod" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.fmod( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float fmodf( float x, float y )
{
__QCS_FCONTEXT( "fmodf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.fmodf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double fmodl( long double x, long double y )
{
__QCS_FCONTEXT( "fmodl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.fmodl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double remainder( double x, double y )
{
__QCS_FCONTEXT( "remainder" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.remainder( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float remainderf( float x, float y )
{
__QCS_FCONTEXT( "remainderf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.remainderf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double remainderl( long double x, long double y )
{
__QCS_FCONTEXT( "remainderl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.remainderl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double remquo( double x, double y, int* quo )
{
__QCS_FCONTEXT( "remquo" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.remquo( x, y, quo );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float remquof( float x, float y, int* quo )
{
__QCS_FCONTEXT( "remquof" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.remquof( x, y, quo );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double remquol( long double x, long double y, int* quo )
{
__QCS_FCONTEXT( "remquol" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.remquol( x, y, quo );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double copysign( double x, double y )
{
__QCS_FCONTEXT( "copysign" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.copysign( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float copysignf( float x, float y )
{
__QCS_FCONTEXT( "copysignf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.copysignf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double copysignl( long double x, long double y )
{
__QCS_FCONTEXT( "copysignl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.copysignl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double nan( const char* tagp )
{
__QCS_FCONTEXT( "nan" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.nan( tagp );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float nanf( const char* tagp )
{
__QCS_FCONTEXT( "nanf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.nanf( tagp );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double nanl( const char* tagp )
{
__QCS_FCONTEXT( "nanl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.nanl( tagp );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double nextafter( double x, double y )
{
__QCS_FCONTEXT( "nextafter" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.nextafter( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float nextafterf( float x, float y )
{
__QCS_FCONTEXT( "nextafterf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.nextafterf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double nextafterl( long double x, long double y )
{
__QCS_FCONTEXT( "nextafterl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.nextafterl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double nexttoward( double x, long double y )
{
__QCS_FCONTEXT( "nexttoward" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.nexttoward( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float nexttowardf( float x, long double y )
{
__QCS_FCONTEXT( "nexttowardf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.nexttowardf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double nexttowardl( long double x, long double y )
{
__QCS_FCONTEXT( "nexttowardl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.nexttowardl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double fdim( double x, double y )
{
__QCS_FCONTEXT( "fdim" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.fdim( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float fdimf( float x, float y )
{
__QCS_FCONTEXT( "fdimf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.fdimf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double fdiml( long double x, long double y )
{
__QCS_FCONTEXT( "fdiml" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.fdiml( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double fmax( double x, double y )
{
__QCS_FCONTEXT( "fmax" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.fmax( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float fmaxf( float x, float y )
{
__QCS_FCONTEXT( "fmaxf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.fmaxf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double fmaxl( long double x, long double y )
{
__QCS_FCONTEXT( "fmaxl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.fmaxl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double fmin( double x, double y )
{
__QCS_FCONTEXT( "fmin" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.fmin( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float fminf( float x, float y )
{
__QCS_FCONTEXT( "fminf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.fminf( x, y );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double fminl( long double x, long double y )
{
__QCS_FCONTEXT( "fminl" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.fminl( x, y );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double fma( double x, double y, double z )
{
__QCS_FCONTEXT( "fma" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.fma( x, y, z );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) float fmaf( float x, float y, float z )
{
__QCS_FCONTEXT( "fmaf" );
float fResult = 0;
__QCS_PROTECT
{
fResult = _math.fmaf( x, y, z );
}__QCS_ENDPROTECT
return fResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) long double fmal( long double x, long double y, long double z )
{
__QCS_FCONTEXT( "fmal" );
long double lResult = 0;
__QCS_PROTECT
{
lResult = _math.fmal( x, y, z );
}__QCS_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isgreater( long double x, long double y )
{
__QCS_FCONTEXT( "isgreater" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isgreater( x, y );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isgreaterequal( long double x, long double y )
{
__QCS_FCONTEXT( "isgreaterequal" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isgreaterequal( x, y );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isless( long double x, long double y )
{
__QCS_FCONTEXT( "isless" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isless( x, y );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int islessequal( long double x, long double y )
{
__QCS_FCONTEXT( "islessequal" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.islessgreater( x, y );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int islessgreater( long double x, long double y )
{
__QCS_FCONTEXT( "islessgreater" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.islessgreater( x, y );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int isunordered( long double x, long double y )
{
__QCS_FCONTEXT( "isunordered" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _math.isunordered( x, y );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double j0( double x )
{
__QCS_FCONTEXT( "j0" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.j0( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double j1( double x )
{
__QCS_FCONTEXT( "j1" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.j1( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double jn( int n , double x )
{
__QCS_FCONTEXT( "jn" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.jn( n, x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double scalb( double x, double y )
{
__QCS_FCONTEXT( "scalb" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.scalb( x, y );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double y0( double x )
{
__QCS_FCONTEXT( "y0" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.y0( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double _y0( double x )
{
__QCS_FCONTEXT( "_y0" );
return y0( x );
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double y1( double x )
{
__QCS_FCONTEXT( "y1" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.y1( x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double _y1( double x )
{
__QCS_FCONTEXT( "_y1" );
return y1( x );
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double yn( int n, double x )
{
__QCS_FCONTEXT( "yn" );
double dResult = 0;
__QCS_PROTECT
{
dResult = _math.yn( n, x );
}__QCS_ENDPROTECT
return dResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) double _yn( int n, double x )
{
__QCS_FCONTEXT( "_yn" );
return yn( n, x );
}
__QCMP_ENDLINKAGE_C
| 22.450182 | 89 | 0.462632 | mfaithfull |
6db98c69314e0e13ee71fbced033b38e07882615 | 1,147 | cpp | C++ | legion/engine/physics/physx/data/physx_wrapper_container.cpp | Rythe-Interactive/Rythe-Engine.rythe-legacy | c119c494524b069a73100b12dc3d8b898347830d | [
"MIT"
] | 2 | 2022-03-08T09:46:17.000Z | 2022-03-28T08:07:05.000Z | legion/engine/physics/physx/data/physx_wrapper_container.cpp | Rythe-Interactive/Rythe-Engine.rythe-legacy | c119c494524b069a73100b12dc3d8b898347830d | [
"MIT"
] | 3 | 2022-03-02T13:49:10.000Z | 2022-03-22T11:54:06.000Z | legion/engine/physics/physx/data/physx_wrapper_container.cpp | Rythe-Interactive/Rythe-Engine.rythe-legacy | c119c494524b069a73100b12dc3d8b898347830d | [
"MIT"
] | null | null | null | #include "physx_wrapper_container.hpp"
namespace legion::physics
{
PhysxInternalWrapper& PhysxWrapperContainer::createPhysxWrapper(physics_component& unregisteredPhysXWrapper)
{
unregisteredPhysXWrapper.physicsComponentID = nextID;
m_wrapperIDSet.insert(nextID);
m_physxWrappers.emplace_back();
nextID++;
return m_physxWrappers[m_physxWrappers.size() - 1];
}
void PhysxWrapperContainer::PopAndSwapRemoveWrapper(size_type id)
{
size_type index = m_wrapperIDSet.index_of(id);
if (index != m_wrapperIDSet.npos)
{
m_wrapperIDSet.erase(id);
std::swap(m_physxWrappers[index], m_physxWrappers[m_physxWrappers.size() - 1]);
m_physxWrappers.pop_back();
}
}
pointer<PhysxInternalWrapper> PhysxWrapperContainer::findWrapperWithID(size_type id)
{
if (m_wrapperIDSet.contains(id))
{
core::pointer<PhysxInternalWrapper> wrapper{ &m_physxWrappers[m_wrapperIDSet.index_of(id)] };
return pointer< PhysxInternalWrapper>{ wrapper };
}
return { nullptr };
}
}
| 29.410256 | 112 | 0.665214 | Rythe-Interactive |
6dbae9f7c2946d9c02138867a02ad2e8d9c507d1 | 3,972 | cpp | C++ | rviz_common/src/rviz_common/viewport_mouse_event.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 5 | 2020-01-14T06:45:59.000Z | 2021-03-11T11:22:35.000Z | rviz_common/src/rviz_common/viewport_mouse_event.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 2 | 2019-02-12T21:55:08.000Z | 2019-02-20T01:01:24.000Z | rviz_common/src/rviz_common/viewport_mouse_event.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 9 | 2018-09-09T20:48:17.000Z | 2021-03-11T11:22:52.000Z | /*
* Copyright (c) 2017, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "rviz_common/viewport_mouse_event.hpp"
#include <QMouseEvent>
#include <QWheelEvent>
#include "rviz_common/render_panel.hpp"
#include "rviz_rendering/render_window.hpp"
namespace rviz_common
{
ViewportMouseEvent::ViewportMouseEvent(RenderPanel * p, QMouseEvent * e, int lx, int ly)
: panel(p),
type(e->type()),
device_pixel_ratio(static_cast<int>(panel->getRenderWindow()->devicePixelRatio())),
x(e->x() * device_pixel_ratio),
y(e->y() * device_pixel_ratio),
wheel_delta(0),
acting_button(e->button()),
buttons_down(e->buttons()),
modifiers(e->modifiers()),
last_x(lx * device_pixel_ratio),
last_y(ly * device_pixel_ratio)
{
}
ViewportMouseEvent::ViewportMouseEvent(RenderPanel * p, QWheelEvent * e, int lx, int ly)
: panel(p),
type(e->type()),
device_pixel_ratio(static_cast<int>(panel->getRenderWindow()->devicePixelRatio())),
x(e->x() * device_pixel_ratio),
y(e->y() * device_pixel_ratio),
wheel_delta(e->delta()),
acting_button(Qt::NoButton),
buttons_down(e->buttons()),
modifiers(e->modifiers()),
last_x(lx * device_pixel_ratio),
last_y(ly * device_pixel_ratio)
{
}
bool ViewportMouseEvent::left()
{
return buttons_down & Qt::LeftButton;
}
bool ViewportMouseEvent::middle()
{
return buttons_down & Qt::MidButton;
}
bool ViewportMouseEvent::right()
{
return buttons_down & Qt::RightButton;
}
bool ViewportMouseEvent::shift()
{
return modifiers & Qt::ShiftModifier;
}
bool ViewportMouseEvent::control()
{
return modifiers & Qt::ControlModifier;
}
bool ViewportMouseEvent::alt()
{
return modifiers & Qt::AltModifier;
}
bool ViewportMouseEvent::leftUp()
{
return type == QEvent::MouseButtonRelease && acting_button == Qt::LeftButton;
}
bool ViewportMouseEvent::middleUp()
{
return type == QEvent::MouseButtonRelease && acting_button == Qt::MidButton;
}
bool ViewportMouseEvent::rightUp()
{
return type == QEvent::MouseButtonRelease && acting_button == Qt::RightButton;
}
bool ViewportMouseEvent::leftDown()
{
return type == QEvent::MouseButtonPress && acting_button == Qt::LeftButton;
}
bool ViewportMouseEvent::middleDown()
{
return type == QEvent::MouseButtonPress && acting_button == Qt::MidButton;
}
bool ViewportMouseEvent::rightDown()
{
return type == QEvent::MouseButtonPress && acting_button == Qt::RightButton;
}
} // namespace rviz_common
| 30.090909 | 88 | 0.737412 | romi2002 |
6dc4a97c1fae289eba081b444e8f22d9cb96b016 | 7,923 | cpp | C++ | mailbox_base_station/src/RadioManager.cpp | mattheweshleman/mailbox-event-driven-demo | 68775613f7af22d52600b258680ba265578242b8 | [
"Unlicense"
] | 3 | 2018-02-21T18:36:48.000Z | 2020-04-04T04:51:56.000Z | mailbox_base_station/src/RadioManager.cpp | mattheweshleman/mailbox-event-driven-demo | 68775613f7af22d52600b258680ba265578242b8 | [
"Unlicense"
] | null | null | null | mailbox_base_station/src/RadioManager.cpp | mattheweshleman/mailbox-event-driven-demo | 68775613f7af22d52600b258680ba265578242b8 | [
"Unlicense"
] | null | null | null | /*
* RadioManager.cpp
*
* Created on: May 28, 2016
* Author: Matthew Eshleman
*/
#include "RadioManager.h"
#include <cstdint>
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "mbed.h"
#include "sx1276-inAir.h"
#include "myDebug.h"
#include "app_config_data_types.hpp"
#include "radio_settings.h"
#include "sensor_msg.h"
#include "core_cmFunc.h"
#include "ack_msg.h"
namespace RadioManager
{
enum class RadioEvent : char
{
ENTER_STATE, //internal use only
EXIT_STATE, //internal use only
RADIO_CREATED,
MSG_SENT_OK,
SENSOR_MSG_RXD_OK,
MSG_SEND_ERROR,
RX_TIMEOUT,
RX_ERROR
};
static void InjectEvent(RadioEvent event);
/**
* simple flat state machine defining radio manager
* behavior.
*/
class Statemachine
{
public:
Statemachine() : mCurrent(nullptr) {}
virtual ~Statemachine() {}
void Init();
void ProcessEvent(const RadioEvent event);
private:
/*
* Check this out... http://www.gotw.ca/gotw/057.htm
* For background on the below.
*/
struct Handler_;
typedef Handler_ (*Handler)(Statemachine*, const RadioEvent);
struct Handler_
{
Handler_(Handler pp) :
p(pp)
{
}
operator Handler()
{
return p;
}
Handler p;
};
static Handler_ InitRadio(Statemachine* me, const RadioEvent event);
static Handler_ Receive(Statemachine* me, const RadioEvent event);
static Handler_ SendAck(Statemachine* me, const RadioEvent event);
Handler mCurrent;
};
static constexpr uint32_t RX_TIMEOUT_ONE_SECOND = 1000000; // in us
static QueueHandle_t m_queue = nullptr;
static SX1276inAir* m_radio = nullptr;
static RadioEventHandler m_sensorMsgReceivedHandler = nullptr;
static void RadioManagerTask(void *);
static void CreateTheRadio(void);
/******************************************************
* NOTE: All "OnRadioXyz()" methods are called from
* various ISR contexts!
******************************************************/
static void OnRadioTxDone(void);
static void OnRadioRxDone(uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr);
static void OnRadioTxTimeout(void);
static void OnRadioRxTimeout(void);
static void OnRadioRxError(void);
/**
*
*/
void Init(RadioEventHandler sensorMsgRxEventHandler)
{
m_sensorMsgReceivedHandler = sensorMsgRxEventHandler;
auto rtn = xTaskCreate(RadioManagerTask, "RadioManager",
configMINIMAL_STACK_SIZE*2, nullptr, tskIDLE_PRIORITY+1, nullptr);
if (rtn != pdPASS)
{
debug_if(1, "radiomanager failed task create!\n");
}
}
/**
*
*/
void RadioManagerTask(void*)
{
debug_if(1, "Starting Radio Manager Task\n");
m_queue = xQueueCreate(5, sizeof(RadioEvent));
if (m_queue == nullptr)
{
return;
}
Statemachine statemachine;
statemachine.Init();
RadioEvent event;
while (1)
{
if (xQueueReceive(m_queue, &(event), (TickType_t ) portMAX_DELAY))
{
statemachine.ProcessEvent(event);
}
}
}
/**
*
*/
void Statemachine::Init()
{
mCurrent = InitRadio;
ProcessEvent(RadioEvent::ENTER_STATE);
}
/**
*
*/
void Statemachine::ProcessEvent(const RadioEvent event)
{
if (mCurrent != nullptr)
{
Handler new_handler = mCurrent(this, event);
if (new_handler != mCurrent)
{
mCurrent(this, RadioEvent::EXIT_STATE);
mCurrent = new_handler;
mCurrent(this, RadioEvent::ENTER_STATE);
}
}
}
/**
*
*/
Statemachine::Handler_ Statemachine::InitRadio(Statemachine* me,
const RadioEvent event)
{
switch (event)
{
case RadioEvent::ENTER_STATE:
//Create and find the SX1276inAir radio
CreateTheRadio();
InjectEvent(RadioEvent::RADIO_CREATED);
break;
case RadioEvent::RADIO_CREATED:
return Receive;
break;
default:
break;
}
return InitRadio;
}
/**
*
*/
Statemachine::Handler_ Statemachine::Receive(Statemachine* me,
const RadioEvent event)
{
switch (event)
{
case RadioEvent::RX_ERROR:
case RadioEvent::RX_TIMEOUT:
case RadioEvent::ENTER_STATE:
m_radio->Rx(RX_TIMEOUT_ONE_SECOND * 30);
break;
case RadioEvent::SENSOR_MSG_RXD_OK:
if (m_sensorMsgReceivedHandler)
{
m_sensorMsgReceivedHandler();
}
return SendAck;
break;
default:
break;
}
return Receive;
}
/**
*
*/
Statemachine::Handler_ Statemachine::SendAck(Statemachine* me,
const RadioEvent event)
{
switch (event)
{
case RadioEvent::ENTER_STATE:
static AckMsg ack;
m_radio->Send((uint8_t*) &ack, sizeof(AckMsg));
break;
case RadioEvent::MSG_SEND_ERROR:
return Receive;
break;
case RadioEvent::MSG_SENT_OK:
return Receive;
break;
default:
break;
}
return SendAck;
}
/**
*
*/
void InjectEvent(RadioEvent event)
{
BaseType_t rtn = xQueueSend(m_queue, &event, 100);
if (rtn != pdPASS)
{
debug_if(1, "Queue Send failure!\n");
}
}
/**
* CreateTheRadio()
*/
void CreateTheRadio(void)
{
if (m_radio != nullptr)
{
debug_if(1, "ASSERT: radio exists, why call CreateTheRadio() ??\n");
return;
}
//Create and Initialize instance of SX1276inAir
m_radio = new SX1276inAir(OnRadioTxDone, OnRadioTxTimeout, OnRadioRxDone,
OnRadioRxTimeout, OnRadioRxError, NULL, NULL);
m_radio->SetBoardType(BOARD_INAIR9);
wait_ms(10);
//Wait for radio to be detected
while (m_radio->Read(REG_VERSION) == 0x00)
{
wait_ms(400);
debug_if(1, "Waiting on radio....\n", NULL);
}
//Initialize radio
m_radio->SetChannel(RF_FREQUENCY);
m_radio->SetTxConfig(MODEM_LORA, TX_OUTPUT_POWER, 0, LORA_BANDWIDTH,
LORA_SPREADING_FACTOR, LORA_CODINGRATE,
LORA_PREAMBLE_LENGTH, LORA_FIX_LENGTH_PAYLOAD_ON,
LORA_CRC_ENABLED, LORA_FHSS_ENABLED, LORA_NB_SYMB_HOP,
LORA_IQ_INVERSION_ON, 2000000);
m_radio->SetRxConfig(MODEM_LORA, LORA_BANDWIDTH,
LORA_SPREADING_FACTOR, LORA_CODINGRATE, 0,
LORA_PREAMBLE_LENGTH, LORA_SYMBOL_TIMEOUT,
LORA_FIX_LENGTH_PAYLOAD_ON, 0, LORA_CRC_ENABLED,
LORA_FHSS_ENABLED, LORA_NB_SYMB_HOP, LORA_IQ_INVERSION_ON, true);
}
/**
*
*/
void OnRadioTxDone(void)
{
m_radio->Sleep();
RadioEvent event = RadioEvent::MSG_SENT_OK;
xQueueSendToBackFromISR(m_queue, &event, nullptr);
}
/**
*
*/
void OnRadioRxDone(uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr)
{
static const SensorMsg REFERENCE_SENSOR_MSG;
if (size != sizeof(SensorMsg))
{
debug_if(1, "Rx size is not expected, size = %d\n", size);
m_radio->Sleep();
}
else
{
SensorMsg* pRxdMsg = (SensorMsg*) payload;
m_radio->Sleep();
/**
* The Sensor hardware is not able
* to measure its battery level, so this check
* is ignoring the battery fields.
*/
if ((0
== memcmp(pRxdMsg->hdr_id, REFERENCE_SENSOR_MSG.hdr_id,
sizeof(REFERENCE_SENSOR_MSG.hdr_id)))
&& (pRxdMsg->msg_id == REFERENCE_SENSOR_MSG.msg_id))
{
RadioEvent event = RadioEvent::SENSOR_MSG_RXD_OK;
xQueueSendToBackFromISR(m_queue, &event, nullptr);
}
else
{
debug_if(1, "size matched, but rx msg contents do not pass\n", size);
}
}
}
/**
*
*/
void OnRadioTxTimeout(void)
{
debug_if(1, "OnTxTimeout\n");
m_radio->Sleep();
RadioEvent event = RadioEvent::MSG_SEND_ERROR;
xQueueSendToBackFromISR(m_queue, &event, nullptr);
}
/**
*
*/
void OnRadioRxTimeout(void)
{
debug_if(1, "OnRxTimeout\n");
m_radio->Sleep();
RadioEvent event = RadioEvent::RX_TIMEOUT;
xQueueSendToBackFromISR(m_queue, &event, nullptr);
}
/**
*
*/
void OnRadioRxError(void)
{
debug_if(1, "OnRxError\n");
m_radio->Sleep();
RadioEvent event = RadioEvent::RX_ERROR;
xQueueSendToBackFromISR(m_queue, &event, nullptr);
}
} //namespace
| 21.471545 | 85 | 0.654424 | mattheweshleman |
6dd15b3fcf648fd857cb5a70bd4dff49e1cb3465 | 1,330 | hpp | C++ | tlib/include/tlib/print.hpp | osstudy/thor-os | 9b5793da647a27d7a6de2e48f6dd39dca0313d2b | [
"BSL-1.0"
] | null | null | null | tlib/include/tlib/print.hpp | osstudy/thor-os | 9b5793da647a27d7a6de2e48f6dd39dca0313d2b | [
"BSL-1.0"
] | null | null | null | tlib/include/tlib/print.hpp | osstudy/thor-os | 9b5793da647a27d7a6de2e48f6dd39dca0313d2b | [
"BSL-1.0"
] | 1 | 2020-02-04T16:36:51.000Z | 2020-02-04T16:36:51.000Z | //=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// 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 USER_PRINT_HPP
#define USER_PRINT_HPP
#include "tlib/config.hpp"
ASSERT_ONLY_THOR_PROGRAM
#include <stdarg.h>
#include <types.hpp>
#include <string.hpp>
#include <tlib/keycode.hpp>
namespace tlib {
void print(char c);
void print(const char* s);
void print(const std::string& s);
void print(uint8_t v);
void print(uint16_t v);
void print(uint32_t v);
void print(uint64_t v);
void print(int8_t v);
void print(int16_t v);
void print(int32_t v);
void print(int64_t v);
void print_line();
void print_line(const char* s);
void print_line(size_t v);
void print_line(const std::string& s);
void set_canonical(bool can);
void set_mouse(bool m);
size_t read_input(char* buffer, size_t max);
size_t read_input(char* buffer, size_t max, size_t ms);
std::keycode read_input_raw();
std::keycode read_input_raw(size_t ms);
void clear();
size_t get_columns();
size_t get_rows();
#include "printf_dec.hpp"
void user_logf(const char* s, ...);
} //end of namespace tlib
#endif
| 20.78125 | 73 | 0.658647 | osstudy |
6dd3142759f66b0b5eb6af52307768fab1a3d002 | 113 | hxx | C++ | src/Providers/UNIXProviders/Directory/UNIX_Directory_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/Directory/UNIX_Directory_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/Directory/UNIX_Directory_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_STUB
#ifndef __UNIX_DIRECTORY_PRIVATE_H
#define __UNIX_DIRECTORY_PRIVATE_H
#endif
#endif
| 9.416667 | 34 | 0.831858 | brunolauze |
6dd54260043d8016f283e6e1487c35b4c634129e | 661 | hpp | C++ | src/background/RoadGenerator.hpp | AgaBuu/TankBotFight | 154b176b697b5d88fffb4b0c9c9c2f8dac334afb | [
"MIT"
] | 10 | 2021-08-06T13:07:01.000Z | 2022-02-03T20:28:11.000Z | src/background/RoadGenerator.hpp | AgaBuu/TankBotFight | 154b176b697b5d88fffb4b0c9c9c2f8dac334afb | [
"MIT"
] | 29 | 2021-08-06T12:47:25.000Z | 2022-03-01T13:35:41.000Z | src/background/RoadGenerator.hpp | AgaBuu/TankBotFight | 154b176b697b5d88fffb4b0c9c9c2f8dac334afb | [
"MIT"
] | 10 | 2021-08-06T13:07:03.000Z | 2022-02-09T12:26:52.000Z | #pragma once
#include <SFML/Graphics.hpp>
#include <background/Ground.hpp>
class TextureStore;
class RoadGenerator {
public:
using RoadVec = std::vector<std::vector<bool>>;
using GroundTypeVec = std::vector<std::vector<GroundType>>;
static RoadVec generate();
};
namespace RoadPattern {
enum Pattern {
/* * * * *
- - - - -
* * * * *
* * * * *
* * * * */
VerticalLine = 0,
/* * * | *
* * * | *
* * * | *
* * * | *
* * * | */
HorizontalLine,
/* * * | *
- - - + -
* * * | *
* * * | *
* * * | */
SingleCrossroad,
/* * * * *
- - - + -
* * * | *
* * * | *
* * * | */
TLetter,
Size
};
}
| 15.022727 | 61 | 0.429652 | AgaBuu |
6dd67b7706bb01e6cf2a651e17a06faecc4838f8 | 13,722 | cpp | C++ | dependencies/TinyTest/TinyLib.cpp | bmharper/xo | 575429591c166cc70db60385d2a6563d0f9bc9ed | [
"Unlicense"
] | 7 | 2015-12-18T04:17:29.000Z | 2020-03-13T15:38:54.000Z | dependencies/TinyTest/TinyLib.cpp | benharper123/xo | 575429591c166cc70db60385d2a6563d0f9bc9ed | [
"Unlicense"
] | null | null | null | dependencies/TinyTest/TinyLib.cpp | benharper123/xo | 575429591c166cc70db60385d2a6563d0f9bc9ed | [
"Unlicense"
] | 4 | 2016-09-18T13:16:02.000Z | 2022-03-23T11:33:53.000Z | /*
This file contains the utility functions that are used by testing code.
*/
#ifdef _WIN32
#include <direct.h>
#include <VersionHelpers.h>
#include <tchar.h>
#pragma warning(push) // TinyLib-TOP
#pragma warning(disable: 6387)
#pragma warning(disable: 28204)
#include "StackWalker.h"
#else
#include <unistd.h>
#include <sys/wait.h>
#define _T(x) x
#endif
//typedef long long int64;
//typedef unsigned int uint;
#ifdef _WIN32
#define DIRSEP '\\'
#define EXE_EXTENSION ".exe"
#define DEFAULT_TEMP_DIR "c:\\temp"
#else
#define DIRSEP '/'
#define EXE_EXTENSION ""
#define DEFAULT_TEMP_DIR "/tmp"
#endif
#ifndef MAX_PATH
#define MAX_PATH 255
#endif
static bool IsExecutingUnderGuidance = false;
static int MasterPID = 0;
static char* TestCmdLineArgs[TT_MAX_CMDLINE_ARGS + 1]; // +1 for the null terminator
static char TestTempDir[TT_TEMP_DIR_SIZE + 1];
// These are defined inside TinyMaster.cpp
static int TTRun_Internal(const TT_TestList& tests, int argc, char** argv);
void TTException::CopyStr(size_t n, char* dst, const char* src)
{
dst[0] = 0;
if (src)
{
size_t i = 0;
for (; src[i] && i < n; i++)
dst[i] = src[i];
if (i < n) dst[i] = 0;
dst[n - 1] = 0;
}
}
void TTException::Set(const char* msg, const char* file, int line)
{
CopyStr(MsgLen, Msg, msg);
CopyStr(MsgLen, File, file);
Line = line;
}
TTException::TTException(const char* msg, const char* file, int line)
{
TTAssertFailed(msg, file, line, false);
Set(msg, file, line);
}
TT_TestList::TT_TestList()
{
// TT_TestList constructor must do nothing, but rely instead on zero-initialization of static data (which is part of the C spec).
// The reason is because constructor initialization order is undefined, and you will end up in this
// constructor some time AFTER objects have already started adding themselves to the list.
}
TT_TestList::~TT_TestList()
{
Clear();
}
void TT_TestList::Add(const TT_Test& t)
{
if (Count == Capacity)
{
int newcap = Capacity * 2;
if (newcap < 8) newcap = 8;
TT_Test* newlist = (TT_Test*) malloc(sizeof(List[0]) * newcap);
if (!newlist)
{
printf("TT_TestList out of memory\n");
exit(1);
}
memcpy(newlist, List, sizeof(List[0]) * Count);
free(List);
Capacity = newcap;
List = newlist;
}
List[Count++] = t;
}
void TT_TestList::Clear()
{
free(List);
List = NULL;
Count = 0;
Capacity = 0;
}
void TTSetProcessIdle()
{
#ifdef _WIN32
bool isVista = false;
#ifdef NTDDI_WINBLUE
isVista = IsWindowsVistaOrGreater();
#else
OSVERSIONINFO inf;
inf.dwOSVersionInfoSize = sizeof(inf);
GetVersionEx(&inf);
isVista = inf.dwMajorVersion >= 6;
#endif
SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
if (isVista)
SetPriorityClass(GetCurrentProcess(), PROCESS_MODE_BACKGROUND_BEGIN); // Lowers IO priorities too
#else
fprintf(stderr, "TTSetProcessIdle not implemented\n");
#endif
}
bool TTFileExists(const char* f)
{
#ifdef _WIN32
return GetFileAttributesA(f) != INVALID_FILE_ATTRIBUTES;
#else
return access(f, F_OK) != -1;
#endif
}
void TTWriteWholeFile(const char* filename, const char* str)
{
FILE* h = fopen(filename, "wb");
fwrite(str, strlen(str), 1, h);
fclose(h);
}
void TTLog(const char* msg, ...)
{
char buff[8192];
va_list va;
va_start(va, msg);
vsprintf(buff, msg, va);
va_end(va);
{
char tz[128];
time_t t;
time(&t);
tm t2;
#ifdef _WIN32
_localtime64_s(&t2, &t);
#else
localtime_r(&t, &t2);
#endif
strftime(tz, sizeof(tz), "%Y-%m-%d %H:%M:%S ", &t2);
//fwrite( tz, strlen(tz), 1, f );
fputs(tz, stdout);
//fwrite( buff, strlen(buff), 1, f );
buff[sizeof(buff) - 1] = 0;
fputs(buff, stdout);
//fclose(f);
}
}
static const char* ParallelName(TTParallel p)
{
switch (p)
{
case TTParallel_Invalid: return "INVALID!";
case TTParallelDontCare: return TT_PARALLEL_DONTCARE;
case TTParallelWholeCore: return TT_PARALLEL_WHOLECORE;
case TTParallelSolo: return TT_PARALLEL_SOLO;
}
return NULL;
}
unsigned int TTGetProcessID()
{
#ifdef _WIN32
return (unsigned int) GetCurrentProcessId();
#else
return (unsigned int) getpid();
#endif
}
std::string TTGetProcessPath()
{
char buf[1024];
#ifdef _WIN32
GetModuleFileNameA(NULL, buf, 1024);
#else
buf[readlink("/proc/self/exe", buf, 1024 - 1)] = 0; // untested
#endif
buf[1023] = 0;
return buf;
}
void TTSleep(unsigned int milliseconds)
{
#ifdef _WIN32
Sleep(milliseconds);
#else
int64_t nano = milliseconds * (int64_t) 1000000;
timespec t;
t.tv_nsec = nano % 1000000000;
t.tv_sec = (nano - t.tv_nsec) / 1000000000;
nanosleep(&t, NULL);
#endif
}
char** TTArgs()
{
return TestCmdLineArgs;
}
void TTSetTempDir(const char* tmp)
{
strncpy(TestTempDir, tmp + strlen(TT_PREFIX_TESTDIR), TT_TEMP_DIR_SIZE);
TestTempDir[TT_TEMP_DIR_SIZE] = 0;
size_t len = strlen(TestTempDir);
if (len != 0)
{
// Fight the shell's interpretation of:
// test.exe "two=c:\my\dir\"
// The Windows shell (or perhaps command line argument parser) will treat
// that last backslash as an escape, and end up including the quote character in the command line parameter.
// So here we chop off the last character, if it happens to be a quote.
if (TestTempDir[len - 1] == '"')
TestTempDir[len - 1] = 0;
}
// ensure our temp dir path ends with a dir separator
len = strlen(TestTempDir);
if (len != 0 && TestTempDir[len - 1] != DIRSEP)
{
TestTempDir[len] = DIRSEP;
TestTempDir[len + 1] = 0;
}
}
std::string TTGetTempDir()
{
return TestTempDir;
}
std::string TT_ToString(int v) { return std::to_string(v); }
std::string TT_ToString(double v) { return std::to_string(v); }
std::string TT_ToString(std::string v) { return v; }
const int MAXARGS = 30;
int TTRun_WrapperW(TT_TestList& tests, int argc, wchar_t** argv)
{
const int ARGSIZE = 400;
char* argva[MAXARGS];
if (argc >= MAXARGS - 1) { printf("TTRun_InternalW: Too many arguments\n"); return 1; }
for (int i = 0; i < argc; i++)
{
argva[i] = (char*) malloc(ARGSIZE);
wcstombs(argva[i], argv[i], ARGSIZE);
}
argva[argc] = NULL;
int res = TTRun_Wrapper(tests, argc, argva);
for (int i = 0; i < argc; i++)
free(argva[i]);
return res;
}
int TTRun_Wrapper(TT_TestList& tests, int argc, char** argv)
{
int res = TTRun_Internal(tests, argc, argv);
// ensure that there are no memory leaks by the time we return
tests.Clear();
return res;
}
#ifndef _WIN32
// Dummy
class StackWalker
{
protected:
virtual void OnOutput(bool isCallStackProper, const char* szText) {}
};
inline bool IsDebuggerPresent() { return false; }
#endif
class StackWalkerToConsole : public StackWalker
{
protected:
virtual void OnOutput(bool isCallStackProper, const char* szText)
{
if (isCallStackProper)
printf("%s", szText);
}
};
static void Die()
{
#ifdef _WIN32
if (IsDebuggerPresent())
__debugbreak();
TerminateProcess(GetCurrentProcess(), 1);
#else
_exit(1);
#endif
}
#ifdef _WIN32
static LONG WINAPI TTExceptionHandler(EXCEPTION_POINTERS* exInfo)
{
if (exInfo->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)
{
fputs("Stack overflow\n", stdout);
}
else
{
// The words "Stack Trace" must appear at the top, otherwise Jenkins
// is likely to discard too much of your trace, or your exception information
StackWalkerToConsole sw; // output to console
printf("------- Unhandled Exception and Stack Trace ------- \n"
" Code: 0x%8.8X\n"
" Flags: %u\n"
" Address: 0x%p\n",
exInfo->ExceptionRecord->ExceptionCode,
exInfo->ExceptionRecord->ExceptionFlags,
exInfo->ExceptionRecord->ExceptionAddress);
fflush(stdout);
printf("-------\n");
fflush(stdout);
sw.ShowCallstack(GetCurrentThread(), exInfo->ContextRecord);
fflush(stdout);
}
fflush(stdout);
TerminateProcess(GetCurrentProcess(), 33);
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
static void TTPurecallHandler()
{
printf("Undefined virtual function called (purecall)\n");
fflush(stdout);
Die();
}
#ifdef _WIN32
static void TTInvalidParameterHandler(const wchar_t * expression, const wchar_t * function, const wchar_t * file, unsigned int line, uintptr_t pReserved)
{
//if ( expression && function && file )
// fputs( "CRT function called with invalid parameters: %S\n%S\n%S:%d\n", expression, function, file, line );
//else
fputs("CRT function called with invalid parameters\n", stdout);
fflush(stdout);
Die();
}
#endif
static void TTSignalHandler(int signal)
{
printf("Signal %d called", signal);
fflush(stdout);
Die();
}
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 6031) // return value ignored for mkdir
#endif
void TT_IPC_Filename(bool up, unsigned int masterPID, unsigned int testedPID, char (&filename)[256])
{
#ifdef _WIN32
// We prefer c:\temp over obscure stuff inside the "proper" temp directory, because that tends to fill up with stuff you never see.
_mkdir("c:\\temp");
sprintf(filename, "c:\\temp\\tiny_test_ipc_%s_%u_%u", up ? "up" : "down", masterPID, testedPID);
#else
sprintf(filename, "/tmp/tiny_test_ipc_%s_%u_%u", up ? "up" : "down", masterPID, testedPID);
#endif
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
bool TT_IPC_Read_Raw(unsigned int waitMS, char (&filename)[256], char (&msg)[TT_IPC_MEM_SIZE])
{
memset(msg, 0, sizeof(msg));
FILE* file = fopen(filename, "rb");
if (file == NULL)
{
TTSleep(waitMS);
return false;
}
unsigned int length = 0;
bool good = false;
if (fread(&length, sizeof(length), 1, file) == 1)
{
if (length > TT_IPC_MEM_SIZE)
printf("Error: TT_IPC_Read_Raw encountered a block larger than TT_IPC_MEM_SIZE\n");
else
good = fread(&msg, length, 1, file) == 1;
}
fclose(file);
// We acknowledge receipt by deleting the file
if (good)
remove(filename);
return good;
}
void TT_IPC_Write_Raw(char (&filename)[256], const char* msg)
{
char buf[512];
unsigned int length = (unsigned int) strlen(msg);
FILE* file = fopen(filename, "wb");
if (file == NULL)
{
sprintf(buf, "TT_IPC failed to open %s", filename);
TTAssertFailed(buf, "internal", 0, true);
}
fwrite(&length, sizeof(length), 1, file);
fwrite(msg, length, 1, file);
fclose(file);
file = NULL;
// The other side acknowledges this transmission by deleting the file
unsigned int sleepMS = 10;
for (unsigned int nwait = 0; nwait < 3 * 1000 / sleepMS; nwait++)
{
TTSleep(sleepMS);
if (!TTFileExists(filename))
return;
if (nwait * sleepMS > 500)
printf("Still waiting for other side to delete %s\n", filename);
}
sprintf(buf, "TT_IPC executor failed to acknowledge read on %s", filename);
TTAssertFailed(buf, "internal", 0, true);
}
static void TT_IPC(const char* msg, ...)
{
// This is one-way communication, from the tested process to the master process
// Disable IPC if we're not being run as an automated test.
if (MasterPID == 0)
return;
char filename[256];
TT_IPC_Filename(true, MasterPID, TTGetProcessID(), filename);
char buf[8192];
va_list va;
va_start(va, msg);
vsprintf(buf, msg, va);
va_end(va);
TT_IPC_Write_Raw(filename, buf);
}
void TTNotifySubProcess(unsigned int pid)
{
TT_IPC("%s %u", TT_IPC_CMD_SUBP_RUN, pid);
}
unsigned int TTLaunchChildProcess_Internal(const char* cmd, const char** args)
{
#ifdef _WIN32
std::string all = cmd;
for (size_t i = 0; args[i]; i++)
{
all += " ";
all += args[i];
}
unsigned int pid = -1;
STARTUPINFOA si;
memset(&si, 0, sizeof(si));
PROCESS_INFORMATION pi;
DWORD flags = 0;
// Creating a new console can be useful when debugging, but not sure if this is
// really the right thing to do, for consistency sake.
if (!TTIsRunningUnderMaster())
flags |= CREATE_NEW_CONSOLE;
char* buf = new char[all.size() + 1];
memcpy(buf, all.c_str(), all.size());
buf[all.size()] = 0;
bool ok = !!CreateProcessA(cmd, buf, NULL, NULL, false, flags, NULL, NULL, &si, &pi);
if (ok)
{
pid = pi.dwProcessId;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
#else
std::vector<const char*> all;
all.push_back(cmd);
for (size_t i = 0; args[i]; i++)
all.push_back(args[i]);
all.push_back(nullptr);
pid_t pid = fork();
if (pid == 0)
{
// child
pid_t res = execvp(cmd, (char * const *) &all[0]);
// execvp only returns if an error occurred
printf("launch of pid = %d failed (%s)\n", (int) getpid(), cmd);
exit(1);
}
else
{
// parent
// We assume that the child process is expected to run indefinitely. At least,
// we expect it to run at least until we return from this function. So it's safe to
// say that if the child has already exited, then the execvp failed.
// We wait for only 5ms, because the execvp fails fast if the path cannot be found.
bool running = true;
for (int i = 0; i < 5; i++)
{
int status = 0;
pid_t res = waitpid(pid, &status, WNOHANG | WUNTRACED);
if (res == pid)
{
running = false;
break;
}
TTSleep(1);
}
if (!running)
return -1;
printf("launch of pid = %d succeeded (%s)\n", (int) pid, cmd);
}
#endif
return (unsigned int) pid;
}
void TTLaunchChildProcess(const char* cmd, const char** args)
{
unsigned int pid = TTLaunchChildProcess_Internal(cmd, args);
if (pid == -1)
{
// try rewriting 'cmd' path to be in same directory as ourselves
std::string self = TTGetProcessPath();
auto lastslash = self.rfind(DIRSEP);
if (lastslash != -1 && std::string(cmd).find(DIRSEP) == -1)
{
std::string newCmd = self.substr(0, lastslash + 1) + cmd;
if (newCmd.rfind(EXE_EXTENSION) != newCmd.size() - strlen(EXE_EXTENSION))
newCmd += EXE_EXTENSION;
pid = TTLaunchChildProcess_Internal(newCmd.c_str(), args);
}
}
if (pid != -1)
TTNotifySubProcess(pid);
else
TTAssertFailed((std::string("Failed to launch child process ") + cmd).c_str(), "", 0, true);
}
#ifdef _MSC_VER
#pragma warning( pop ) // TinyLib-TOP
#endif
| 23.781629 | 153 | 0.683865 | bmharper |
6dd704aef7d847fa4387f612abd9ce17ce995973 | 2,848 | cpp | C++ | liblava-extras/liblava-extras/fbx/fbx_loader.cpp | Cons-Cat/lava-fbx | 266a52bc5616abd38a1b72086809521caff41971 | [
"MIT"
] | null | null | null | liblava-extras/liblava-extras/fbx/fbx_loader.cpp | Cons-Cat/lava-fbx | 266a52bc5616abd38a1b72086809521caff41971 | [
"MIT"
] | null | null | null | liblava-extras/liblava-extras/fbx/fbx_loader.cpp | Cons-Cat/lava-fbx | 266a52bc5616abd38a1b72086809521caff41971 | [
"MIT"
] | null | null | null | #include <liblava-extras/fbx/fbx_glm.hpp>
#include <liblava-extras/fbx/fbx_loader.hpp>
namespace lava::extras {
auto load_fbx_scene(lava::name filename) -> ofbx::IScene* {
std::string target_file = filename;
// lava::cdata const file_data = lava::file_data(filename);
// TODO(conscat): Modernize C-style casts.
FILE* fp = fopen(filename, "rb");
if (fp == nullptr) {
return nullptr;
}
fseek(fp, 0, SEEK_END);
lava::int64 file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char* content = new ofbx::u8[file_size];
fread(content, 1, file_size, fp);
// ofbx::u8 const* fbx_data = reinterpret_cast<ofbx::u8
// const*>(file_data.ptr);
auto* scene =
ofbx::load(static_cast<ofbx::u8*>(content), file_size,
static_cast<ofbx::u64>(ofbx::LoadFlags::TRIANGULATE));
// auto* scene = ofbx::load((ofbx::u8*)fbx_data, file_data.size,
// (ofbx::u64)ofbx::LoadFlags::TRIANGULATE);
// ofbx::IScene* scene = ofbx::load(
// fbx_data, file_data.size,
// static_cast<ofbx::u64>(ofbx::LoadFlags::TRIANGULATE));
return scene;
}
// TODO(conscat): Template the type of vertices here.
auto load_fbx_model(ofbx::IScene* scene) -> fbx_data {
lava::extras::fbx_data fbx_data;
lava::mesh_data mesh_data;
int indices_offset = 0;
int mesh_count = scene->getMeshCount();
for (int i = 0; i < mesh_count; i++) {
const ofbx::Mesh* mesh = scene->getMesh(i);
auto mesh_transform_global = mesh->getGlobalTransform();
const ofbx::Geometry* geom = mesh->getGeometry();
const int vertex_count = geom->getVertexCount();
const ofbx::Vec3* fbx_vertices = geom->getVertices();
for (int i = 0; i < vertex_count; ++i) {
ofbx::Vec3 v = fbx_vertices[i];
glm::vec4 transformed_position =
lava::extras::fbx_mat_to_glm_mat(mesh_transform_global) *
glm::vec4(v.x, v.y, v.z, 1);
lava::vertex lava_vertex{.position = glm::vec3(transformed_position.x,
-transformed_position.y,
transformed_position.z)};
mesh_data.vertices.push_back(lava_vertex);
}
const int* indices = geom->getFaceIndices();
int index_count = geom->getIndexCount();
for (int j = 0; j < index_count; j++) {
// Negative indices represent the end of a polygon. They must be inverted
// and decremented.
int index = (indices[j] < 0) ? (-indices[j] - 1) : indices[j];
mesh_data.indices.push_back(index +
indices_offset); // cast to `lava::index`
}
indices_offset += vertex_count;
}
// TODO(conscat): Template arguments (and concepts) for loading colors,
// normals, and UVs.
fbx_data.mesh_data = mesh_data;
return fbx_data;
}
} // namespace lava::extras
| 37.973333 | 79 | 0.625351 | Cons-Cat |
6ddf6156d6075b439a93ac137a6c23e8da335f9b | 1,028 | hpp | C++ | src/ida_cnv_utils.hpp | obaby/ida_key_checker | f31315e0d29d1e02362c3f870245d2d8873271bb | [
"MIT"
] | 1 | 2021-11-19T13:11:56.000Z | 2021-11-19T13:11:56.000Z | src/ida_cnv_utils.hpp | obaby/ida_key_checker | f31315e0d29d1e02362c3f870245d2d8873271bb | [
"MIT"
] | null | null | null | src/ida_cnv_utils.hpp | obaby/ida_key_checker | f31315e0d29d1e02362c3f870245d2d8873271bb | [
"MIT"
] | 1 | 2021-11-19T13:12:00.000Z | 2021-11-19T13:12:00.000Z | /*
* Some conversion utils header
*
* RnD, 2021
*/
#ifdef _MSC_VER
#pragma once
#endif
#ifndef _IDA_CONVERSION_UTILS_HPP_
#define _IDA_CONVERSION_UTILS_HPP_
#include <cstdint>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "ida_license.hpp"
#include "ida_key.hpp"
using namespace std;
namespace ida
{
void print_license(const license_t& license, bool skip_ver = false);
string get_license_type(uint16_t type);
string get_license_id(const id_t& id);
string get_time(time_t time, bool extended = false);
string get_username(const char* username);
string get_hex(const uint8_t* data, size_t size);
string get_hex(const string& value);
template<typename T>
string get_hex(const T& value)
{
std::stringstream str;
str << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2);
if (sizeof(T) == 1)
str << static_cast<uint16_t>(value);
else
str << value;
return str.str();
}
time_t get_time(const string& value, bool extended = false);
}
#endif // _IDA_CONVERSION_UTILS_HPP_ | 20.56 | 69 | 0.724708 | obaby |
6de0021626771d7b428cf23078f5bcf3a5838a0e | 7,072 | cpp | C++ | JEngine/src/Platform/OpenGL/OpenGLShader.cpp | peter-819/JEngine | f4362cdaa5e781e3a973cf84b604bd055b1b3880 | [
"Apache-2.0"
] | 1 | 2020-06-01T05:24:16.000Z | 2020-06-01T05:24:16.000Z | JEngine/src/Platform/OpenGL/OpenGLShader.cpp | peter-819/JEngine | f4362cdaa5e781e3a973cf84b604bd055b1b3880 | [
"Apache-2.0"
] | null | null | null | JEngine/src/Platform/OpenGL/OpenGLShader.cpp | peter-819/JEngine | f4362cdaa5e781e3a973cf84b604bd055b1b3880 | [
"Apache-2.0"
] | null | null | null | #include "JEpch.h"
#include "OpenGLShader.h"
#include "glad/glad.h"
#include "gtc/type_ptr.hpp"
namespace JEngine {
static GLenum ShaderTypeFromString(const std::string& type) {
if (type == "vertex")
return GL_VERTEX_SHADER;
if (type == "fragment" || type == "pixel")
return GL_FRAGMENT_SHADER;
JE_CORE_ASSERT(false, "Unknown shader type");
return 0;
}
bool OpenGLShader::checkStatus(
GLuint objectID,
PFNGLGETSHADERIVPROC objectPropertyGetterFunc,
PFNGLGETSHADERINFOLOGPROC getInfoLogFunc,
GLenum statusType
) {
GLint compileStatus;
objectPropertyGetterFunc(objectID, statusType, &compileStatus);
if (compileStatus != GL_TRUE) {
GLint infoLogLength;
objectPropertyGetterFunc(objectID, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar* buffer = new GLchar[infoLogLength];
GLsizei bufferSize;
getInfoLogFunc(objectID, infoLogLength, &bufferSize, buffer);
JE_CORE_ERROR("{0}", buffer);
delete[] buffer;
return false;
}
return true;
}
bool OpenGLShader::checkShaderStatus(GLuint shaderID) {
return checkStatus(shaderID, glGetShaderiv, glGetShaderInfoLog, GL_COMPILE_STATUS);
}
bool OpenGLShader::checkProgramStatus(GLuint programID) {
return checkStatus(programID, glGetProgramiv, glGetProgramInfoLog, GL_LINK_STATUS);
}
std::string OpenGLShader::ReadSource(const std::string & filepath) {
std::ifstream meInput(filepath);
if (!meInput.good()) {
JE_CORE_ASSERT(false, "Failed to load shader file");
exit(1);
}
return std::string(
std::istreambuf_iterator<char>(meInput),
std::istreambuf_iterator<char>()
);
}
void OpenGLShader::Compile(const std::unordered_map<GLenum, std::string>& ShaderSource) {
std::array<GLuint, 4> ShaderIDs;
int Index = 0;
ProgramID = glCreateProgram();
for (auto& kv : ShaderSource) {
GLuint ShaderID = glCreateShader(kv.first);
const GLchar* adapter[1];
adapter[0] = kv.second.c_str();
glShaderSource(ShaderID, 1, adapter, 0);
glCompileShader(ShaderID);
JE_CORE_ASSERT(checkShaderStatus(ShaderID), "Can't compile shader");
glAttachShader(ProgramID, ShaderID);
glLinkProgram(ProgramID);
JE_CORE_ASSERT(checkProgramStatus(ProgramID), "Can't Attach shader");
ShaderIDs[Index++] = ShaderID;
glDeleteShader(ShaderID);
}
for (auto id : ShaderIDs)
glDetachShader(ProgramID, id);
}
std::unordered_map<GLenum, std::string> OpenGLShader::PreProcess(const std::string& source) {
std::unordered_map<GLenum, std::string> shadersource;
const char* typetoken = "#type";
size_t typeTokenLength = strlen(typetoken);
size_t pos = source.find(typetoken, 0);
while (pos != std::string::npos) {
size_t eol = source.find_first_of("\r\n", pos);
JE_CORE_ASSERT(eol != std::string::npos, "Syntax error");
size_t begin = pos + typeTokenLength + 1;
std::string type = source.substr(begin, eol - begin);
JE_CORE_ASSERT(ShaderTypeFromString(type), "Invalid shader type");
size_t NextLinePos = source.find_first_not_of("\r\n", eol);
JE_CORE_ASSERT(NextLinePos != std::string::npos, "Syntax error");
pos = source.find(typetoken, NextLinePos);
shadersource[ShaderTypeFromString(type)] = (pos == std::string::npos) ? source.substr(NextLinePos) : source.substr(NextLinePos, pos - NextLinePos);
}
return shadersource;
}
OpenGLShader::OpenGLShader(const std::string& name,const std::string& vertshader,const std::string& fragshader) {
std::unordered_map<GLenum, std::string> ShaderSource;
ShaderSource[GL_VERTEX_SHADER] = vertshader;
ShaderSource[GL_FRAGMENT_SHADER] = fragshader;
Compile(ShaderSource);
m_Name = name;
}
OpenGLShader::OpenGLShader(const std::string& filepath) {
std::string source = ReadSource(filepath);
auto shadersources = PreProcess(source);
Compile(shadersources);
/*auto lastSlash = filepath.find_last_of("/\\");
lastSlash = lastSlash == std::string::npos ? 0 : lastSlash + 1;
auto lastDot = filepath.rfind('.');
auto count = lastDot == std::string::npos ? filepath.size() - lastSlash : lastDot - lastSlash;
m_Name = filepath.substr(lastSlash, count);*/
std::filesystem::path path = filepath;
m_Name = path.stem().string();
}
OpenGLShader::OpenGLShader(const std::string& name, const std::string& filepath) {
std::string source = ReadSource(filepath);
auto shadersources = PreProcess(source);
Compile(shadersources);
m_Name = name;
}
void OpenGLShader::Bind() const {
glUseProgram(ProgramID);
}
void OpenGLShader::UnBind() const {
glUseProgram(0);
}
const std::string& OpenGLShader::GetName() const { return m_Name; }
//----------------------------------SET VALUE PART-------------------------------------------//
void OpenGLShader::SetFloat (const std::string& name, float value) {
UpLoadUniformFloat (name, value);
}
void OpenGLShader::SetFloat2(const std::string& name, const glm::vec2& value) {
UpLoadUniformFloat2(name, value);
}
void OpenGLShader::SetFloat3(const std::string& name, const glm::vec3& value) {
UpLoadUniformFloat3(name, value);
}
void OpenGLShader::SetFloat4(const std::string& name, const glm::vec4& value) {
UpLoadUniformFloat4(name, value);
}
void OpenGLShader::SetMat3(const std::string& name, const glm::mat3& matrix) {
UpLoadUniformMat3(name, matrix);
}
void OpenGLShader::SetMat4(const std::string& name, const glm::mat4& matrix) {
UpLoadUniformMat4(name, matrix);
}
void OpenGLShader::SetBool(const std::string& name,bool value){
UpLoadUniformBool(name, value);
}
//-------------------------------UPLOAD UNIFORM VALUE PART------------------------------------//
void OpenGLShader::UpLoadUniformFloat (const std::string& name, float value) {
GLuint location = glGetUniformLocation(ProgramID, name.c_str());
glUniform1f(location, value);
}
void OpenGLShader::UpLoadUniformFloat2(const std::string& name, const glm::vec2& value) {
GLuint location = glGetUniformLocation(ProgramID, name.c_str());
glUniform2f(location, value.x, value.y);
}
void OpenGLShader::UpLoadUniformFloat3(const std::string& name, const glm::vec3& value) {
GLuint location = glGetUniformLocation(ProgramID, name.c_str());
glUniform3f(location, value.x, value.y, value.z);
}
void OpenGLShader::UpLoadUniformFloat4(const std::string& name, const glm::vec4& value) {
GLuint location = glGetUniformLocation(ProgramID, name.c_str());
glUniform4f(location, value.x, value.y, value.z, value.w);
}
void OpenGLShader::UpLoadUniformMat3(const std::string& name, const glm::mat3& matrix) {
GLint location = glGetUniformLocation(ProgramID, name.c_str());
glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(matrix));
}
void OpenGLShader::UpLoadUniformMat4(const std::string& name, const glm::mat4& matrix) {
GLint location = glGetUniformLocation(ProgramID, name.c_str());
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix));
}
void OpenGLShader::UpLoadUniformBool(const std::string& name, bool value) {
GLuint location = glGetUniformLocation(ProgramID, name.c_str());
glUniform1i(location, value);
}
} | 33.67619 | 150 | 0.711538 | peter-819 |
6de0a964aa479015f01f1facb00db4ca2b058f26 | 2,136 | cpp | C++ | tbaas/src/v20180416/model/PeerDetailForUser.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | tbaas/src/v20180416/model/PeerDetailForUser.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | tbaas/src/v20180416/model/PeerDetailForUser.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* 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/tbaas/v20180416/model/PeerDetailForUser.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tbaas::V20180416::Model;
using namespace std;
PeerDetailForUser::PeerDetailForUser() :
m_peerNameHasBeenSet(false)
{
}
CoreInternalOutcome PeerDetailForUser::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("PeerName") && !value["PeerName"].IsNull())
{
if (!value["PeerName"].IsString())
{
return CoreInternalOutcome(Error("response `PeerDetailForUser.PeerName` IsString=false incorrectly").SetRequestId(requestId));
}
m_peerName = string(value["PeerName"].GetString());
m_peerNameHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void PeerDetailForUser::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_peerNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PeerName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_peerName.c_str(), allocator).Move(), allocator);
}
}
string PeerDetailForUser::GetPeerName() const
{
return m_peerName;
}
void PeerDetailForUser::SetPeerName(const string& _peerName)
{
m_peerName = _peerName;
m_peerNameHasBeenSet = true;
}
bool PeerDetailForUser::PeerNameHasBeenSet() const
{
return m_peerNameHasBeenSet;
}
| 27.74026 | 138 | 0.718633 | sinjoywong |
6de56421c8e677f857ef2ed30b996838c97996bf | 891 | cpp | C++ | Havtorn/Source/Engine/Core/MathTypes/Curve.cpp | AxelSavage/NewEngine | cd86b4ff19d97f69b0f2ffb16343722885898424 | [
"MIT"
] | null | null | null | Havtorn/Source/Engine/Core/MathTypes/Curve.cpp | AxelSavage/NewEngine | cd86b4ff19d97f69b0f2ffb16343722885898424 | [
"MIT"
] | null | null | null | Havtorn/Source/Engine/Core/MathTypes/Curve.cpp | AxelSavage/NewEngine | cd86b4ff19d97f69b0f2ffb16343722885898424 | [
"MIT"
] | 1 | 2022-01-09T12:01:24.000Z | 2022-01-09T12:01:24.000Z | // Copyright 2022 Team Havtorn. All Rights Reserved.
#include "hvpch.h"
#include "Curve.h"
namespace Havtorn
{
SVector SCatmullRom::GetPoint(F32 t)
{
F32 tt = t * t;
F32 ttt = t * t * t;
return
(P3 * (-tt + ttt)
+ P2 * (t + 4.0f * tt - 3.0f * ttt)
+ P1 * (2.0f - 5.0f * tt + 3.0f * ttt)
+ P0 * (-t + 2.0f * tt - ttt)) * 0.5f
;
}
SVector SCatmullRom::GetTangent(F32 t)
{
F32 tt = t * t;
return
(P3 * (-2.0f * t + 3.0f * tt)
+ P2 * (1.0f + 8.0f * t - 9.0f * tt)
+ P1 * (-10.0f * t + 9.0f * tt)
+ P0 * (-1.0f + 4.0f * t - 3 * tt)) * 0.5f
;
}
SVector SCatmullRom::GetNormal(F32 t)
{
SVector tangent = GetTangent(t);
// TODO.NR: Rotate tangent 90 degrees for normal
return tangent;
}
SCatmullRom::SCatmullRom(const SVector& p0, const SVector& p1, const SVector& p2, const SVector& p3)
: P0(p0), P1(p1), P2(p2), P3(p3)
{}
}
| 20.25 | 101 | 0.542088 | AxelSavage |
6de660aa4d47fbee24ea72d3a4c40bd782b45bec | 3,485 | cpp | C++ | libnaucrates/src/parser/CParseHandlerScalarPartBoundOpen.cpp | hsyuan/gporca | 793b1dd7f55eb0e97f829e9e3b58d2a3133cf7ad | [
"ECL-2.0",
"Apache-2.0"
] | 466 | 2016-01-26T18:07:03.000Z | 2022-03-30T06:08:55.000Z | libnaucrates/src/parser/CParseHandlerScalarPartBoundOpen.cpp | hsyuan/gporca | 793b1dd7f55eb0e97f829e9e3b58d2a3133cf7ad | [
"ECL-2.0",
"Apache-2.0"
] | 463 | 2016-01-26T19:13:02.000Z | 2022-03-24T03:08:13.000Z | libnaucrates/src/parser/CParseHandlerScalarPartBoundOpen.cpp | hsyuan/gporca | 793b1dd7f55eb0e97f829e9e3b58d2a3133cf7ad | [
"ECL-2.0",
"Apache-2.0"
] | 203 | 2016-01-26T13:46:35.000Z | 2022-03-22T03:17:06.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2014 Pivotal, Inc.
//
// @filename:
// CParseHandlerScalarPartBoundOpen.cpp
//
// @doc:
// Implementation of the SAX parse handler class for parsing part bound openness
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerScalarPartBoundOpen.h"
#include "naucrates/dxl/operators/CDXLOperatorFactory.h"
#include "naucrates/dxl/operators/CDXLScalarPartBoundOpen.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/parser/CParseHandlerScalarOp.h"
using namespace gpdxl;
XERCES_CPP_NAMESPACE_USE
//---------------------------------------------------------------------------
// @function:
// CParseHandlerScalarPartBoundOpen::CParseHandlerScalarPartBoundOpen
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CParseHandlerScalarPartBoundOpen::CParseHandlerScalarPartBoundOpen(
CMemoryPool *mp, CParseHandlerManager *parse_handler_mgr,
CParseHandlerBase *parse_handler_root)
: CParseHandlerScalarOp(mp, parse_handler_mgr, parse_handler_root)
{
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerScalarPartBoundOpen::StartElement
//
// @doc:
// Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerScalarPartBoundOpen::StartElement(
const XMLCh *const, // element_uri,
const XMLCh *const element_local_name,
const XMLCh *const, // element_qname,
const Attributes &attrs)
{
if (0 != XMLString::compareString(
CDXLTokens::XmlstrToken(EdxltokenScalarPartBoundOpen),
element_local_name))
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(
m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag,
str->GetBuffer());
}
ULONG partition_level = CDXLOperatorFactory::ExtractConvertAttrValueToUlong(
m_parse_handler_mgr->GetDXLMemoryManager(), attrs, EdxltokenPartLevel,
EdxltokenScalarPartBoundOpen);
BOOL is_lower_bound = CDXLOperatorFactory::ExtractConvertAttrValueToBool(
m_parse_handler_mgr->GetDXLMemoryManager(), attrs,
EdxltokenScalarPartBoundLower, EdxltokenScalarPartBoundOpen);
m_dxl_node = GPOS_NEW(m_mp)
CDXLNode(m_mp, GPOS_NEW(m_mp) CDXLScalarPartBoundOpen(
m_mp, partition_level, is_lower_bound));
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerScalarPartBoundOpen::EndElement
//
// @doc:
// Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerScalarPartBoundOpen::EndElement(
const XMLCh *const, // element_uri,
const XMLCh *const element_local_name,
const XMLCh *const // element_qname
)
{
if (0 != XMLString::compareString(
CDXLTokens::XmlstrToken(EdxltokenScalarPartBoundOpen),
element_local_name))
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(
m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag,
str->GetBuffer());
}
GPOS_ASSERT(NULL != m_dxl_node);
// deactivate handler
m_parse_handler_mgr->DeactivateHandler();
}
// EOF
| 32.570093 | 81 | 0.643042 | hsyuan |
6df03fb545e337ff07d06e36ec8ed24e62c3b79b | 7,480 | cpp | C++ | SSW/main.cpp | qq456cvb/SSW | 65c5d4d782330e6d87531dab759baff9d4d7104b | [
"MIT"
] | null | null | null | SSW/main.cpp | qq456cvb/SSW | 65c5d4d782330e6d87531dab759baff9d4d7104b | [
"MIT"
] | null | null | null | SSW/main.cpp | qq456cvb/SSW | 65c5d4d782330e6d87531dab759baff9d4d7104b | [
"MIT"
] | null | null | null | //
// main.cpp
// SSW
//
// Created by Neil on 16/05/2018.
// Copyright © 2018 Neil. All rights reserved.
//
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include "unionset.hpp"
using namespace cv;
using namespace std;
class Mypair {
public:
Union *first, *second;
Mypair(Union *a, Union *b) : first(a), second(b) {};
bool operator==(const Mypair &p) {
return (first == p.first && second == p.second) || (first == p.second && second == p.first);
}
};
struct PairHasher
{
std::size_t operator()(const Mypair& p) const
{
using std::size_t;
using std::hash;
return (hash<void*>()(p.first) ^ hash<void*>()(p.second));
}
};
struct EdgeHasher
{
std::size_t operator()(const Edge& e) const
{
using std::size_t;
using std::hash;
return (hash<void*>()(e.first) ^ hash<void*>()(e.second));
}
};
bool operator==(const Edge &e1, const Edge &e2) {
return (e1.first == e2.first && e1.second == e2.second) ||
(e1.second == e2.first && e1.first == e2.second);
}
void showUnions(std::vector<Union> &unions, int rows, int cols) {
static vector<Vec3b> colors;
if (colors.empty()) {
for (int i = 0; i < unions.size(); i++) {
colors.emplace_back(rand() % 255, rand() % 255, rand() % 255);
}
}
unordered_map<Union*, Vec3b> set;
for (int i = 0; i < unions.size(); i++) {
Union *tmp = &unions[i];
set[find(tmp)] = colors[i];
}
printf("number of components: %lu\n", set.size());
Mat result(rows, cols, CV_8UC3);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
Union *tmp = &unions[i * cols + j];
result.at<Vec3b>(i, j) = set[find(tmp)];
}
}
cv::imshow("result", result);
cv::waitKey(0);
}
int main(int argc, const char * argv[]) {
auto img = imread("lena.jpg");
// resize(img, img, Size(256, 256));
// resize(img, img, Size(320, 240));
// Mat bgr[3];
// split(img, bgr);
// img = bgr[0];
cvtColor(img, img, CV_BGR2GRAY);
float sigma = 0.8f;
GaussianBlur(img, img, Size(0, 0), sigma);
Mat dx, dy;
spatialGradient(img, dx, dy);
int k = 300;
auto ptr = (uint8_t*)img.data;
std::vector<Edge> edges;
edges.reserve(img.rows * img.cols * 4);
std::vector<Union> unions;
unions.reserve(img.rows * img.cols);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int idx = i * img.cols + j;
unions.emplace_back();
if (i > 0) {
edges.emplace_back(&unions[unions.size() - 1 - img.cols], &unions.back(), abs((int)ptr[idx] - (int)ptr[idx - img.cols]));
unions.back().neighbours.insert(&unions[unions.size() - 1 - img.cols]);
unions[unions.size() - 1 - img.cols].neighbours.insert(&unions.back());
}
if (j > 0) {
edges.emplace_back(&unions[unions.size() - 2], &unions.back(), abs((int)ptr[idx] - (int)ptr[idx - 1]));
unions.back().neighbours.insert(&unions[unions.size() - 2]);
unions[unions.size() - 2].neighbours.insert(&unions.back());
}
if (i > 0 && j > 0) {
edges.emplace_back(&unions[unions.size() - 2 - img.cols], &unions.back(), abs((int)ptr[idx] - (int)ptr[idx - 1 - img.cols]));
unions.back().neighbours.insert(&unions[unions.size() - 2 - img.cols]);
unions[unions.size() - 2 - img.cols].neighbours.insert(&unions.back());
}
if (j < img.cols - 1 && i > 0) {
edges.emplace_back(&unions[unions.size() - img.cols], &unions.back(), abs((int)ptr[idx] - (int)ptr[idx + 1 - img.cols]));
unions.back().neighbours.insert(&unions[unions.size() - img.cols]);
unions[unions.size() - img.cols].neighbours.insert(&unions.back());
}
float angle = atan2(float(dy.at<uchar>(i, j)), float(dx.at<uchar>(i, j)));
if (angle < 0) angle += M_PI / 2;
int bin_idx = static_cast<int>(angle / M_PI * 4);
unions.back().hist[bin_idx] = 1.f;
}
}
sort(edges.begin(), edges.end(), [](const Edge &e1, const Edge &e2){
return e1.weight < e2.weight;
});
for (int i = 0; i < edges.size(); i++) {
Union *a = find(edges[i].first);
Union *b = find(edges[i].second);
if (a != b) {
if (edges[i].weight <= fmin(a->inter + k / (float)a->size, b->inter + k / (float)b->size)) {
merge(a, b)->inter = edges[i].weight;
}
}
}
showUnions(unions, img.rows, img.cols);
// hash map, runtime: NK, N is # of components, K is # of neighbours
unordered_set<Union*> set;
for (int i = 0; i < unions.size(); i++) {
Union *tmp = &unions[i];
set.insert(find(tmp));
}
unordered_set<Edge, EdgeHasher> sims;
for (auto u : set) {
for (auto nbr : u->neighbours) {
Union *other = find(nbr);
if (other == u) continue;
float score_size =1. - (u->size + other->size) / double(img.cols * img.rows);
float score_texture = 0.f;
for (int i = 0; i < 8; i++) {
score_texture += u->hist[i] * other->hist[i];
}
float sim = score_size + score_texture;
sims.emplace(u, other, sim);
}
}
for (auto sim : sims) {
for (auto nbr : sim.first->neighbours) {
if (sim.first == find(nbr)) continue;
assert(sims.find(Edge(find(sim.first), find(nbr), 0.f)) != sims.end());
}
}
int cnt = 0;
auto target = set.size() - 2;
while (cnt++ < target) {
auto min_edge = *std::max_element(sims.begin(), sims.end(), [](const Edge &e1, const Edge &e2) {
return e1.sim < e2.sim;
});
auto u1 = find(min_edge.first);
auto u2 = find(min_edge.second);
if (u1 == u2) continue;
for (auto nbr : u1->neighbours) {
assert(u1->parent == u1);
if (u1 == find(nbr)) continue;
if (sims.find(Edge(u1, find(nbr), 0.f)) != sims.end()) {
sims.erase(sims.find(Edge(u1, find(nbr), 0.f)));
}
}
for (auto nbr : u2->neighbours) {
assert(u2->parent == u2);
if (u2 == find(nbr)) continue;
if (sims.find(Edge(u2, find(nbr), 0.f)) != sims.end()) {
sims.erase(sims.find(Edge(u2, find(nbr), 0.f)));
}
}
auto merged = merge(u1, u2);
for (auto nbr : merged->neighbours) {
Union *other = find(nbr);
if (other == merged) continue;
float score_size =1. - (merged->size + other->size) / double(img.cols * img.rows);
float score_texture = 0.f;
for (int i = 0; i < 8; i++) {
score_texture += merged->hist[i] * other->hist[i];
}
float sim = score_size + score_texture;
sims.emplace(merged, other, sim);
}
if (cnt % 100 == 0) {
showUnions(unions, img.rows, img.cols);
}
}
return 0;
}
| 34 | 141 | 0.504011 | qq456cvb |
6df4642fad4bd0d1a0539e5584fc6111a57541aa | 2,658 | cpp | C++ | modules/gin_network/3rdparty/liboauthcpp/src/urlencode.cpp | christofmuc/Gin | 8bedff1fd4db8452c56e220dcfae17dfae8825ac | [
"BSD-3-Clause"
] | 112 | 2018-01-29T09:36:00.000Z | 2022-03-30T21:27:56.000Z | modules/gin_network/3rdparty/liboauthcpp/src/urlencode.cpp | christofmuc/Gin | 8bedff1fd4db8452c56e220dcfae17dfae8825ac | [
"BSD-3-Clause"
] | 19 | 2018-02-09T22:27:50.000Z | 2022-01-31T22:43:53.000Z | modules/gin_network/3rdparty/liboauthcpp/src/urlencode.cpp | christofmuc/Gin | 8bedff1fd4db8452c56e220dcfae17dfae8825ac | [
"BSD-3-Clause"
] | 20 | 2018-05-03T03:10:00.000Z | 2022-03-24T12:12:36.000Z | #include "urlencode.h"
#include <cassert>
#include <sstream>
#include <iomanip>
inline bool isUnreserved(char c)
{
switch (c)
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '-': case '.': case '_': case '~':
return true;
default:
return false;
}
}
inline bool isSubDelim(char c)
{
switch (c)
{
case '!': case '$': case '&': case '\'': case '(':
case ')': case '*': case '+': case ',': case ';':
case '=':
return true;
default:
return false;
}
}
std::string char2hex( char dec )
{
char dig1 = (dec&0xF0)>>4;
char dig2 = (dec&0x0F);
if ( 0<= dig1 && dig1<= 9) dig1+=48; //0,48 in ascii
if (10<= dig1 && dig1<=15) dig1+=65-10; //A,65 in ascii
if ( 0<= dig2 && dig2<= 9) dig2+=48;
if (10<= dig2 && dig2<=15) dig2+=65-10;
std::string r;
r.append( &dig1, 1);
r.append( &dig2, 1);
return r;
}
std::string urlencode( const std::string &s, URLEncodeType enctype)
{
std::stringstream escaped;
std::string::const_iterator itStr = s.begin();
for (; itStr != s.end(); ++itStr)
{
char c = *itStr;
// Unreserved chars - never percent-encoded
if (isUnreserved(c))
{
escaped << c;
continue;
}
// Further on, the encoding depends on the context (where in the
// URI we are, what type of URI, and which character).
switch (enctype)
{
case URLEncode_Path:
if (isSubDelim(c))
{
escaped << c;
continue;
}
/* fall-through */
case URLEncode_Everything:
escaped << '%' << char2hex(c);
break;
default:
assert(false && "Unknown urlencode type");
break;
}
}
return escaped.str();
}
| 25.557692 | 72 | 0.455606 | christofmuc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.