hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5321df21a41c8bbe9a19670446cb6a24a27ca34c
| 8,022
|
hpp
|
C++
|
KFR/include/kfr/dsp/oscillators.hpp
|
Asifadam93/FiltreMusical
|
dcd53bc41934f219fb9b3d5aef281099fb572a49
|
[
"BSD-3-Clause"
] | null | null | null |
KFR/include/kfr/dsp/oscillators.hpp
|
Asifadam93/FiltreMusical
|
dcd53bc41934f219fb9b3d5aef281099fb572a49
|
[
"BSD-3-Clause"
] | null | null | null |
KFR/include/kfr/dsp/oscillators.hpp
|
Asifadam93/FiltreMusical
|
dcd53bc41934f219fb9b3d5aef281099fb572a49
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* Copyright (C) 2016 D Levin (http://www.kfrlib.com)
* This file is part of KFR
*
* KFR is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KFR 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 KFR.
*
* If GPL is not suitable for your project, you must purchase a commercial license to use KFR.
* Buying a commercial license is mandatory as soon as you develop commercial activities without
* disclosing the source code of your own applications.
* See http://www.kfrlib.com for details.
*/
#pragma once
#include "../base/basic_expressions.hpp"
#include "../base/sin_cos.hpp"
namespace kfr
{
template <typename T>
auto jaehne(T magn, size_t size)
{
return typed<T>(magn * sin(c_pi<T, 1, 2> * sqr(linspace(T(0), T(size), size, false)) / size), size);
}
template <typename T>
auto swept(T magn, size_t size)
{
return typed<T>(
magn * sin(c_pi<T, 1, 4> * sqr(sqr(linspace(T(0), T(size), size, false)) / sqr(T(size))) * T(size)),
size);
}
namespace intrinsics
{
template <typename T>
KFR_SINTRIN T rawsine(T x)
{
return intrinsics::fastsin(x * c_pi<T, 2>);
}
template <typename T>
KFR_SINTRIN T sinenorm(T x)
{
return intrinsics::rawsine(fract(x));
}
template <typename T>
KFR_SINTRIN T sine(T x)
{
return intrinsics::sinenorm(c_recip_pi<T, 1, 2> * x);
}
template <typename T>
KFR_SINTRIN T rawsquare(T x)
{
return select(x < T(0.5), T(1), -T(1));
}
template <typename T>
KFR_SINTRIN T squarenorm(T x)
{
return intrinsics::rawsquare(fract(x));
}
template <typename T>
KFR_SINTRIN T square(T x)
{
return intrinsics::squarenorm(c_recip_pi<T, 1, 2> * x);
}
template <typename T>
KFR_SINTRIN T rawsawtooth(T x)
{
return T(1) - 2 * x;
}
template <typename T>
KFR_SINTRIN T sawtoothnorm(T x)
{
return intrinsics::rawsawtooth(fract(x));
}
template <typename T>
KFR_SINTRIN T sawtooth(T x)
{
return intrinsics::sawtoothnorm(c_recip_pi<T, 1, 2> * x);
}
template <typename T>
KFR_SINTRIN T isawtoothnorm(T x)
{
return T(-1) + 2 * fract(x + 0.5);
}
template <typename T>
KFR_SINTRIN T isawtooth(T x)
{
return intrinsics::isawtoothnorm(c_recip_pi<T, 1, 2> * x);
}
template <typename T>
KFR_SINTRIN T rawtriangle(T x)
{
return 1 - abs(4 * x - 2);
}
template <typename T>
KFR_SINTRIN T trianglenorm(T x)
{
return intrinsics::rawtriangle(fract(x + 0.25));
}
template <typename T>
KFR_SINTRIN T triangle(T x)
{
return intrinsics::trianglenorm(c_recip_pi<T, 1, 2> * x);
}
}
KFR_I_FN(rawsine)
KFR_I_FN(sine)
KFR_I_FN(sinenorm)
KFR_I_FN(rawsquare)
KFR_I_FN(square)
KFR_I_FN(squarenorm)
KFR_I_FN(rawtriangle)
KFR_I_FN(triangle)
KFR_I_FN(trianglenorm)
KFR_I_FN(rawsawtooth)
KFR_I_FN(sawtooth)
KFR_I_FN(sawtoothnorm)
KFR_I_FN(isawtooth)
KFR_I_FN(isawtoothnorm)
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 rawsine(const T1& x)
{
return intrinsics::rawsine(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::rawsine, E1> rawsine(E1&& x)
{
return { fn::rawsine(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 sine(const T1& x)
{
return intrinsics::sine(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::sine, E1> sine(E1&& x)
{
return { fn::sine(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 sinenorm(const T1& x)
{
return intrinsics::sinenorm(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::sinenorm, E1> sinenorm(E1&& x)
{
return { fn::sinenorm(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 rawsquare(const T1& x)
{
return intrinsics::rawsquare(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::rawsquare, E1> rawsquare(E1&& x)
{
return { fn::rawsquare(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 square(const T1& x)
{
return intrinsics::square(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::square, E1> square(E1&& x)
{
return { fn::square(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 squarenorm(const T1& x)
{
return intrinsics::squarenorm(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::squarenorm, E1> squarenorm(E1&& x)
{
return { fn::squarenorm(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 rawtriangle(const T1& x)
{
return intrinsics::rawtriangle(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::rawtriangle, E1> rawtriangle(E1&& x)
{
return { fn::rawtriangle(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 triangle(const T1& x)
{
return intrinsics::triangle(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::triangle, E1> triangle(E1&& x)
{
return { fn::triangle(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 trianglenorm(const T1& x)
{
return intrinsics::trianglenorm(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::trianglenorm, E1> trianglenorm(E1&& x)
{
return { fn::trianglenorm(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 rawsawtooth(const T1& x)
{
return intrinsics::rawsawtooth(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::rawsawtooth, E1> rawsawtooth(E1&& x)
{
return { fn::rawsawtooth(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 sawtooth(const T1& x)
{
return intrinsics::sawtooth(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::sawtooth, E1> sawtooth(E1&& x)
{
return { fn::sawtooth(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 sawtoothnorm(const T1& x)
{
return intrinsics::sawtoothnorm(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::sawtoothnorm, E1> sawtoothnorm(E1&& x)
{
return { fn::sawtoothnorm(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 isawtooth(const T1& x)
{
return intrinsics::isawtooth(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::isawtooth, E1> isawtooth(E1&& x)
{
return { fn::isawtooth(), std::forward<E1>(x) };
}
template <typename T1, KFR_ENABLE_IF(is_numeric<T1>::value)>
KFR_INTRIN T1 isawtoothnorm(const T1& x)
{
return intrinsics::isawtoothnorm(x);
}
template <typename E1, KFR_ENABLE_IF(is_input_expression<E1>::value)>
KFR_INTRIN internal::expression_function<fn::isawtoothnorm, E1> isawtoothnorm(E1&& x)
{
return { fn::isawtoothnorm(), std::forward<E1>(x) };
}
}
| 28.856115
| 108
| 0.721516
|
Asifadam93
|
5321f099bf6f9ded7e3b350abe66a8c9345c54b7
| 1,472
|
cpp
|
C++
|
lib/lane/src/Utils/FilesystemWindows.cpp
|
calhewitt/LANE
|
412c3d465e6a459714f7a4a7ca4de30e571e0220
|
[
"BSD-2-Clause"
] | null | null | null |
lib/lane/src/Utils/FilesystemWindows.cpp
|
calhewitt/LANE
|
412c3d465e6a459714f7a4a7ca4de30e571e0220
|
[
"BSD-2-Clause"
] | null | null | null |
lib/lane/src/Utils/FilesystemWindows.cpp
|
calhewitt/LANE
|
412c3d465e6a459714f7a4a7ca4de30e571e0220
|
[
"BSD-2-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
/// \file FilesystemWindows.cpp
/// \author Hector Stalker <hstalker0@gmail.com>
/// \version 0.1
///
/// \brief Cross-platform filesystem handling code - Windows specific
///
/// \copyright Copyright (c) 2014, Hector Stalker. All rights reserved.
/// This file is under the Simplified (2-clause) BSD license
/// For conditions of distribution and use, see:
/// http://opensource.org/licenses/BSD-2-Clause
/// or read the 'LICENSE.md' file distributed with this code
#include <vector>
#include <string>
#include <windows.h>
#include <tchar.h>
#include "Utils/Filesystem.hpp"
namespace lane {
namespace utils {
std::vector<std::string> getDirectoryContents(
const std::string& directory
) noexcept {
std::vector<std::string> fileList;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Find the first file in the directory.
hFind = FindFirstFile((TCHAR*)(directory + "/*").c_str(), &ffd);
// Loop over the rest of the files
if (hFind != INVALID_HANDLE_VALUE) {
do {
std::string path = ffd.cFileName;
// Don't add current directory marker and previous directory marker
if (path != "." && path != "..") {
fileList.push_back(path);
}
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
return fileList;
}
} // utils
} // lane
| 28.862745
| 79
| 0.601902
|
calhewitt
|
5322a7ecf129c7d181d3f747bcab653342de468d
| 12,344
|
cc
|
C++
|
src/applications/dns/DNSServerBase.cc
|
saenridanra/inet-dns-extension
|
1fa452792f954297f2dc7ede3b699e73ca17c0c1
|
[
"MIT"
] | 1
|
2015-04-03T15:18:52.000Z
|
2015-04-03T15:18:52.000Z
|
src/applications/dns/DNSServerBase.cc
|
saenridanra/inet-dns-extension
|
1fa452792f954297f2dc7ede3b699e73ca17c0c1
|
[
"MIT"
] | null | null | null |
src/applications/dns/DNSServerBase.cc
|
saenridanra/inet-dns-extension
|
1fa452792f954297f2dc7ede3b699e73ca17c0c1
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2014-2015 Andreas Rain
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 "DNSServerBase.h"
Define_Module(DNSServerBase);
void DNSServerBase::initialize(int stage)
{
if (stage == inet::INITSTAGE_LOCAL)
{
cSimpleModule::initialize(stage);
// Initialize gates
out.setOutputGate(gate("udpOut"));
out.bind(DNS_PORT);
receivedQueries = 0;
}
else if (stage == inet::INITSTAGE_LAST)
{
rootServers = inet::L3AddressResolver().resolve(cStringTokenizer(par("root_servers")).asVector());
}
}
void DNSServerBase::handleMessage(cMessage *msg)
{
int isDNS = 0;
int isQR = 0;
std::shared_ptr<INETDNS::Query> query;
DNSPacket* response;
// Check if we received a query
if (msg->arrivedOn("udpIn"))
{
if ((isDNS = INETDNS::isDNSpacket((cPacket*) msg)))
{
if ((isQR = INETDNS::isQueryOrResponse((cPacket*) msg)) == 0)
{
query = INETDNS::resolveQuery((cPacket*) msg);
receivedQueries++;
cPacket *pk = check_and_cast<cPacket *>(msg);
inet::UDPDataIndication *ctrl = check_and_cast<inet::UDPDataIndication *>(pk->getControlInfo());
inet::L3Address srcAddress = ctrl->getSrcAddr();
query->src_address = srcAddress.str();
response = handleQuery(query);
if (response == NULL)
{ // only happens if recursive resolving was initiated
delete msg;
return;
}
// and send the response to the source address
sendResponse(response, srcAddress);
}
else
{
// Just got a response, lets see if its an answer fitting one of
// the queries we need to resolved.
response = handleRecursion((DNSPacket*) msg);
if (response != NULL)
{
// this was the final answer, i.e.
// get the original packet and the src addr
int id = ((DNSPacket*) msg)->getId();
std::shared_ptr<INETDNS::CachedQuery> cq = get_query_from_cache(id);
inet::L3Address addr = inet::L3AddressResolver().resolve(cq->query->src_address.c_str());
// free cached query data
remove_query_from_cache(id, cq);
// we're not an authority, set it here.
sendResponse(response, addr);
}
}
}
}
delete msg;
}
DNSPacket* DNSServerBase::handleRecursion(DNSPacket* packet)
{
// first check if we have a query id that belongs to this packet
// and the answer relates to the query
DNSPacket* response;
if (!queryCache.count(packet->getId()))
{
return NULL; // we do not have a query that belongs to this key
}
std::shared_ptr<INETDNS::CachedQuery> cq = queryCache[packet->getId()];
std::shared_ptr<INETDNS::Query> original_query = cq->query;
// first check, see if there are actually answers
if (DNS_HEADER_AA(packet->getOptions()) && packet->getAncount() > 0)
{
// we have what we looked for, return
std::string msg_name = std::string("dns_response#") + std::to_string(original_query->id);
response = INETDNS::createResponse(msg_name, 1, packet->getAncount(), packet->getNscount(),
packet->getArcount(), original_query->id, DNS_HEADER_OPCODE(original_query->options), 0,
DNS_HEADER_RD(original_query->options), 1, 0);
short i;
for (i = 0; i < cq->query->qdcount; i++)
{
INETDNS::appendQuestion(response, INETDNS::copyDnsQuestion(&cq->query->questions[i]), i);
}
std::string bubble_popup = "";
for (i = 0; i < packet->getAncount(); i++)
{
// store the response in the cache
if (responseCache)
{
// check if the record is not an A or AAAA record
if (packet->getAnswers(i).rtype != DNS_TYPE_VALUE_A
&& packet->getAnswers(i).rtype != DNS_TYPE_VALUE_AAAA)
{
//create a copy and put it into the cache
std::shared_ptr<INETDNS::DNSRecord> r = INETDNS::copyDnsRecord(&(packet->getAnswers(i)));
#ifdef DEBUG_ENABLED
// put the record into the cache
bubble_popup.append("New cache entry:\n");
bubble_popup.append(r->rname.c_str());
bubble_popup.append(":");
bubble_popup.append(INETDNS::getTypeStringForValue(r->rtype));
bubble_popup.append(":");
bubble_popup.append(INETDNS::getClassStringForValue(r->rclass));
bubble_popup.append("\nData: ");
bubble_popup.append(r->strdata.c_str());
bubble_popup.append("\n---------\n");
#endif
responseCache->put_into_cache(r);
}
}
INETDNS::appendAnswer(response, INETDNS::copyDnsRecord(&packet->getAnswers(i)), i);
}
#ifdef DEBUG_ENABLED
if (bubble_popup != "")
{
EV << bubble_popup.c_str();
this->getParentModule()->bubble(bubble_popup.c_str());
}
#endif
if (responseCache && original_query->questions[0].qname == packet->getQuestions(0).qname)
{
// we have a mismatch in the queries, this means we followed a CNAME chain
// and used the end of chain to query the server, hence we need to append
// the CNAME chain
std::string cnhash = original_query->questions[0].qname + ":" + DNS_TYPE_STR_CNAME + ":" +
DNS_CLASS_STR_IN;
std::list<std::string> hashes = responseCache->get_matching_hashes(cnhash);
int num_hashes = hashes.size();
// reset size of answers to ancount + hashes length
response->setNumAnswers(response->getAncount() + num_hashes);
response->setAncount(response->getAncount() + num_hashes);
int pos = packet->getAncount();
for(auto it = hashes.begin(); it != hashes.end(); it++)
{
// use the hash to get the corresponding entry
std::string tmp = (std::string) *it;
std::list<std::shared_ptr<DNSRecord>> records = responseCache->get_from_cache(tmp);
if (!records.empty())
break;
// list should not be greater one otherwise there is a collision
if (records.size() > 1)
{
responseCache->remove_from_cache(tmp);
break;
}
// only one record, extract data into tmp
if ((*(records.begin()))->rtype == DNS_TYPE_VALUE_CNAME)
{
// append record to the section
INETDNS::appendAnswer(response, INETDNS::copyDnsRecord(*(records.begin())),
pos);
pos++;
}
}
}
for (i = 0; i < packet->getNscount(); i++)
{
INETDNS::appendAuthority(response, INETDNS::copyDnsRecord(&packet->getAuthorities(i)), i);
}
for (i = 0; i < packet->getArcount(); i++)
{
INETDNS::appendAdditional(response, INETDNS::copyDnsRecord(&packet->getAdditional(i)), i);
}
return response;
}
else if (DNS_HEADER_AA(packet->getOptions()) && packet->getAncount() == 0)
{
// return the entry not found response
std::string msg_name = "dns_response#" + std::to_string(original_query->id);
response = INETDNS::createResponse(msg_name, 1, 0, 0, 0, original_query->id,
DNS_HEADER_OPCODE(original_query->options), 1, DNS_HEADER_RD(original_query->options), 1, 3);
for (int i = 0; i < cq->query->qdcount; i++)
{
INETDNS::appendQuestion(response, INETDNS::copyDnsQuestion(&cq->query->questions[i]), i);
}
return response; // return the response with no entry found..
}
else if (packet->getNscount() > 0 && packet->getArcount() > 0 && !DNS_HEADER_AA(packet->getOptions()))
{
// we have an answer for a query
// pick one at random and delegate the question
int p = intrand(packet->getNscount());
std::shared_ptr<DNSRecord> r = INETDNS::copyDnsRecord(&packet->getAdditional(p));
// query the name server for our original query
std::string msg_name = "dns_query#" + std::to_string(cq->internal_id) + std::string("--recursive");
DNSPacket *query = INETDNS::createQuery(msg_name, packet->getQuestions(0).qname, DNS_CLASS_IN,
packet->getQuestions(0).qtype, cq->internal_id, 1);
// Resolve the ip address for the record
inet::L3Address address = inet::L3AddressResolver().resolve(r->strdata.c_str());
if (!address.isUnspecified())
sendResponse(query, address);
return NULL; // since this packet is fine we pass it upwards
}
else if (packet->getNscount() > 0 && !DNS_HEADER_AA(packet->getOptions()))
{
// TODO: no ar record, we need to start at the beginning with this reference..
return NULL;
}
else
{
// something went wrong, return a server failure query
std::string msg_name = "dns_response#" + std::to_string(original_query->id);
response = INETDNS::createResponse(msg_name, 1, 0, 0, 0, original_query->id,
DNS_HEADER_OPCODE(original_query->options), 0, DNS_HEADER_RD(original_query->options), 1, 2);
return response; // return the response with no entry found..
}
return NULL;
}
int DNSServerBase::remove_query_from_cache(int id, std::shared_ptr<INETDNS::CachedQuery> cq)
{
queryCache.erase(queryCache.find(id));
return 1;
}
std::shared_ptr<INETDNS::CachedQuery> DNSServerBase::get_query_from_cache(int id)
{
std::shared_ptr<INETDNS::CachedQuery> q = queryCache[id];
return q;
}
int DNSServerBase::store_in_query_cache(int id, std::shared_ptr<INETDNS::Query> query)
{
// store the query in the cache...
std::shared_ptr<INETDNS::CachedQuery> q(new INETDNS::CachedQuery());
q->internal_id = id;
q->query = query;
queryCache[id] = q;
return 1;
}
DNSPacket* DNSServerBase::handleQuery(std::shared_ptr<INETDNS::Query> query)
{
return NULL;
}
void DNSServerBase::sendResponse(DNSPacket *response, inet::L3Address returnAddress)
{
if (!returnAddress.isUnspecified())
{
if (response == NULL)
{
std::cout << "Bad response\n" << std::endl;
return;
}
response->setByteLength(INETDNS::estimateDnsPacketSize(response));
out.sendTo(response, returnAddress, DNS_PORT);
}
else
std::cout << "Missing return address\n" << std::endl;
}
DNSPacket* DNSServerBase::unsupportedOperation(std::shared_ptr<INETDNS::Query> q)
{
// TODO: return unsupported packet.
return NULL;
}
| 36.412979
| 112
| 0.590327
|
saenridanra
|
5323722b0462f8acc3b0e240d43fce4ca889afa4
| 228
|
cpp
|
C++
|
Engine/Source/Runtime/SlateCore/Private/Fonts/FontProviderInterface.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | 1
|
2022-01-29T18:36:12.000Z
|
2022-01-29T18:36:12.000Z
|
Engine/Source/Runtime/SlateCore/Private/Fonts/FontProviderInterface.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
Engine/Source/Runtime/SlateCore/Private/Fonts/FontProviderInterface.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Fonts/FontProviderInterface.h"
UFontProviderInterface::UFontProviderInterface(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
| 25.333333
| 91
| 0.815789
|
windystrife
|
5323936abff33578169018a145c93e9c23b2d8e8
| 2,309
|
cpp
|
C++
|
src/udp_interface.cpp
|
storypku/network_interface
|
50906c457ff6ed9684cfa3167b229124aabc6594
|
[
"MIT"
] | 1
|
2020-06-02T08:52:03.000Z
|
2020-06-02T08:52:03.000Z
|
src/udp_interface.cpp
|
storypku/network_interface
|
50906c457ff6ed9684cfa3167b229124aabc6594
|
[
"MIT"
] | null | null | null |
src/udp_interface.cpp
|
storypku/network_interface
|
50906c457ff6ed9684cfa3167b229124aabc6594
|
[
"MIT"
] | null | null | null |
/*
* Unpublished Copyright (c) 2009-2017 AutonomouStuff, LLC, All Rights Reserved.
*
* This file is part of the network_interface ROS 1.0 driver which is released under the MIT license.
* See file LICENSE included with this software or go to https://opensource.org/licenses/MIT for full license details.
*/
#include <network_interface.h>
using namespace AS::Network; // NOLINT
using boost::asio::ip::udp;
// Default constructor.
UDPInterface::UDPInterface() :
socket_(io_service_)
{
}
// Default destructor.
UDPInterface::~UDPInterface()
{
}
return_statuses UDPInterface::open(const char *ip_address, const int &port)
{
if (socket_.is_open())
return OK;
std::stringstream sPort;
sPort << port;
udp::resolver res(io_service_);
udp::resolver::query query(udp::v4(), ip_address, sPort.str());
sender_endpoint_ = *res.resolve(query);
boost::system::error_code ec;
socket_.connect(sender_endpoint_, ec);
if (ec.value() == boost::system::errc::success)
{
return OK;
}
else if (ec.value() == boost::asio::error::invalid_argument)
{
return BAD_PARAM;
}
else
{
close();
return INIT_FAILED;
}
}
return_statuses UDPInterface::close()
{
if (!socket_.is_open())
return SOCKET_CLOSED;
boost::system::error_code ec;
socket_.close(ec);
if (ec.value() == boost::system::errc::success)
{
return OK;
}
else
{
return CLOSE_FAILED;
}
}
bool UDPInterface::is_open()
{
return socket_.is_open();
}
return_statuses UDPInterface::read(unsigned char *msg,
const size_t &buf_size,
size_t &bytes_read)
{
if (!socket_.is_open())
return SOCKET_CLOSED;
boost::system::error_code ec;
bytes_read = socket_.receive_from(boost::asio::buffer(msg, buf_size), sender_endpoint_, 0, ec);
if (ec.value() == boost::system::errc::success)
{
return OK;
}
else
{
return READ_FAILED;
}
}
return_statuses UDPInterface::write(unsigned char *msg, const size_t &msg_size)
{
if (!socket_.is_open())
return SOCKET_CLOSED;
boost::system::error_code ec;
socket_.send_to(boost::asio::buffer(msg, msg_size), sender_endpoint_, 0, ec);
if (ec.value() == boost::system::errc::success)
{
return OK;
}
else
{
return WRITE_FAILED;
}
}
| 20.433628
| 117
| 0.662191
|
storypku
|
5325af0d311e39200f5fb2cea8688113ecadfdb6
| 1,094
|
cpp
|
C++
|
search_engine/process_queries.cpp
|
oleg-nazarov/cpp-yandex-praktikum
|
a09781c198b0aff469c4d1175c91d72800909bf2
|
[
"MIT"
] | 1
|
2022-03-15T19:01:03.000Z
|
2022-03-15T19:01:03.000Z
|
search_engine/process_queries.cpp
|
oleg-nazarov/cpp-yandex-praktikum
|
a09781c198b0aff469c4d1175c91d72800909bf2
|
[
"MIT"
] | 1
|
2022-03-15T19:11:59.000Z
|
2022-03-15T19:11:59.000Z
|
search_engine/process_queries.cpp
|
oleg-nazarov/cpp-yandex-praktikum
|
a09781c198b0aff469c4d1175c91d72800909bf2
|
[
"MIT"
] | null | null | null |
#include "process_queries.h"
#include <algorithm>
#include <execution>
#include <iterator>
#include <string>
#include <vector>
#include "document.h"
#include "search_server.h"
std::vector<std::vector<Document>> ProcessQueries(const SearchServer& search_server, const std::vector<std::string>& queries) {
std::vector<std::vector<Document>> documents(queries.size());
std::transform(
std::execution::par,
queries.begin(), queries.end(),
documents.begin(),
[&search_server](const std::string& query) {
return search_server.FindTopDocuments(query);
});
return documents;
}
std::vector<Document> ProcessQueriesJoined(const SearchServer& search_server, const std::vector<std::string>& queries) {
auto documents = ProcessQueries(search_server, queries);
std::vector<Document> joined_documents;
for (auto& doc : documents) {
joined_documents.insert(
joined_documents.end(),
std::make_move_iterator(doc.begin()), std::make_move_iterator(doc.end()));
}
return joined_documents;
}
| 28.789474
| 127
| 0.680073
|
oleg-nazarov
|
5328d7fc5df06a60f6df800f03b5e2d992ad864a
| 30,734
|
cpp
|
C++
|
src/fs/Formats/FAT/FAT32/FATPartition.cpp
|
Unified-Projects/Unified-OS
|
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
|
[
"BSD-2-Clause"
] | null | null | null |
src/fs/Formats/FAT/FAT32/FATPartition.cpp
|
Unified-Projects/Unified-OS
|
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
|
[
"BSD-2-Clause"
] | null | null | null |
src/fs/Formats/FAT/FAT32/FATPartition.cpp
|
Unified-Projects/Unified-OS
|
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
|
[
"BSD-2-Clause"
] | null | null | null |
#include <fs/Formats/FAT/FAT32/FATPartition.h>
#include <fs/Formats/FAT/FAT32/Directory.h>
#include <fs/Formats/FAT/FAT32/FAT.h>
using namespace UnifiedOS;
using namespace UnifiedOS::FileSystem;
using namespace UnifiedOS::FileSystem::FAT32;
#include <common/cstring.h> //Needed for path interaction
Fat32Partition::Fat32Partition(GPT::GPTPartitonEntry Partition, DiskDevice* disk, void* BootSector)
: PartitionDevice(Partition.StartLBA, Partition.EndLBA, Partition.TypeGUID, Partition.PartitionGUID, disk),
MBR(rMBR)
{
//Save the boot sector
rMBR = *((MBR::FAT32_MBR*)BootSector);
//Read the flags for the drive
rFlags.ReadOnly = (Partition.Flags >> 60 == 1);
rFlags.Hidden = (Partition.Flags >> 62 == 1);
rFlags.AutoMount = !(Partition.Flags >> 63 == 1);
//Set the format
rFormat = PARTITION_FAT_32;
//Read Root Directory to get the volume name
FATClusterEntries* RootClusters = ScanForEntries(this, 0);
//Disk read check
if(RootClusters){
DirectoryEntryListing* RootDirectory = ReadDirectoryEntries(this, RootClusters);
if(RootDirectory){
//If LongFileName
if(RootDirectory->Directories.get_at(0)->LFNE.size()){
}
else{//Normal file name
//Setup name location
PartitionName = new char[11];
//Load data
Memory::memcpy(PartitionName, &(RootDirectory->Directories.get_at(0)->RDE.FileName), 11);
}
delete RootDirectory;
}
delete RootClusters;
}
}
GeneralFile Fat32Partition::ResolveFile(const char* Path){
//Create the file
GeneralFile File = {};
//Check if the set Mount is correct
if(Path[0] == Mount + 0x41){
//Find out the length of the path
size_t Length = strlen(Path);
//Subdirectories
uint64_t Subdirectories = 0;
Vector<uint64_t> SectionSpacing = {};
uint64_t CurrentSpacing = 0;
//Calculate how many subdirectories are in the path
for(int i = 0; i < Length; i++){
if(Path[i] == '/' || Path[i] == '\\'){
Subdirectories++;
//Add spacing
SectionSpacing.add_back(CurrentSpacing);
CurrentSpacing = 0;
}
else{
CurrentSpacing++;
}
}
//Add spacing
SectionSpacing.add_back(CurrentSpacing);
CurrentSpacing = 0;
//Remove first entry because its not a part of the filepath
SectionSpacing.erase(0);
//Remove RootDirectory as a subdir
Subdirectories -= 1;
//For memory comparison
uint64_t OffsetIntoPath = 3; //Default to 3 for "A:/"
//if it is a directory we want to store the new cluster
uint32_t NewClusterPosition = 0;
//First iterate over root directory
//Read Root Directory to get the volume name
FATClusterEntries* RootClusters = ScanForEntries(this, NewClusterPosition);
//Disk read check
if(RootClusters){
DirectoryEntryListing* RootDirectory = ReadDirectoryEntries(this, RootClusters);
if(RootDirectory){
//Look over entries
for(int i = 0; i < RootDirectory->Directories.size(); i++){
//To Save time compare if it should be a directory OR NOT
if((Subdirectories > 0 && CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false)) ||
(Subdirectories == 0 && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false))){
//Because the same process for creaing the file is here so I will make a bool for both to use
bool CorrectEntry = false;
//File name
char* EntryName = nullptr;
if(RootDirectory->Directories.get_at(i)->LFNE.size() > 0){//Compare as a long file name entry
//Creation of Long File Name From Entries
//Name Size
uint64_t NameSize = 0;
//Skipping character
bool Skip = false;
//Loop over LFNE entries and get the length of the s
for(int e = RootDirectory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
}
//Reset Skip
Skip = false;
//Check lengths
if(NameSize == SectionSpacing.get_at(0)){ //Run further comparsions
EntryName = new char[NameSize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data into EntryName
for(int e = RootDirectory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x];
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x];
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x];
}
Skip = !Skip;
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, NameSize)){
CorrectEntry = true;
}
}
}
else{//Root Directory Entry
//For size comparison
uint8_t EntrySize = 0;
//Extention dot
if(!CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
EntrySize += 1;
}
//Load the filename
for(int e = 0; e < 11; e++){
if(RootDirectory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
EntrySize++;
}
}
//Check lengths
if(EntrySize == SectionSpacing.get_at(0)){ //Run further comparsions
EntryName = new char[EntrySize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data
for(int e = 0; e < 11 && PosInName < EntrySize; e++){
if(RootDirectory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
if(RootDirectory->Directories.get_at(i)->RDE.FileName[e] >= 0x41 && RootDirectory->Directories.get_at(i)->RDE.FileName[e] <= 0x5A)
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->RDE.FileName[e]+ 0x20;
else{
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->RDE.FileName[e];
}
}
else if(!CountedExtention && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
CountedExtention = true;
//Add the decimal place
EntryName[PosInName++] = '.';
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, EntrySize)){
CorrectEntry = true;
}
}
}
//File creation
if(CorrectEntry){
//Cluster
NewClusterPosition = ((RootDirectory->Directories.get_at(i)->RDE.High2BytesOfAddressOfFirstCluster << 16) & 0xFF00) |
RootDirectory->Directories.get_at(i)->RDE.Low2BytesOfAddressOfFirstCluster;
//Only entry needed (File is found)
if(Subdirectories == 0){
//Sort out the name
uint16_t ExtentionPos = 0;
//Find the position of the start of the Extention
for(int x = SectionSpacing.get_at(0) - 1; x >= 0; x--){
if(EntryName[x] == '.'){
ExtentionPos = x;
break;
}
}
if(ExtentionPos){
//Copy the name data
File.Name = new uint8_t[ExtentionPos];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), ExtentionPos);
//Copy the extention
File.Extention = new uint8_t[SectionSpacing.get_at(0) - ExtentionPos - 1];
Memory::memcpy(File.Extention, ((uint8_t*)EntryName) + ExtentionPos + 1, SectionSpacing.get_at(0) - ExtentionPos - 1);
}
else{
File.Name = new uint8_t[SectionSpacing.get_at(0)];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), SectionSpacing.get_at(0));
}
//Path Setup
File.FullPath = new uint8_t[strlen(Path)];
Memory::memcpy(File.FullPath, Path, strlen(Path));
//Basic file info
File.FileSize = RootDirectory->Directories.get_at(i)->RDE.FileSize;
//Entries
FATClusterEntries* FatEntries = ScanForEntries(this, NewClusterPosition);
//Setup the secotrs
File.Sectors = new uint64_t[FatEntries->Entries.size()*MBR.SectorsPerCluster];
File.SectorCount = FatEntries->Entries.size()*MBR.SectorsPerCluster;
//Copy the sectors
for(int e = 0; e < FatEntries->Entries.size(); e++){
for(int s = 0; s < MBR.SectorsPerCluster; s++){
File.Sectors[(e * MBR.SectorsPerCluster) + s] = FatEntries->Entries.get_at(e) * MBR.SectorsPerCluster + s;
}
}
//Disk Setup
File.Disk = this;
//Attributes
File.Attributes.Hidden = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_HiddenM, false);
File.Attributes.Directory = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false);
File.Attributes.ReadOnly = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_Read_OnlyM, false);
File.Attributes.Archive = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_ArchiveM, false);
//Validation
File.Found = true;
//End
delete FatEntries;
delete RootDirectory;
delete RootClusters;
return File;
}
}
//Memory Freeing
if(EntryName)
delete EntryName;
}
}
delete RootDirectory;
}
else{ //Fail Prevention
delete RootClusters;
return File;
}
delete RootClusters;
}
else{ //Fail Prevention
return File;
}
//Now move onto any subdirectories
for(int d = 0; d < Subdirectories; d++){
//Offset the PathOffset
OffsetIntoPath += SectionSpacing.get_at(d) + 1;
//Read Directory to get the volume name
FATClusterEntries* DirectoryClusters = ScanForEntries(this, NewClusterPosition);
//Disk read check
if(DirectoryClusters){
DirectoryEntryListing* Directory = ReadDirectoryEntries(this, DirectoryClusters);
if(Directory){
//Look over entries
for(int i = 0; i < Directory->Directories.size(); i++){
//To Save time compare if it should be a directory OR NOT
if((Subdirectories > d + 1 && CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false)) ||
(Subdirectories == d + 1 && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false))){
//Because the same process for creaing the file is here so I will make a bool for both to use
bool CorrectEntry = false;
//File name
char* EntryName = nullptr;
if(Directory->Directories.get_at(i)->LFNE.size() > 0){//Compare as a long file name entry
//Creation of Long File Name From Entries
//Name Size
uint64_t NameSize = 0;
//Skipping character
bool Skip = false;
//Loop over LFNE entries and get the length of the s
for(int e = Directory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
}
//Reset Skip
Skip = false;
//Check lengths
if(NameSize == SectionSpacing.get_at(d+1)){ //Run further comparsions
EntryName = new char[NameSize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data into EntryName
for(int e = Directory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
EntryName[PosInName++] = Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x];
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
EntryName[PosInName++] = Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x];
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
EntryName[PosInName++] = Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x];
}
Skip = !Skip;
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, NameSize)){
CorrectEntry = true;
}
}
}
else{//Root Directory Entry
//For size comparison
uint8_t EntrySize = 0;
//Extention dot
if(!CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
EntrySize += 1;
}
//Load the filename
for(int e = 0; e < 11; e++){
if(Directory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
EntrySize++;
}
}
//Check lengths
if(EntrySize == SectionSpacing.get_at(d + 1)){ //Run further comparsions
EntryName = new char[EntrySize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data
for(int e = 0; e < 11 && PosInName < EntrySize; e++){
if(Directory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
if(Directory->Directories.get_at(i)->RDE.FileName[e] >= 0x41 && Directory->Directories.get_at(i)->RDE.FileName[e] <= 0x5A)
EntryName[PosInName++] = Directory->Directories.get_at(i)->RDE.FileName[e]+ 0x20;
else{
EntryName[PosInName++] = Directory->Directories.get_at(i)->RDE.FileName[e];
}
}
else if(!CountedExtention && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
CountedExtention = true;
//Add the decimal place
EntryName[PosInName++] = '.';
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, EntrySize)){
CorrectEntry = true;
}
}
}
//File creation
if(CorrectEntry){
//Cluster
NewClusterPosition = ((Directory->Directories.get_at(i)->RDE.High2BytesOfAddressOfFirstCluster << 16) & 0xFF00) |
Directory->Directories.get_at(i)->RDE.Low2BytesOfAddressOfFirstCluster;
//Only entry needed (File is found)
if(Subdirectories == d+1){
//Sort out the name
uint16_t ExtentionPos = 0;
//Find the position of the start of the Extention
for(int x = SectionSpacing.get_at(d+1) - 1; x >= 0; x--){
if(EntryName[x] == '.'){
ExtentionPos = x;
break;
}
}
if(ExtentionPos){
//Copy the name data
File.Name = new uint8_t[ExtentionPos];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), ExtentionPos);
//Copy the extention
File.Extention = new uint8_t[SectionSpacing.get_at(d+1) - ExtentionPos - 1];
Memory::memcpy(File.Extention, ((uint8_t*)EntryName) + ExtentionPos + 1, SectionSpacing.get_at(d+1) - ExtentionPos - 1);
}
else{
File.Name = new uint8_t[SectionSpacing.get_at(d+1)];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), SectionSpacing.get_at(d+1));
}
//Path Setup
File.FullPath = new uint8_t[strlen(Path)];
Memory::memcpy(File.FullPath, Path, strlen(Path));
//Basic file info
File.FileSize = Directory->Directories.get_at(i)->RDE.FileSize;
//Entries
FATClusterEntries* FatEntries = ScanForEntries(this, NewClusterPosition);
//Setup the secotrs
File.Sectors = new uint64_t[FatEntries->Entries.size()*MBR.SectorsPerCluster];
File.SectorCount = FatEntries->Entries.size()*MBR.SectorsPerCluster;
//Copy the sectors
for(int e = 0; e < FatEntries->Entries.size(); e++){
for(int s = 0; s < MBR.SectorsPerCluster; s++){
File.Sectors[(e * MBR.SectorsPerCluster) + s] = FatEntries->Entries.get_at(e) * MBR.SectorsPerCluster + s;
}
}
//Disk Setup
File.Disk = this;
//Attributes
File.Attributes.Hidden = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_HiddenM, false);
File.Attributes.Directory = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false);
File.Attributes.ReadOnly = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_Read_OnlyM, false);
File.Attributes.Archive = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_ArchiveM, false);
//Validation
File.Found = true;
//End
// delete FatEntries;
delete Directory;
delete DirectoryClusters;
return File;
}
}
//Memory Freeing
if(EntryName)
delete EntryName;
}
}
delete Directory;
}
else{ //Fail Prevention
delete DirectoryClusters;
return File;
}
delete DirectoryClusters;
}
else{ //Fail Prevention
return File;
}
}
}
//return
return File;
}
GeneralDirectory Fat32Partition::ResolveDir(const char* Path){
//Create the directory
GeneralDirectory Directory = {};
//return
return Directory;
}
| 52.179966
| 276
| 0.413874
|
Unified-Projects
|
53298cf97e74554425a7e2d3be0f025f32ae6125
| 1,608
|
cpp
|
C++
|
src/shared/variable.cpp
|
FoFabien/SF2DEngine
|
3d10964cbdae439584c10ab427ade394d720713f
|
[
"Zlib"
] | null | null | null |
src/shared/variable.cpp
|
FoFabien/SF2DEngine
|
3d10964cbdae439584c10ab427ade394d720713f
|
[
"Zlib"
] | null | null | null |
src/shared/variable.cpp
|
FoFabien/SF2DEngine
|
3d10964cbdae439584c10ab427ade394d720713f
|
[
"Zlib"
] | null | null | null |
#include "variable.hpp"
// globale variable
int32_t gVar[VARIABLE_COUNT];
int32_t sysVar[SYSTEM_VARIABLE_COUNT];
void initGlobaleVariable()
{
for(int32_t i = 0; i < VARIABLE_COUNT; ++i) gVar[i] = 0;
for(int32_t i = 0; i < SYSTEM_VARIABLE_COUNT; ++i) sysVar[i] = 0;
}
void resetGlobaleVariableAndString()
{
for(int32_t i = 0; i < VARIABLE_COUNT; ++i) gVar[i] = 0;
for(int32_t i = 0; i < STRING_COUNT; ++i) gStr[i].clear();
}
void storeFloat(const float &f, int32_t &v)
{
v = *((int32_t*)(&f));
}
float loadFloat(const int32_t &v)
{
return *((float*)(&v));
}
// globale string
std::string gStr[STRING_COUNT];
void updateGlobaleString(int32_t id)
{
if(id < 0)
{
for(int32_t i = 0; i < STRING_COUNT; ++i) updateGlobaleString(i);
return;
}
if(id > STRING_COUNT) return;
switch(id)
{
default: return;
}
}
std::string sysStr[SYSTEM_STRING_COUNT];
void updateSystemString(int32_t id)
{
if(id < 0)
{
for(int32_t i = 0; i < SYSTEM_STRING_COUNT; ++i) updateSystemString(i);
return;
}
if(id > SYSTEM_STRING_COUNT) return;
switch(id)
{
default: return;
}
}
// debug
#ifdef DEBUG_BUILD
int32_t dVar[10];
std::string dStr[10];
#endif
// ---------------------------------
// add specific global variable here
// ---------------------------------
// dungeon data
std::vector<std::vector<int8_t> > fov;
std::vector<int8_t> tile_grid;
void initDungeonData()
{
fov.clear();
while(fov.size() < DUNGEON_MAX_COUNT) fov.push_back(std::vector<int8_t>());
tile_grid.clear();
}
| 20.615385
| 79
| 0.600746
|
FoFabien
|
532be93864c9a79d5616e6dd14585049baf732c0
| 31,561
|
cpp
|
C++
|
src/vehicles/Plane.cpp
|
gameblabla/reeee3
|
1b6d0f742b1b6fb681756de702ed618e90361139
|
[
"Unlicense"
] | 2
|
2021-03-24T22:11:27.000Z
|
2021-05-07T06:51:04.000Z
|
src/vehicles/Plane.cpp
|
gameblabla/reeee3
|
1b6d0f742b1b6fb681756de702ed618e90361139
|
[
"Unlicense"
] | null | null | null |
src/vehicles/Plane.cpp
|
gameblabla/reeee3
|
1b6d0f742b1b6fb681756de702ed618e90361139
|
[
"Unlicense"
] | null | null | null |
#include "common.h"
#include "main.h"
#include "General.h"
#include "ModelIndices.h"
#include "FileMgr.h"
#include "Streaming.h"
#include "Replay.h"
#include "Camera.h"
#include "DMAudio.h"
#include "Wanted.h"
#include "Coronas.h"
#include "Particle.h"
#include "Explosion.h"
#include "World.h"
#include "HandlingMgr.h"
#include "Plane.h"
#include "MemoryHeap.h"
CPlaneNode *pPathNodes;
CPlaneNode *pPath2Nodes;
CPlaneNode *pPath3Nodes;
CPlaneNode *pPath4Nodes;
int32 NumPathNodes;
int32 NumPath2Nodes;
int32 NumPath3Nodes;
int32 NumPath4Nodes;
float TotalLengthOfFlightPath;
float TotalLengthOfFlightPath2;
float TotalLengthOfFlightPath3;
float TotalLengthOfFlightPath4;
float TotalDurationOfFlightPath;
float TotalDurationOfFlightPath2;
float TotalDurationOfFlightPath3;
float TotalDurationOfFlightPath4;
float LandingPoint;
float TakeOffPoint;
CPlaneInterpolationLine aPlaneLineBits[6];
float PlanePathPosition[3];
float OldPlanePathPosition[3];
float PlanePathSpeed[3];
float PlanePath2Position[3];
float PlanePath3Position;
float PlanePath4Position;
float PlanePath2Speed[3];
float PlanePath3Speed;
float PlanePath4Speed;
enum
{
CESNA_STATUS_NONE, // doesn't even exist
CESNA_STATUS_FLYING,
CESNA_STATUS_DESTROYED,
CESNA_STATUS_LANDED,
};
int32 CesnaMissionStatus;
int32 CesnaMissionStartTime;
CPlane *pDrugRunCesna;
int32 DropOffCesnaMissionStatus;
int32 DropOffCesnaMissionStartTime;
CPlane *pDropOffCesna;
CPlane::CPlane(int32 id, uint8 CreatedBy)
: CVehicle(CreatedBy)
{
CVehicleModelInfo *mi = (CVehicleModelInfo*)CModelInfo::GetModelInfo(id);
m_vehType = VEHICLE_TYPE_PLANE;
pHandling = mod_HandlingManager.GetHandlingData((tVehicleType)mi->m_handlingId);
SetModelIndex(id);
m_fMass = 100000000.0f;
m_fTurnMass = 100000000.0f;
m_fAirResistance = 0.9994f;
m_fElasticity = 0.05f;
bUsesCollision = false;
m_bHasBeenHit = false;
m_bIsDrugRunCesna = false;
m_bIsDropOffCesna = false;
SetStatus(STATUS_PLANE);
bIsBIGBuilding = true;
m_level = LEVEL_GENERIC;
#ifdef FIX_BUGS
m_isFarAway = false;
#endif
}
CPlane::~CPlane()
{
DeleteRwObject();
}
void
CPlane::SetModelIndex(uint32 id)
{
CVehicle::SetModelIndex(id);
}
void
CPlane::DeleteRwObject(void)
{
if(m_rwObject && RwObjectGetType(m_rwObject) == rpATOMIC){
m_matrix.Detach();
if(RwObjectGetType(m_rwObject) == rpATOMIC){ // useless check
RwFrame *f = RpAtomicGetFrame((RpAtomic*)m_rwObject);
RpAtomicDestroy((RpAtomic*)m_rwObject);
RwFrameDestroy(f);
}
m_rwObject = nil;
}
CEntity::DeleteRwObject();
}
// There's a LOT of copy and paste in here. Maybe this could be refactored somehow
void
CPlane::ProcessControl(void)
{
int i;
CVector pos;
// Explosion
if(m_bHasBeenHit){
// BUG: since this is all based on frames, you can skip the explosion processing when you go into the menu
if(GetModelIndex() == MI_AIRTRAIN){
int frm = CTimer::GetFrameCounter() - m_nFrameWhenHit;
if(frm == 20){
static int nFrameGen;
CRGBA colors[8];
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), 0);
colors[0] = CRGBA(0, 0, 0, 255);
colors[1] = CRGBA(224, 230, 238, 255);
colors[2] = CRGBA(224, 230, 238, 255);
colors[3] = CRGBA(0, 0, 0, 255);
colors[4] = CRGBA(224, 230, 238, 255);
colors[5] = CRGBA(0, 0, 0, 255);
colors[6] = CRGBA(0, 0, 0, 255);
colors[7] = CRGBA(224, 230, 238, 255);
CVector dir;
for(i = 0; i < 40; i++){
dir.x = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.y = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.z = CGeneral::GetRandomNumberInRange(0.0f, 2.0f);
int rotSpeed = CGeneral::GetRandomNumberInRange(10, 30);
if(CGeneral::GetRandomNumber() & 1)
rotSpeed = -rotSpeed;
int f = ++nFrameGen & 3;
CParticle::AddParticle(PARTICLE_HELI_DEBRIS, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), dir,
nil, CGeneral::GetRandomNumberInRange(0.1f, 1.0f),
colors[nFrameGen&7], rotSpeed, 0, f, 0);
}
}
if(frm >= 40 && frm <= 80 && frm & 1){
if(frm & 1){
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.y = frm - 40;
pos = GetMatrix() * pos;
}else{
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.y = 40 - frm;
pos = GetMatrix() * pos;
}
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, pos, 0);
}
if(frm == 60)
bRenderScorched = true;
if(frm == 82){
TheCamera.SetFadeColour(255, 255, 255);
TheCamera.Fade(0.0f, FADE_OUT);
TheCamera.ProcessFade();
TheCamera.Fade(1.0f, FADE_IN);
FlagToDestroyWhenNextProcessed();
}
}else{
int frm = CTimer::GetFrameCounter() - m_nFrameWhenHit;
if(frm == 20){
static int nFrameGen;
CRGBA colors[8];
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), 0);
colors[0] = CRGBA(0, 0, 0, 255);
colors[1] = CRGBA(224, 230, 238, 255);
colors[2] = CRGBA(224, 230, 238, 255);
colors[3] = CRGBA(0, 0, 0, 255);
colors[4] = CRGBA(252, 66, 66, 255);
colors[5] = CRGBA(0, 0, 0, 255);
colors[6] = CRGBA(0, 0, 0, 255);
colors[7] = CRGBA(252, 66, 66, 255);
CVector dir;
for(i = 0; i < 40; i++){
dir.x = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.y = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.z = CGeneral::GetRandomNumberInRange(0.0f, 2.0f);
int rotSpeed = CGeneral::GetRandomNumberInRange(30.0f, 20.0f);
if(CGeneral::GetRandomNumber() & 1)
rotSpeed = -rotSpeed;
int f = ++nFrameGen & 3;
CParticle::AddParticle(PARTICLE_HELI_DEBRIS, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), dir,
nil, CGeneral::GetRandomNumberInRange(0.1f, 1.0f),
colors[nFrameGen&7], rotSpeed, 0, f, 0);
}
}
if(frm >= 40 && frm <= 60 && frm & 1){
if(frm & 1){
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.y = (frm - 40)*0.3f;
pos = GetMatrix() * pos;
}else{
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.y = (40 - frm)*0.3f;
pos = GetMatrix() * pos;
}
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, pos, 0);
}
if(frm == 30)
bRenderScorched = true;
if(frm == 62){
TheCamera.SetFadeColour(200, 200, 200);
TheCamera.Fade(0.0f, FADE_OUT);
TheCamera.ProcessFade();
TheCamera.Fade(1.0f, FADE_IN);
if(m_bIsDrugRunCesna){
CesnaMissionStatus = CESNA_STATUS_DESTROYED;
pDrugRunCesna = nil;
}
if(m_bIsDropOffCesna){
DropOffCesnaMissionStatus = CESNA_STATUS_DESTROYED;
pDropOffCesna = nil;
}
FlagToDestroyWhenNextProcessed();
}
}
}
// Update plane position and speed
if(GetModelIndex() == MI_AIRTRAIN || !m_isFarAway || ((CTimer::GetFrameCounter() + m_randomSeed) & 7) == 0){
if(GetModelIndex() == MI_AIRTRAIN){
float pathPositionRear = PlanePathPosition[m_nPlaneId] - 30.0f;
if(pathPositionRear < 0.0f)
pathPositionRear += TotalLengthOfFlightPath;
float pathPosition = pathPositionRear + 30.0f;
float pitch = 0.0f;
float distSinceTakeOff = pathPosition - TakeOffPoint;
if(distSinceTakeOff <= 0.0f && distSinceTakeOff > -70.0f){
// shortly before take off
pitch = 1.0f - distSinceTakeOff/-70.0f;
}else if(distSinceTakeOff >= 0.0f && distSinceTakeOff < 100.0f){
// shortly after take off
pitch = 1.0f - distSinceTakeOff/100.0f;
}
float distSinceLanding = pathPosition - LandingPoint;
if(distSinceLanding <= 0.0f && distSinceLanding > -200.0f){
// shortly before landing
pitch = 1.0f - distSinceLanding/-200.0f;
}else if(distSinceLanding >= 0.0f && distSinceLanding < 70.0f){
// shortly after landing
pitch = 1.0f - distSinceLanding/70.0f;
}
// Advance current node to appropriate position
float pos1, pos2;
int nextTrackNode = m_nCurPathNode + 1;
pos1 = pPathNodes[m_nCurPathNode].t;
if(nextTrackNode < NumPathNodes)
pos2 = pPathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = TotalLengthOfFlightPath;
}
while(pathPositionRear < pos1 || pathPositionRear > pos2){
m_nCurPathNode = (m_nCurPathNode+1) % NumPathNodes;
nextTrackNode = m_nCurPathNode + 1;
pos1 = pPathNodes[m_nCurPathNode].t;
if(nextTrackNode < NumPathNodes)
pos2 = pPathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = TotalLengthOfFlightPath;
}
}
bool bothOnGround = pPathNodes[m_nCurPathNode].bOnGround && pPathNodes[nextTrackNode].bOnGround;
if(PlanePathPosition[m_nPlaneId] >= LandingPoint && OldPlanePathPosition[m_nPlaneId] < LandingPoint)
DMAudio.PlayOneShot(m_audioEntityId, SOUND_PLANE_ON_GROUND, 0.0f);
float dist = pPathNodes[nextTrackNode].t - pPathNodes[m_nCurPathNode].t;
if(dist < 0.0f)
dist += TotalLengthOfFlightPath;
float f = (pathPositionRear - pPathNodes[m_nCurPathNode].t)/dist;
CVector posRear = (1.0f - f)*pPathNodes[m_nCurPathNode].p + f*pPathNodes[nextTrackNode].p;
// Same for the front
float pathPositionFront = pathPositionRear + 60.0f;
if(pathPositionFront > TotalLengthOfFlightPath)
pathPositionFront -= TotalLengthOfFlightPath;
int curPathNodeFront = m_nCurPathNode;
int nextPathNodeFront = curPathNodeFront + 1;
pos1 = pPathNodes[curPathNodeFront].t;
if(nextPathNodeFront < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = TotalLengthOfFlightPath;
}
while(pathPositionFront < pos1 || pathPositionFront > pos2){
curPathNodeFront = (curPathNodeFront+1) % NumPathNodes;
nextPathNodeFront = curPathNodeFront + 1;
pos1 = pPathNodes[curPathNodeFront].t;
if(nextPathNodeFront < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = TotalLengthOfFlightPath;
}
}
dist = pPathNodes[nextPathNodeFront].t - pPathNodes[curPathNodeFront].t;
if(dist < 0.0f)
dist += TotalLengthOfFlightPath;
f = (pathPositionFront - pPathNodes[curPathNodeFront].t)/dist;
CVector posFront = (1.0f - f)*pPathNodes[curPathNodeFront].p + f*pPathNodes[nextPathNodeFront].p;
// And for another point 60 units in front of the plane, used to calculate roll
float pathPositionFront2 = pathPositionFront + 60.0f;
if(pathPositionFront2 > TotalLengthOfFlightPath)
pathPositionFront2 -= TotalLengthOfFlightPath;
int curPathNodeFront2 = m_nCurPathNode;
int nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pPathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = TotalLengthOfFlightPath;
}
while(pathPositionFront2 < pos1 || pathPositionFront2 > pos2){
curPathNodeFront2 = (curPathNodeFront2+1) % NumPathNodes;
nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pPathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = TotalLengthOfFlightPath;
}
}
dist = pPathNodes[nextPathNodeFront2].t - pPathNodes[curPathNodeFront2].t;
if(dist < 0.0f)
dist += TotalLengthOfFlightPath;
f = (pathPositionFront2 - pPathNodes[curPathNodeFront2].t)/dist;
CVector posFront2 = (1.0f - f)*pPathNodes[curPathNodeFront2].p + f*pPathNodes[nextPathNodeFront2].p;
// Now set matrix
GetMatrix().SetTranslateOnly((posRear + posFront) / 2.0f);
GetMatrix().GetPosition().z += 4.3f;
CVector fwd = posFront - posRear;
fwd.Normalise();
if(pitch != 0.0f){
fwd.z += 0.4f*pitch;
fwd.Normalise();
}
CVector fwd2 = posFront2 - posRear;
fwd2.Normalise();
CVector roll = CrossProduct(fwd, fwd2);
CVector right = CrossProduct(fwd, CVector(0.0f, 0.0f, 1.0f));
if(!bothOnGround)
right.z += 3.0f*roll.z;
right.Normalise();
CVector up = CrossProduct(right, fwd);
GetMatrix().GetRight() = right;
GetMatrix().GetUp() = up;
GetMatrix().GetForward() = fwd;
// Set speed
m_vecMoveSpeed = fwd*PlanePathSpeed[m_nPlaneId]/60.0f;
m_fSpeed = PlanePathSpeed[m_nPlaneId]/60.0f;
m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f);
m_isFarAway = !((posFront - TheCamera.GetPosition()).MagnitudeSqr2D() < sq(300.0f));
}else{
float planePathPosition;
float totalLengthOfFlightPath;
CPlaneNode *pathNodes;
float planePathSpeed;
int numPathNodes;
if(m_bIsDrugRunCesna){
planePathPosition = PlanePath3Position;
totalLengthOfFlightPath = TotalLengthOfFlightPath3;
pathNodes = pPath3Nodes;
planePathSpeed = PlanePath3Speed;
numPathNodes = NumPath3Nodes;
if(CesnaMissionStatus == CESNA_STATUS_LANDED){
pDrugRunCesna = nil;
FlagToDestroyWhenNextProcessed();
}
}else if(m_bIsDropOffCesna){
planePathPosition = PlanePath4Position;
totalLengthOfFlightPath = TotalLengthOfFlightPath4;
pathNodes = pPath4Nodes;
planePathSpeed = PlanePath4Speed;
numPathNodes = NumPath4Nodes;
if(DropOffCesnaMissionStatus == CESNA_STATUS_LANDED){
pDropOffCesna = nil;
FlagToDestroyWhenNextProcessed();
}
}else{
planePathPosition = PlanePath2Position[m_nPlaneId];
totalLengthOfFlightPath = TotalLengthOfFlightPath2;
pathNodes = pPath2Nodes;
planePathSpeed = PlanePath2Speed[m_nPlaneId];
numPathNodes = NumPath2Nodes;
}
// Advance current node to appropriate position
float pathPositionRear = planePathPosition - 10.0f;
if(pathPositionRear < 0.0f)
pathPositionRear += totalLengthOfFlightPath;
float pos1, pos2;
int nextTrackNode = m_nCurPathNode + 1;
pos1 = pathNodes[m_nCurPathNode].t;
if(nextTrackNode < numPathNodes)
pos2 = pathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = totalLengthOfFlightPath;
}
while(pathPositionRear < pos1 || pathPositionRear > pos2){
m_nCurPathNode = (m_nCurPathNode+1) % numPathNodes;
nextTrackNode = m_nCurPathNode + 1;
pos1 = pathNodes[m_nCurPathNode].t;
if(nextTrackNode < numPathNodes)
pos2 = pathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = totalLengthOfFlightPath;
}
}
float dist = pathNodes[nextTrackNode].t - pathNodes[m_nCurPathNode].t;
if(dist < 0.0f)
dist += totalLengthOfFlightPath;
float f = (pathPositionRear - pathNodes[m_nCurPathNode].t)/dist;
CVector posRear = (1.0f - f)*pathNodes[m_nCurPathNode].p + f*pathNodes[nextTrackNode].p;
// Same for the front
float pathPositionFront = pathPositionRear + 20.0f;
if(pathPositionFront > totalLengthOfFlightPath)
pathPositionFront -= totalLengthOfFlightPath;
int curPathNodeFront = m_nCurPathNode;
int nextPathNodeFront = curPathNodeFront + 1;
pos1 = pathNodes[curPathNodeFront].t;
if(nextPathNodeFront < numPathNodes)
pos2 = pathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = totalLengthOfFlightPath;
}
while(pathPositionFront < pos1 || pathPositionFront > pos2){
curPathNodeFront = (curPathNodeFront+1) % numPathNodes;
nextPathNodeFront = curPathNodeFront + 1;
pos1 = pathNodes[curPathNodeFront].t;
if(nextPathNodeFront < numPathNodes)
pos2 = pathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = totalLengthOfFlightPath;
}
}
dist = pathNodes[nextPathNodeFront].t - pathNodes[curPathNodeFront].t;
if(dist < 0.0f)
dist += totalLengthOfFlightPath;
f = (pathPositionFront - pathNodes[curPathNodeFront].t)/dist;
CVector posFront = (1.0f - f)*pathNodes[curPathNodeFront].p + f*pathNodes[nextPathNodeFront].p;
// And for another point 30 units in front of the plane, used to calculate roll
float pathPositionFront2 = pathPositionFront + 30.0f;
if(pathPositionFront2 > totalLengthOfFlightPath)
pathPositionFront2 -= totalLengthOfFlightPath;
int curPathNodeFront2 = m_nCurPathNode;
int nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < numPathNodes)
pos2 = pathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = totalLengthOfFlightPath;
}
while(pathPositionFront2 < pos1 || pathPositionFront2 > pos2){
curPathNodeFront2 = (curPathNodeFront2+1) % numPathNodes;
nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < numPathNodes)
pos2 = pathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = totalLengthOfFlightPath;
}
}
dist = pathNodes[nextPathNodeFront2].t - pathNodes[curPathNodeFront2].t;
if(dist < 0.0f)
dist += totalLengthOfFlightPath;
f = (pathPositionFront2 - pathNodes[curPathNodeFront2].t)/dist;
CVector posFront2 = (1.0f - f)*pathNodes[curPathNodeFront2].p + f*pathNodes[nextPathNodeFront2].p;
// Now set matrix
GetMatrix().SetTranslateOnly((posRear + posFront) / 2.0f);
GetMatrix().GetPosition().z += 1.0f;
CVector fwd = posFront - posRear;
fwd.Normalise();
CVector fwd2 = posFront2 - posRear;
fwd2.Normalise();
CVector roll = CrossProduct(fwd, fwd2);
CVector right = CrossProduct(fwd, CVector(0.0f, 0.0f, 1.0f));
right.z += 3.0f*roll.z;
right.Normalise();
CVector up = CrossProduct(right, fwd);
GetMatrix().GetRight() = right;
GetMatrix().GetUp() = up;
GetMatrix().GetForward() = fwd;
// Set speed
m_vecMoveSpeed = fwd*planePathSpeed/60.0f;
m_fSpeed = planePathSpeed/60.0f;
m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f);
m_isFarAway = !((posFront - TheCamera.GetPosition()).MagnitudeSqr2D() < sq(300.0f));
}
}
bIsInSafePosition = true;
GetMatrix().UpdateRW();
UpdateRwFrame();
// Handle streaming and such
CVehicleModelInfo *mi = (CVehicleModelInfo*)CModelInfo::GetModelInfo(GetModelIndex());
if(m_isFarAway){
// Switch to LOD model
if(m_rwObject && RwObjectGetType(m_rwObject) == rpCLUMP){
DeleteRwObject();
if(mi->m_planeLodId != -1){
PUSH_MEMID(MEMID_WORLD);
m_rwObject = CModelInfo::GetModelInfo(mi->m_planeLodId)->CreateInstance();
POP_MEMID();
if(m_rwObject)
m_matrix.AttachRW(RwFrameGetMatrix(RpAtomicGetFrame((RpAtomic*)m_rwObject)));
}
}
}else if(CStreaming::HasModelLoaded(GetModelIndex())){
if(m_rwObject && RwObjectGetType(m_rwObject) == rpATOMIC){
// Get rid of LOD model
m_matrix.Detach();
if(m_rwObject){ // useless check
if(RwObjectGetType(m_rwObject) == rpATOMIC){ // useless check
RwFrame *f = RpAtomicGetFrame((RpAtomic*)m_rwObject);
RpAtomicDestroy((RpAtomic*)m_rwObject);
RwFrameDestroy(f);
}
m_rwObject = nil;
}
}
// Set high detail model
if(m_rwObject == nil){
int id = GetModelIndex();
m_modelIndex = -1;
SetModelIndex(id);
}
}else{
CStreaming::RequestModel(GetModelIndex(), STREAMFLAGS_DEPENDENCY);
}
}
void
CPlane::PreRender(void)
{
CVehicleModelInfo *mi = (CVehicleModelInfo*)CModelInfo::GetModelInfo(GetModelIndex());
CVector lookVector = GetPosition() - TheCamera.GetPosition();
float camDist = lookVector.Magnitude();
if(camDist != 0.0f)
lookVector *= 1.0f/camDist;
else
lookVector = CVector(1.0f, 0.0f, 0.0f);
float behindness = DotProduct(lookVector, GetForward());
// Wing lights
if(behindness < 0.0f){
// in front of plane
CVector lightPos = mi->m_positions[PLANE_POS_LIGHT_RIGHT];
CVector lightR = GetMatrix() * lightPos;
CVector lightL = lightR;
lightL -= GetRight()*2.0f*lightPos.x;
float intensity = -0.6f*behindness + 0.4f;
float size = 1.0f - behindness;
if(behindness < -0.9f && camDist < 50.0f){
// directly in front
CCoronas::RegisterCorona((uintptr)this + 10, 255*intensity, 255*intensity, 255*intensity, 255,
lightL, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_HEADLIGHTS, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
CCoronas::RegisterCorona((uintptr)this + 11, 255*intensity, 255*intensity, 255*intensity, 255,
lightR, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_HEADLIGHTS, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
}else{
CCoronas::RegisterCorona((uintptr)this + 10, 255*intensity, 255*intensity, 255*intensity, 255,
lightL, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_NONE, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
CCoronas::RegisterCorona((uintptr)this + 11, 255*intensity, 255*intensity, 255*intensity, 255,
lightR, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_NONE, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
}
}
// Tail light
if(CTimer::GetTimeInMilliseconds() & 0x200){
CVector pos = GetMatrix() * mi->m_positions[PLANE_POS_LIGHT_TAIL];
CCoronas::RegisterCorona((uintptr)this + 12, 255, 0, 0, 255,
pos, 1.0f, 120.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_NONE, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
}
}
void
CPlane::Render(void)
{
CEntity::Render();
}
#define CRUISE_SPEED (50.0f)
#define TAXI_SPEED (5.0f)
void
CPlane::InitPlanes(void)
{
int i;
CesnaMissionStatus = CESNA_STATUS_NONE;
// Jumbo
if(pPathNodes == nil){
pPathNodes = LoadPath("data\\paths\\flight.dat", NumPathNodes, TotalLengthOfFlightPath, true);
// Figure out which nodes are on ground
CColPoint colpoint;
CEntity *entity;
for(i = 0; i < NumPathNodes; i++){
if(CWorld::ProcessVerticalLine(pPathNodes[i].p, 1000.0f, colpoint, entity, true, false, false, false, true, false, nil)){
pPathNodes[i].p.z = colpoint.point.z;
pPathNodes[i].bOnGround = true;
}else
pPathNodes[i].bOnGround = false;
}
// Find lading and takeoff points
LandingPoint = -1.0f;
TakeOffPoint = -1.0f;
bool lastOnGround = pPathNodes[NumPathNodes-1].bOnGround;
for(i = 0; i < NumPathNodes; i++){
if(pPathNodes[i].bOnGround && !lastOnGround)
LandingPoint = pPathNodes[i].t;
else if(!pPathNodes[i].bOnGround && lastOnGround)
TakeOffPoint = pPathNodes[i].t;
lastOnGround = pPathNodes[i].bOnGround;
}
// Animation
float time = 0.0f;
float position = 0.0f;
// Start on ground with slow speed
aPlaneLineBits[0].type = 1;
aPlaneLineBits[0].time = time;
aPlaneLineBits[0].position = position;
aPlaneLineBits[0].speed = TAXI_SPEED;
aPlaneLineBits[0].acceleration = 0.0f;
float dist = (TakeOffPoint-600.0f) - position;
time += dist/TAXI_SPEED;
position += dist;
// Accelerate to take off
aPlaneLineBits[1].type = 2;
aPlaneLineBits[1].time = time;
aPlaneLineBits[1].position = position;
aPlaneLineBits[1].speed = TAXI_SPEED;
aPlaneLineBits[1].acceleration = 618.75f/600.0f;
time += 600.0f/((CRUISE_SPEED+TAXI_SPEED)/2.0f);
position += 600.0f;
// Fly at cruise speed
aPlaneLineBits[2].type = 1;
aPlaneLineBits[2].time = time;
aPlaneLineBits[2].position = position;
aPlaneLineBits[2].speed = CRUISE_SPEED;
aPlaneLineBits[2].acceleration = 0.0f;
dist = LandingPoint - TakeOffPoint;
time += dist/CRUISE_SPEED;
position += dist;
// Brake after landing
aPlaneLineBits[3].type = 2;
aPlaneLineBits[3].time = time;
aPlaneLineBits[3].position = position;
aPlaneLineBits[3].speed = CRUISE_SPEED;
aPlaneLineBits[3].acceleration = -618.75f/600.0f;
time += 600.0f/((CRUISE_SPEED+TAXI_SPEED)/2.0f);
position += 600.0f;
// Taxi
aPlaneLineBits[4].type = 1;
aPlaneLineBits[4].time = time;
aPlaneLineBits[4].position = position;
aPlaneLineBits[4].speed = TAXI_SPEED;
aPlaneLineBits[4].acceleration = 0.0f;
time += (TotalLengthOfFlightPath - position)/TAXI_SPEED;
// end
aPlaneLineBits[5].time = time;
TotalDurationOfFlightPath = time;
}
// Dodo
if(pPath2Nodes == nil){
pPath2Nodes = LoadPath("data\\paths\\flight2.dat", NumPath2Nodes, TotalLengthOfFlightPath2, true);
TotalDurationOfFlightPath2 = TotalLengthOfFlightPath2/CRUISE_SPEED;
}
// Mission Cesna
if(pPath3Nodes == nil){
pPath3Nodes = LoadPath("data\\paths\\flight3.dat", NumPath3Nodes, TotalLengthOfFlightPath3, false);
TotalDurationOfFlightPath3 = TotalLengthOfFlightPath3/CRUISE_SPEED;
}
// Mission Cesna
if(pPath4Nodes == nil){
pPath4Nodes = LoadPath("data\\paths\\flight4.dat", NumPath4Nodes, TotalLengthOfFlightPath4, false);
TotalDurationOfFlightPath4 = TotalLengthOfFlightPath4/CRUISE_SPEED;
}
CStreaming::LoadAllRequestedModels(false);
CStreaming::RequestModel(MI_AIRTRAIN, 0);
CStreaming::LoadAllRequestedModels(false);
for(i = 0; i < 3; i++){
CPlane *plane = new CPlane(MI_AIRTRAIN, PERMANENT_VEHICLE);
plane->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
plane->SetStatus(STATUS_ABANDONED);
plane->bIsLocked = true;
plane->m_nPlaneId = i;
plane->m_nCurPathNode = 0;
CWorld::Add(plane);
}
CStreaming::RequestModel(MI_DEADDODO, 0);
CStreaming::LoadAllRequestedModels(false);
for(i = 0; i < 3; i++){
CPlane *plane = new CPlane(MI_DEADDODO, PERMANENT_VEHICLE);
plane->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
plane->SetStatus(STATUS_ABANDONED);
plane->bIsLocked = true;
plane->m_nPlaneId = i;
plane->m_nCurPathNode = 0;
CWorld::Add(plane);
}
}
void
CPlane::Shutdown(void)
{
delete[] pPathNodes;
delete[] pPath2Nodes;
delete[] pPath3Nodes;
delete[] pPath4Nodes;
pPathNodes = nil;
pPath2Nodes = nil;
pPath3Nodes = nil;
pPath4Nodes = nil;
}
CPlaneNode*
CPlane::LoadPath(char const *filename, int32 &numNodes, float &totalLength, bool loop)
{
int bp, lp;
int i;
CFileMgr::LoadFile(filename, work_buff, sizeof(work_buff), "r");
*gString = '\0';
for(bp = 0, lp = 0; work_buff[bp] != '\n'; bp++, lp++)
gString[lp] = work_buff[bp];
bp++;
gString[lp] = '\0';
sscanf(gString, "%d", &numNodes);
CPlaneNode *nodes = new CPlaneNode[numNodes];
for(i = 0; i < numNodes; i++){
*gString = '\0';
for(lp = 0; work_buff[bp] != '\n'; bp++, lp++)
gString[lp] = work_buff[bp];
bp++;
// BUG: game doesn't terminate string
gString[lp] = '\0';
sscanf(gString, "%f %f %f", &nodes[i].p.x, &nodes[i].p.y, &nodes[i].p.z);
}
// Calculate length of segments and path
totalLength = 0.0f;
for(i = 0; i < numNodes; i++){
nodes[i].t = totalLength;
float l = (nodes[(i+1) % numNodes].p - nodes[i].p).Magnitude2D();
if(!loop && i == numNodes-1)
l = 0.0f;
totalLength += l;
}
return nodes;
}
void
CPlane::UpdatePlanes(void)
{
int i, j;
uint32 time;
float t, deltaT;
if(CReplay::IsPlayingBack())
return;
// Jumbo jets
time = CTimer::GetTimeInMilliseconds();
for(i = 0; i < 3; i++){
t = TotalDurationOfFlightPath * (float)(time & 0x7FFFF)/0x80000;
// find current frame
for(j = 0; t > aPlaneLineBits[j+1].time; j++);
OldPlanePathPosition[i] = PlanePathPosition[i];
deltaT = t - aPlaneLineBits[j].time;
switch(aPlaneLineBits[j].type){
case 0: // standing still
PlanePathPosition[i] = aPlaneLineBits[j].position;
PlanePathSpeed[i] = 0.0f;
break;
case 1: // moving with constant speed
PlanePathPosition[i] = aPlaneLineBits[j].position + aPlaneLineBits[j].speed*deltaT;
PlanePathSpeed[i] = (TotalDurationOfFlightPath*1000.0f/0x80000) * aPlaneLineBits[j].speed;
break;
case 2: // accelerating/braking
PlanePathPosition[i] = aPlaneLineBits[j].position + (aPlaneLineBits[j].speed + aPlaneLineBits[j].acceleration*deltaT)*deltaT;
PlanePathSpeed[i] = (TotalDurationOfFlightPath*1000.0f/0x80000)*aPlaneLineBits[j].speed + 2.0f*aPlaneLineBits[j].acceleration*deltaT;
break;
}
// time offset for each plane
time += 0x80000/3;
}
time = CTimer::GetTimeInMilliseconds();
t = TotalDurationOfFlightPath2/0x80000;
PlanePath2Position[0] = CRUISE_SPEED * (time & 0x7FFFF)*t;
PlanePath2Position[1] = CRUISE_SPEED * ((time + 0x80000/3) & 0x7FFFF)*t;
PlanePath2Position[2] = CRUISE_SPEED * ((time + 0x80000/3*2) & 0x7FFFF)*t;
PlanePath2Speed[0] = CRUISE_SPEED*t;
PlanePath2Speed[1] = CRUISE_SPEED*t;
PlanePath2Speed[2] = CRUISE_SPEED*t;
if(CesnaMissionStatus == CESNA_STATUS_FLYING){
PlanePath3Speed = CRUISE_SPEED*TotalDurationOfFlightPath3/0x20000;
PlanePath3Position = PlanePath3Speed * ((time - CesnaMissionStartTime) & 0x1FFFF);
if(time - CesnaMissionStartTime >= 128072)
CesnaMissionStatus = CESNA_STATUS_LANDED;
}
if(DropOffCesnaMissionStatus == CESNA_STATUS_FLYING){
PlanePath4Speed = CRUISE_SPEED*TotalDurationOfFlightPath4/0x80000;
PlanePath4Position = PlanePath4Speed * ((time - DropOffCesnaMissionStartTime) & 0x7FFFF);
if(time - DropOffCesnaMissionStartTime >= 521288)
DropOffCesnaMissionStatus = CESNA_STATUS_LANDED;
}
}
bool
CPlane::TestRocketCollision(CVector *rocketPos)
{
int i;
i = CPools::GetVehiclePool()->GetSize();
while(--i >= 0){
CPlane *plane = (CPlane*)CPools::GetVehiclePool()->GetSlot(i);
if(plane &&
#ifdef EXPLODING_AIRTRAIN
(plane->GetModelIndex() == MI_AIRTRAIN || plane->GetModelIndex() == MI_DEADDODO) &&
#else
plane->GetModelIndex() != MI_AIRTRAIN && plane->GetModelIndex() == MI_DEADDODO && // strange check
#endif
!plane->m_bHasBeenHit && (*rocketPos - plane->GetPosition()).Magnitude() < 25.0f){
plane->m_nFrameWhenHit = CTimer::GetFrameCounter();
plane->m_bHasBeenHit = true;
CWorld::Players[CWorld::PlayerInFocus].m_pPed->m_pWanted->RegisterCrime_Immediately(CRIME_DESTROYED_CESSNA,
plane->GetPosition(), i+1983, false);
return true;
}
}
return false;
}
// BUG: not in CPlane in the game
void
CPlane::CreateIncomingCesna(void)
{
if(CesnaMissionStatus == CESNA_STATUS_FLYING){
CWorld::Remove(pDrugRunCesna);
delete pDrugRunCesna;
pDrugRunCesna = nil;
}
pDrugRunCesna = new CPlane(MI_DEADDODO, PERMANENT_VEHICLE);
pDrugRunCesna->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
pDrugRunCesna->SetStatus(STATUS_ABANDONED);
pDrugRunCesna->bIsLocked = true;
pDrugRunCesna->m_nPlaneId = 0;
pDrugRunCesna->m_nCurPathNode = 0;
pDrugRunCesna->m_bIsDrugRunCesna = true;
CWorld::Add(pDrugRunCesna);
CesnaMissionStatus = CESNA_STATUS_FLYING;
CesnaMissionStartTime = CTimer::GetTimeInMilliseconds();
printf("CPlane::CreateIncomingCesna(void)\n");
}
void
CPlane::CreateDropOffCesna(void)
{
if(DropOffCesnaMissionStatus == CESNA_STATUS_FLYING){
CWorld::Remove(pDropOffCesna);
delete pDropOffCesna;
pDropOffCesna = nil;
}
pDropOffCesna = new CPlane(MI_DEADDODO, PERMANENT_VEHICLE);
pDropOffCesna->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
pDropOffCesna->SetStatus(STATUS_ABANDONED);
pDropOffCesna->bIsLocked = true;
pDropOffCesna->m_nPlaneId = 0;
pDropOffCesna->m_nCurPathNode = 0;
pDropOffCesna->m_bIsDropOffCesna = true;
CWorld::Add(pDropOffCesna);
DropOffCesnaMissionStatus = CESNA_STATUS_FLYING;
DropOffCesnaMissionStartTime = CTimer::GetTimeInMilliseconds();
printf("CPlane::CreateDropOffCesna(void)\n");
}
const CVector CPlane::FindDrugPlaneCoordinates(void) { return pDrugRunCesna->GetPosition(); }
const CVector CPlane::FindDropOffCesnaCoordinates(void) { return pDropOffCesna->GetPosition(); }
bool CPlane::HasCesnaLanded(void) { return CesnaMissionStatus == CESNA_STATUS_LANDED; }
bool CPlane::HasCesnaBeenDestroyed(void) { return CesnaMissionStatus == CESNA_STATUS_DESTROYED; }
bool CPlane::HasDropOffCesnaBeenShotDown(void) { return DropOffCesnaMissionStatus == CESNA_STATUS_DESTROYED; }
| 32.33709
| 136
| 0.701784
|
gameblabla
|
532cd22b5c3fc5703751081b99b23a3b37cd742d
| 503
|
cpp
|
C++
|
src/MageFramework/Vulkan/RendererBackend/vAccelerationStructure.cpp
|
AmanSachan1/ShaderPlayGround
|
aba8293404bcba7ecad2a97c86c8aea7d0693945
|
[
"MIT"
] | 2
|
2019-12-04T17:06:44.000Z
|
2019-12-24T16:33:37.000Z
|
src/MageFramework/Vulkan/RendererBackend/vAccelerationStructure.cpp
|
AmanSachan1/GraphicsPlayground
|
aba8293404bcba7ecad2a97c86c8aea7d0693945
|
[
"MIT"
] | null | null | null |
src/MageFramework/Vulkan/RendererBackend/vAccelerationStructure.cpp
|
AmanSachan1/GraphicsPlayground
|
aba8293404bcba7ecad2a97c86c8aea7d0693945
|
[
"MIT"
] | null | null | null |
#include "Vulkan/RendererBackend/vAccelerationStructure.h"
#include <Vulkan/Utilities/vAccelerationStructureUtil.h>
void vBLAS::generateBLAS(VkCommandBuffer commandBuffer,
mageVKBuffer& scratchBuffer, VkDeviceSize scratchOffset,
bool updateOnly) const
{
const VkAccelerationStructureNV previousStructure = updateOnly ? m_accelerationStructure : nullptr;
}
void vTLAS::generateTLAS(VkCommandBuffer commandBuffer,
mageVKBuffer& scratchBuffer, VkDeviceSize scratchOffset,
bool updateOnly) const
{
}
| 31.4375
| 100
| 0.840954
|
AmanSachan1
|
532d377395f6bef19fc6b88303fa8d4b7daa55ee
| 116
|
cpp
|
C++
|
src/cpu/tms9900/tms9995.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 145
|
2018-04-10T17:24:39.000Z
|
2022-03-27T17:39:03.000Z
|
src/cpu/tms9900/tms9995.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 779
|
2018-04-09T21:30:15.000Z
|
2022-03-31T06:38:07.000Z
|
src/cpu/tms9900/tms9995.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 152
|
2018-04-10T10:52:18.000Z
|
2022-03-09T08:24:16.000Z
|
/*
generate the tms9995 emulator
*/
#include "tms9900.h"
#define TMS99XX_MODEL TMS9995_ID
#include "99xxcore.h"
| 11.6
| 32
| 0.741379
|
gameblabla
|
532f4a85f62f3f26b85d1904dbdd3f72fc1d9a53
| 2,342
|
cpp
|
C++
|
src/gboost/wlearner.cpp
|
accosmin/libnano
|
0c4014e1bc76c2e1b38d08211b000a4e17b00ed5
|
[
"MIT"
] | null | null | null |
src/gboost/wlearner.cpp
|
accosmin/libnano
|
0c4014e1bc76c2e1b38d08211b000a4e17b00ed5
|
[
"MIT"
] | 32
|
2019-02-18T10:35:59.000Z
|
2021-12-10T10:37:15.000Z
|
src/gboost/wlearner.cpp
|
accosmin/libnano
|
0c4014e1bc76c2e1b38d08211b000a4e17b00ed5
|
[
"MIT"
] | 1
|
2019-08-05T06:11:09.000Z
|
2019-08-05T06:11:09.000Z
|
#include <mutex>
#include <nano/logger.h>
#include <nano/tensor/stream.h>
#include <nano/gboost/wlearner_dstep.h>
#include <nano/gboost/wlearner_dtree.h>
#include <nano/gboost/wlearner_hinge.h>
#include <nano/gboost/wlearner_stump.h>
#include <nano/gboost/wlearner_table.h>
#include <nano/gboost/wlearner_affine.h>
using namespace nano;
void wlearner_t::batch(int batch)
{
m_batch = batch;
}
void wlearner_t::read(std::istream& stream)
{
serializable_t::read(stream);
int32_t ibatch = 0;
critical(
!::nano::read(stream, ibatch),
"weak learner: failed to read from stream!");
batch(ibatch);
}
void wlearner_t::write(std::ostream& stream) const
{
serializable_t::write(stream);
critical(
!::nano::write(stream, static_cast<int32_t>(batch())),
"weak learner: failed to write to stream!");
}
void wlearner_t::check(const indices_t& samples)
{
critical(
!std::is_sorted(::nano::begin(samples), ::nano::end(samples)),
"weak learner: samples must be sorted by index!");
}
void wlearner_t::scale(tensor4d_t& tables, const vector_t& scale)
{
critical(
scale.size() != 1 && scale.size() != tables.size<0>(),
"weak learner: mis-matching scale!");
critical(
scale.minCoeff() < 0,
"weak learner: invalid scale factors!");
for (tensor_size_t i = 0; i < tables.size<0>(); ++ i)
{
tables.array(i) *= scale(std::min(i, scale.size() - 1));
}
}
tensor4d_t wlearner_t::predict(const dataset_t& dataset, const indices_cmap_t& samples) const
{
tensor4d_t outputs(cat_dims(samples.size(), dataset.tdim()));
outputs.zero();
predict(dataset, samples, outputs);
return outputs;
}
wlearner_factory_t& wlearner_t::all()
{
static wlearner_factory_t manager;
static std::once_flag flag;
std::call_once(flag, [] ()
{
manager.add_by_type<wlearner_lin1_t>();
manager.add_by_type<wlearner_log1_t>();
manager.add_by_type<wlearner_cos1_t>();
manager.add_by_type<wlearner_sin1_t>();
manager.add_by_type<wlearner_dstep_t>();
manager.add_by_type<wlearner_dtree_t>();
manager.add_by_type<wlearner_hinge_t>();
manager.add_by_type<wlearner_stump_t>();
manager.add_by_type<wlearner_table_t>();
});
return manager;
}
| 25.456522
| 93
| 0.66012
|
accosmin
|
53318d0cc4580daf9ddfc856c80d53c417521ea9
| 1,727
|
cc
|
C++
|
src/thread-crosser.cc
|
jjzhang166/capture-thread
|
4c9930b1c223c2f9aa22714855a892e9aa4aa800
|
[
"Apache-2.0"
] | null | null | null |
src/thread-crosser.cc
|
jjzhang166/capture-thread
|
4c9930b1c223c2f9aa22714855a892e9aa4aa800
|
[
"Apache-2.0"
] | null | null | null |
src/thread-crosser.cc
|
jjzhang166/capture-thread
|
4c9930b1c223c2f9aa22714855a892e9aa4aa800
|
[
"Apache-2.0"
] | null | null | null |
/* -----------------------------------------------------------------------------
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------- */
// Author: Kevin P. Barry [ta0kira@gmail.com] [kevinbarry@google.com]
#include <cassert>
#include "thread-crosser.h"
namespace capture_thread {
// static
std::function<void()> ThreadCrosser::WrapCall(std::function<void()> call) {
const auto current = GetCurrent();
if (call && current) {
return current->WrapWithCrosser(WrapCallRec(std::move(call), current));
} else {
return call;
}
}
// static
std::function<void()> ThreadCrosser::WrapCallRec(std::function<void()> call,
const ThreadCrosser* current) {
if (current) {
return WrapCallRec(current->WrapWithContext(std::move(call)),
current->Parent());
} else {
return call;
}
}
void ThreadCrosser::SetOverride::Call(std::function<void()> call) const {
call = WrapCallRec(std::move(call), current_);
assert(call);
if (call) {
call();
}
}
// static
thread_local ThreadCrosser* ThreadCrosser::current_(nullptr);
} // namespace capture_thread
| 29.775862
| 80
| 0.628257
|
jjzhang166
|
53327b456447c6c5ff086262ab9c12fb0d5f14f9
| 1,965
|
cpp
|
C++
|
src/test/test_utils.cpp
|
ShnitzelKiller/Reverse-Engineering-Carpentry
|
585b5ff053c7e3bf286b663a584bc83687691bd6
|
[
"MIT"
] | 3
|
2021-09-08T07:28:13.000Z
|
2022-03-02T21:12:40.000Z
|
src/test/test_utils.cpp
|
ShnitzelKiller/Reverse-Engineering-Carpentry
|
585b5ff053c7e3bf286b663a584bc83687691bd6
|
[
"MIT"
] | 1
|
2021-09-21T14:40:55.000Z
|
2021-09-26T01:19:38.000Z
|
src/test/test_utils.cpp
|
ShnitzelKiller/Reverse-Engineering-Carpentry
|
585b5ff053c7e3bf286b663a584bc83687691bd6
|
[
"MIT"
] | null | null | null |
//
// Created by James Noeckel on 4/7/20.
//
#include <iostream>
#include "utils/top_k_indices.hpp"
#include "utils/sorted_data_structures.hpp"
int main(int argc, char **argv) {
bool passed = true;
{
std::vector<int> sorted_vec;
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 99);
sorted_insert(sorted_vec, 99);
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 3);
passed = passed && sorted_vec.size() == 3 && sorted_vec[0] == 0 && sorted_vec[1] == 3 && sorted_vec[2] == 99
&& &(*sorted_find(sorted_vec, 99)) == &sorted_vec[2] && sorted_contains(sorted_vec, 3);
}
{
std::vector<std::pair<int, int>> sorted_map;
sorted_insert(sorted_map, 0, 9);
sorted_insert(sorted_map, 4, 99);
sorted_insert(sorted_map, 86, 999);
sorted_insert(sorted_map, 4, 98);
sorted_get(sorted_map, 86) = 998;
for (const auto &pair : sorted_map) {
std::cout << '(' << pair.first << ", " << pair.second << ") ";
}
std::cout << std::endl;
passed = passed && sorted_map.size() == 3 && sorted_get(sorted_map, 4) == 99 &&
sorted_get(sorted_map, 0) == 9 &&
sorted_get(sorted_map, 86) == 998 &&
sorted_find(sorted_map, 666) == sorted_map.end() &&
sorted_find(sorted_map, 0)->second == 9;
}
{
std::vector<int> values = {-1, 8, 4, 99};
std::vector<size_t> indices = top_k_indices(values.begin(), values.end(), 3);
passed = passed && indices.size() == 3 && indices[0] == 3 && indices[1] == 1 && indices[2] == 2;
std::vector<size_t> indices2 = top_k_indices(values.begin(), values.end(), 2, std::greater<>());
passed = passed && indices2.size() == 2 && indices2[0] == 0 && indices2[1] == 2;
}
return !passed;
}
| 40.9375
| 116
| 0.561832
|
ShnitzelKiller
|
5335fbf56bc6ff0746bf13c3f4f09f653da58c71
| 347
|
cc
|
C++
|
dreal/util/precision_guard.cc
|
soonho-tri/dreal4
|
e774d1496001e826c82dccee45094dd694089bee
|
[
"Apache-2.0"
] | null | null | null |
dreal/util/precision_guard.cc
|
soonho-tri/dreal4
|
e774d1496001e826c82dccee45094dd694089bee
|
[
"Apache-2.0"
] | 1
|
2018-01-19T16:11:44.000Z
|
2018-01-19T16:11:44.000Z
|
dreal/util/precision_guard.cc
|
soonho-tri/dreal4
|
e774d1496001e826c82dccee45094dd694089bee
|
[
"Apache-2.0"
] | null | null | null |
#include "dreal/util/precision_guard.h"
namespace dreal {
PrecisionGuard::PrecisionGuard(std::ostream* os,
const std::streamsize precision)
: os_{os}, old_precision_(os->precision()) {
os_->precision(precision);
}
PrecisionGuard::~PrecisionGuard() { os_->precision(old_precision_); }
} // namespace dreal
| 24.785714
| 69
| 0.668588
|
soonho-tri
|
533c9c4ecdbdc99bc55d94df5c363119491a63bc
| 7,874
|
cc
|
C++
|
code/Samples/ResourceStress/ResourceStress.cc
|
infancy/oryol
|
06b580116cc2e929b9e1a85920a74fb32d76493c
|
[
"MIT"
] | 1,707
|
2015-01-01T14:56:08.000Z
|
2022-03-28T06:44:09.000Z
|
code/Samples/ResourceStress/ResourceStress.cc
|
infancy/oryol
|
06b580116cc2e929b9e1a85920a74fb32d76493c
|
[
"MIT"
] | 256
|
2015-01-03T14:55:53.000Z
|
2020-09-09T10:43:46.000Z
|
code/Samples/ResourceStress/ResourceStress.cc
|
infancy/oryol
|
06b580116cc2e929b9e1a85920a74fb32d76493c
|
[
"MIT"
] | 222
|
2015-01-05T00:20:54.000Z
|
2022-02-06T01:41:37.000Z
|
//------------------------------------------------------------------------------
// ResourceStress.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/Main.h"
#include "IO/IO.h"
#include "Gfx/Gfx.h"
#include "Dbg/Dbg.h"
#include "HttpFS/HTTPFileSystem.h"
#include "Assets/Gfx/ShapeBuilder.h"
#include "Assets/Gfx/TextureLoader.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/random.hpp"
#include "shaders.h"
using namespace Oryol;
class ResourceStressApp : public App {
public:
AppState::Code OnInit();
AppState::Code OnRunning();
AppState::Code OnCleanup();
void createObjects();
void updateObjects();
void showInfo();
struct Object {
DrawState drawState;
ResourceLabel label;
glm::mat4 modelTransform;
};
glm::mat4 computeMVP(const Object& obj);
static const int MaxNumObjects = 1024;
uint32_t frameCount = 0;
Id shader;
Array<Object> objects;
glm::mat4 view;
glm::mat4 proj;
TextureSetup texBlueprint;
};
OryolMain(ResourceStressApp);
//------------------------------------------------------------------------------
AppState::Code
ResourceStressApp::OnInit() {
// setup IO system
IOSetup ioSetup;
ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
ioSetup.Assigns.Add("tex:", ORYOL_SAMPLE_URL);
IO::Setup(ioSetup);
// setup Gfx system
auto gfxSetup = GfxSetup::Window(600, 400, "Oryol Resource Stress Test");
gfxSetup.DefaultPassAction = PassAction::Clear(glm::vec4(0.5f, 0.5f, 0.5f, 1.0f));
gfxSetup.ResourcePoolSize[GfxResourceType::Mesh] = MaxNumObjects + 32;
gfxSetup.ResourcePoolSize[GfxResourceType::Texture] = MaxNumObjects + 32;
gfxSetup.ResourcePoolSize[GfxResourceType::Pipeline] = MaxNumObjects + 32;
gfxSetup.ResourcePoolSize[GfxResourceType::Shader] = 4;
Gfx::Setup(gfxSetup);
// setup debug text rendering
Dbg::Setup();
// setup the shader that is used by all objects
this->shader = Gfx::CreateResource(Shader::Setup());
// setup matrices
const float fbWidth = (const float) Gfx::DisplayAttrs().FramebufferWidth;
const float fbHeight = (const float) Gfx::DisplayAttrs().FramebufferHeight;
this->proj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
this->view = glm::mat4();
this->texBlueprint.Sampler.MinFilter = TextureFilterMode::LinearMipmapLinear;
this->texBlueprint.Sampler.MagFilter = TextureFilterMode::Linear;
this->texBlueprint.Sampler.WrapU = TextureWrapMode::ClampToEdge;
this->texBlueprint.Sampler.WrapV = TextureWrapMode::ClampToEdge;
return App::OnInit();
}
//------------------------------------------------------------------------------
AppState::Code
ResourceStressApp::OnRunning() {
// delete and create objects
this->frameCount++;
this->updateObjects();
this->createObjects();
this->showInfo();
Gfx::BeginPass();
for (const auto& obj : this->objects) {
// only render objects that have successfully loaded
const Id& tex = obj.drawState.FSTexture[Shader::tex];
if (Gfx::QueryResourceInfo(tex).State == ResourceState::Valid) {
Gfx::ApplyDrawState(obj.drawState);
Shader::vsParams vsParams;
vsParams.mvp = this->proj * this->view * obj.modelTransform;
Gfx::ApplyUniformBlock(vsParams);
Gfx::Draw();
}
}
Dbg::DrawTextBuffer();
Gfx::EndPass();
Gfx::CommitFrame();
// quit or keep running?
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
ResourceStressApp::OnCleanup() {
Dbg::Discard();
Gfx::Discard();
IO::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
void
ResourceStressApp::createObjects() {
if (this->objects.Size() >= MaxNumObjects) {
return;
}
if (Gfx::QueryFreeResourceSlots(GfxResourceType::Mesh) == 0) {
return;
}
if (Gfx::QueryFreeResourceSlots(GfxResourceType::Texture) == 0) {
return;
}
// create a cube object
// NOTE: we're deliberatly not sharing resources to actually
// put some stress on the resource system
Object obj;
obj.label = Gfx::PushResourceLabel();
ShapeBuilder shapeBuilder;
shapeBuilder.Layout = {
{ VertexAttr::Position, VertexFormat::Float3 },
{ VertexAttr::TexCoord0, VertexFormat::Float2 }
};
shapeBuilder.Box(0.1f, 0.1f, 0.1f, 1);
obj.drawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build());
auto ps = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, this->shader);
obj.drawState.Pipeline = Gfx::CreateResource(ps);
obj.drawState.FSTexture[Shader::tex] = Gfx::LoadResource(TextureLoader::Create(
TextureSetup::FromFile(Locator::NonShared("tex:lok_dxt1.dds"), this->texBlueprint)));
glm::vec3 pos = glm::ballRand(2.0f) + glm::vec3(0.0f, 0.0f, -6.0f);
obj.modelTransform = glm::translate(glm::mat4(), pos);
this->objects.Add(obj);
Gfx::PopResourceLabel();
}
//------------------------------------------------------------------------------
void
ResourceStressApp::updateObjects() {
for (int i = this->objects.Size() - 1; i >= 0; i--) {
Object& obj = this->objects[i];
// check if object should be destroyed (it will be
// destroyed after the texture object had been valid for
// at least 3 seconds, or if it failed to load)
const Id& tex = obj.drawState.FSTexture[Shader::tex];
const auto info = Gfx::QueryResourceInfo(tex);
if ((info.State == ResourceState::Failed) ||
((info.State == ResourceState::Valid) && (info.StateAge > (20 * 60)))) {
Gfx::DestroyResources(obj.label);
this->objects.Erase(i);
}
}
}
//------------------------------------------------------------------------------
void
ResourceStressApp::showInfo() {
ResourcePoolInfo texPoolInfo = Gfx::QueryResourcePoolInfo(GfxResourceType::Texture);
ResourcePoolInfo mshPoolInfo = Gfx::QueryResourcePoolInfo(GfxResourceType::Mesh);
Dbg::PrintF("texture pool\r\n"
" num slots: %d, free: %d, used: %d\r\n"
" by state:\r\n"
" initial: %d\r\n"
" setup: %d\r\n"
" pending: %d\r\n"
" valid: %d\r\n"
" failed: %d\r\n\n",
texPoolInfo.NumSlots, texPoolInfo.NumFreeSlots, texPoolInfo.NumUsedSlots,
texPoolInfo.NumSlotsByState[ResourceState::Initial],
texPoolInfo.NumSlotsByState[ResourceState::Setup],
texPoolInfo.NumSlotsByState[ResourceState::Pending],
texPoolInfo.NumSlotsByState[ResourceState::Valid],
texPoolInfo.NumSlotsByState[ResourceState::Failed]);
Dbg::PrintF("mesh pool\r\n"
" num slots: %d, free: %d, used: %d\r\n"
" by state:\r\n"
" initial: %d\r\n"
" setup: %d\r\n"
" pending: %d\r\n"
" valid: %d\r\n"
" failed: %d",
mshPoolInfo.NumSlots, mshPoolInfo.NumFreeSlots, mshPoolInfo.NumUsedSlots,
mshPoolInfo.NumSlotsByState[ResourceState::Initial],
mshPoolInfo.NumSlotsByState[ResourceState::Setup],
mshPoolInfo.NumSlotsByState[ResourceState::Pending],
mshPoolInfo.NumSlotsByState[ResourceState::Valid],
mshPoolInfo.NumSlotsByState[ResourceState::Failed]);
}
| 36.623256
| 93
| 0.578613
|
infancy
|
5340412ccab57648a683999611fdee489474ea5c
| 21,781
|
cpp
|
C++
|
cpp/src/datacentric/dc/platform/data_source/mongo/temporal_mongo_data_source.cpp
|
datacentricorg/datacentric-cpp
|
252f642b1a81c2475050d48e9564eec0a561907e
|
[
"Apache-2.0"
] | 2
|
2019-08-08T01:29:02.000Z
|
2019-08-18T19:19:00.000Z
|
cpp/src/datacentric/dc/platform/data_source/mongo/temporal_mongo_data_source.cpp
|
datacentricorg/datacentric-cpp
|
252f642b1a81c2475050d48e9564eec0a561907e
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/datacentric/dc/platform/data_source/mongo/temporal_mongo_data_source.cpp
|
datacentricorg/datacentric-cpp
|
252f642b1a81c2475050d48e9564eec0a561907e
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright (C) 2013-present The DataCentric 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 <dc/precompiled.hpp>
#include <dc/implement.hpp>
#include <dc/platform/data_source/mongo/temporal_mongo_data_source.hpp>
#include <dc/platform/context/context_base.hpp>
#include <dc/types/record/deleted_record.hpp>
#include <dc/types/record/data_type_info.hpp>
#include <dc/attributes/class/index_elements_attribute.hpp>
#include <dot/mongo/mongo_db/mongo/collection.hpp>
#include <dc/platform/data_source/mongo/temporal_mongo_query.hpp>
namespace dc
{
Record TemporalMongoDataSourceImpl::load_or_null(TemporalId id, dot::Type data_type)
{
if (cutoff_time != nullptr)
{
// If revision_time_constraint is not null, return null for any
// id that is not strictly before the constraint TemporalId
if (id >= cutoff_time.value()) return nullptr;
}
dot::Query query = dot::make_query(get_or_create_collection(data_type), data_type);
dot::ObjectCursorWrapperBase cursor = query->where(new dot::OperatorWrapperImpl("_id", "$eq", id))
->limit(1)
->get_cursor();
if (cursor->begin() != cursor->end())
{
dot::Object obj = *(cursor->begin());
if (!obj.is<DeletedRecord>())
{
Record rec = obj.as<Record>();
if (!data_type->is_assignable_from(rec->get_type()))
{
// If cast result is null, the record was found but it is an instance
// of class that is not derived from TRecord, in this case the API
// requires error message, not returning null
throw dot::Exception(dot::String::format(
"Stored Type {0} for TemporalId={1} and "
"Key={2} is not an instance of the requested Type {3}.", rec->get_type()->name(),
id.to_string(), rec->get_key(), data_type->name()
));
}
// Now we use get_cutoff_time() for the full check
dot::Nullable<TemporalId> cutoff_time = get_cutoff_time(rec->data_set);
if (cutoff_time != nullptr)
{
// Return null for any record that has TemporalId
// that is greater than or equal to cutoff_time.
if (id >= cutoff_time.value()) return nullptr;
}
rec->init(context);
return rec;
}
}
return nullptr;
}
Record TemporalMongoDataSourceImpl::load_or_null(Key key, TemporalId load_from)
{
// dot::String key in semicolon delimited format used in the lookup
dot::String key_value = key->to_string();
dot::Type record_type = dot::typeof<Record>();
dot::Query base_query = dot::make_query(get_or_create_collection(key->get_type()), key->get_type())
->where(new dot::OperatorWrapperImpl("_key", "$eq", key_value))
;
dot::Query query_with_final_constraints = apply_final_constraints(base_query, load_from);
dot::ObjectCursorWrapperBase cursor = query_with_final_constraints
->sort_by_descending(record_type->get_field("_dataset"))
->then_by_descending(record_type->get_field("_id"))
->limit(1)
->get_cursor();
if (cursor->begin() != cursor->end())
{
dot::Object obj = *(cursor->begin());
if (!obj.is<DeletedRecord>())
{
Record rec = obj.as<Record>();
rec->init(context);
return rec;
}
}
return nullptr;
}
void TemporalMongoDataSourceImpl::save_many(dot::List<Record> records, TemporalId save_to)
{
check_not_read_only(save_to);
auto collection = get_or_create_collection(records[0]->get_type());
// Iterate over list elements to populate fields
for(Record rec : records)
{
// This method guarantees that TemporalIds will be in strictly increasing
// order for this instance of the data source class always, and across
// all processes and machine if they are not created within the same
// second.
TemporalId object_id = create_ordered_object_id();
// TemporalId of the record must be strictly later
// than TemporalId of the dataset where it is stored
if (object_id <= save_to)
throw dot::Exception(dot::String::format(
"Attempting to save a record with TemporalId={0} that is later "
"than TemporalId={1} of the dataset where it is being saved.", object_id.to_string(), save_to.to_string()));
// Assign ID and DataSet, and only then initialize, because
// initialization code may use record.ID and record.DataSet
rec->id = object_id;
rec->data_set = save_to;
rec->init(context);
}
collection->insert_many(records);
}
TemporalMongoQuery TemporalMongoDataSourceImpl::get_query(TemporalId data_set, dot::Type type)
{
return make_temporal_mongo_query(get_or_create_collection(type), type, this, data_set);
}
void TemporalMongoDataSourceImpl::delete_record(Key key, TemporalId delete_in)
{
check_not_read_only(delete_in);
dot::Collection collection = get_or_create_collection(key->get_type());
DeletedRecord record = make_deleted_record(key);
TemporalId object_id = create_ordered_object_id();
// TemporalId of the record must be strictly later
// than TemporalId of the dataset where it is stored
if (object_id <= delete_in)
throw dot::Exception(dot::String::format(
"Attempting to save a record with TemporalId={0} that is later "
"than TemporalId={1} of the dataset where it is being saved.", object_id.to_string(), delete_in.to_string()));
// Assign id and data_set, and only then initialize, because
// initialization code may use record.id and record.data_set
record->id = object_id;
record->data_set = delete_in;
collection->insert_one(record);
}
dot::Query TemporalMongoDataSourceImpl::apply_final_constraints(dot::Query query, TemporalId load_from)
{
// Get lookup list by expanding the list of imports to arbitrary
// depth with duplicates and cyclic references removed.
//
// The list will not include datasets that are after the value of
// CutoffTime if specified, or their imports (including
// even those imports that are earlier than the constraint).
dot::HashSet<TemporalId> lookup_set = get_data_set_lookup_list(load_from);
dot::List<TemporalId> lookup_list = dot::make_list<TemporalId>(std::vector<TemporalId>(lookup_set->begin(), lookup_set->end()));
// Apply constraint that the value is _dataset is
// one of the elements of dataSetLookupList_
dot::Query result = query->where(new dot::OperatorWrapperImpl("_dataset", "$in", lookup_list));
// Apply revision time constraint. By making this constraint the
// last among the constraints, we optimize the use of the index.
//
// The property savedBy_ is set using either CutoffTime element.
// Only one of these two elements can be set at a given time.
dot::Nullable<TemporalId> cutoff_time = get_cutoff_time(load_from);
if (cutoff_time != nullptr)
{
result = result->where(new dot::OperatorWrapperImpl("_id", "$lt", cutoff_time.value()));
}
return result;
}
dot::Nullable<TemporalId> TemporalMongoDataSourceImpl::get_data_set_or_empty(dot::String data_set_name, TemporalId load_from)
{
TemporalId result;
if (data_set_dict_->try_get_value(data_set_name, result))
{
// Check if already cached, return if found
return result;
}
else
{
// Otherwise load from storage (this also updates the dictionaries)
DataSetKey data_set_key = make_data_set_key();
data_set_key->data_set_name = data_set_name;
DataSet data_set_data = (dc::DataSet)load_or_null(data_set_key, load_from);
// If not found, return TemporalId.Empty
if (data_set_data == nullptr) return nullptr;
// Get or create dataset detail record
DataSetDetailKey data_set_detail_key = make_data_set_detail_key();
data_set_detail_key->data_set_id = data_set_data->id;
DataSetDetail data_set_detail_data = (dc::DataSetDetail)load_or_null(data_set_detail_key, load_from);
if (data_set_detail_data == nullptr)
{
data_set_detail_data = make_data_set_detail_data();
data_set_detail_key->data_set_id = data_set_data->id;
context.lock()->save_one(data_set_detail_data, load_from);
}
// Cache TemporalId for the dataset and its parent
data_set_dict_[data_set_name] = data_set_data->id;
data_set_owners_dict_[data_set_data->id] = data_set_data->data_set;
dot::HashSet<TemporalId> import_set;
// Build and cache dataset lookup list if not found
if (!data_set_parent_dict_->try_get_value(data_set_data->id, import_set))
{
import_set = build_data_set_lookup_list(data_set_data);
data_set_parent_dict_->add(data_set_data->id, import_set);
}
return data_set_data->id;
}
}
void TemporalMongoDataSourceImpl::save_data_set(DataSet data_set_data, TemporalId save_to)
{
// Save dataset to storage. This updates its Id
// to the new TemporalId created during save
context.lock()->save_one(data_set_data, save_to);
// Cache TemporalId for the dataset and its parent
data_set_dict_[data_set_data->get_key()] = data_set_data->id;
data_set_owners_dict_[data_set_data->id] = data_set_data->data_set;
// Update lookup list dictionary
dot::HashSet<TemporalId> lookup_list = build_data_set_lookup_list(data_set_data);
data_set_parent_dict_->add(data_set_data->id, lookup_list);
}
dot::HashSet<TemporalId> TemporalMongoDataSourceImpl::get_data_set_lookup_list(TemporalId load_from)
{
dot::HashSet<TemporalId> result;
// Root dataset has no imports (there is not even a record
// where these imports can be specified).
//
// Return list containing only the root dataset (TemporalId.Empty) and exit
if (load_from == TemporalId::empty)
{
result = dot::make_hash_set<TemporalId>();
result->add(TemporalId::empty);
return result;
}
if (data_set_parent_dict_->try_get_value(load_from, result))
{
// Check if the lookup list is already cached, return if yes
return result;
}
else
{
// Otherwise load from storage (returns null if not found)
DataSet data_set_data = (dc::DataSet)load_or_null(load_from, dot::typeof<dc::DataSet>());
if (data_set_data == nullptr) throw dot::Exception(dot::String::format("Dataset with TemporalId={0} is not found.", load_from.to_string()));
if (data_set_data->data_set != TemporalId::empty) throw dot::Exception(dot::String::format("Dataset with TemporalId={0} is not stored in root dataset.", load_from.to_string()));
// Build the lookup list
result = build_data_set_lookup_list(data_set_data);
// Add to dictionary and return
data_set_parent_dict_->add(load_from, result);
return result;
}
}
DataSetDetail TemporalMongoDataSourceImpl::get_data_set_detail_or_empty(TemporalId detail_for)
{
DataSetDetail result;
if (detail_for == TemporalId::empty)
{
// Root dataset does not have details
// as it has no parent where the details
// would be stored, and storing details
// in the dataset itself would subject
// them to their own settings.
//
// Accordingly, return null.
return nullptr;
}
else if (data_set_detail_dict_->try_get_value(detail_for, result))
{
// Check if already cached, return if found
return result;
}
else
{
// Get dataset parent from the dictionary.
// We should not get here unless the value
// is already cached.
TemporalId parent_id = data_set_owners_dict_[detail_for];
// Otherwise try loading from storage (this also updates the dictionaries)
DataSetDetailKey data_set_detail_key = make_data_set_detail_key();
data_set_detail_key->data_set_id = detail_for;
result = (DataSetDetail)load_or_null(data_set_detail_key, parent_id);
// Cache in dictionary even if null
data_set_detail_dict_[detail_for] = result;
return result;
}
}
dot::Nullable<TemporalId> TemporalMongoDataSourceImpl::get_cutoff_time(TemporalId data_set_id)
{
// Get imports cutoff time for the dataset detail record.
// If the record is not found, consider its CutoffTime null.
DataSetDetail data_set_detail_data = get_data_set_detail_or_empty(data_set_id);
dot::Nullable<TemporalId> data_set_cutoff_time = data_set_detail_data != nullptr ? data_set_detail_data->cutoff_time : nullptr;
// If CutoffTime is set for both data source and dataset,
// this method returns the earlier of the two values.
dot::Nullable<TemporalId> result = TemporalId::min(cutoff_time, data_set_cutoff_time);
return result;
}
dot::Nullable<TemporalId> TemporalMongoDataSourceImpl::get_imports_cutoff_time(TemporalId data_set_id)
{
// Get dataset detail record
DataSetDetail data_set_detail_data = get_data_set_detail_or_empty(data_set_id);
// Return null if the record is not found
if (data_set_detail_data != nullptr) return data_set_detail_data->imports_cutoff_time;
else return nullptr;
}
dot::Collection TemporalMongoDataSourceImpl::get_or_create_collection(dot::Type data_type)
{
// Check if collection Object has already been cached
// for this type and return cached result if found
dot::Object collection_obj;
if (collection_dict_->try_get_value(data_type, collection_obj))
{
dot::Collection cached_result = collection_obj.as<dot::Collection>();
return cached_result;
}
// Collection name is root class name of the record without prefix
dot::String collection_name = DataTypeInfoImpl::get_or_create(data_type)->get_collection_name();
// Get interfaces to base and typed collections for the same name
dot::Collection typed_collection = db_->get_collection(collection_name);
//--- Load standard index types
// Each data type has an index for optimized loading by key.
// This index consists of Key in ascending order, followed by
// DataSet and ID in descending order.
dot::List<std::tuple<dot::String, int>> load_index_keys = dot::make_list<std::tuple<dot::String, int>>();
load_index_keys->add({ "_key", 1 }); // .key
load_index_keys->add({ "_dataset", -1 }); // .data_set
load_index_keys->add({ "_id", -1 }); // .id
// Use index definition convention to specify the index name
dot::String load_index_name = "Key-DataSet-Id";
dot::IndexOptions load_index_options = dot::make_index_options();
load_index_options->name = load_index_name;
typed_collection->create_index(load_index_keys, load_index_options);
//--- Load custom index types
// Additional indices are provided using IndexAttribute for the class.
// Get a sorted dictionary of (definition, name) pairs
// for the inheritance chain of the specified type.
dot::Dictionary<dot::String, dot::String> index_dict = IndexElementsAttributeImpl::get_attributes_dict(data_type);
// Iterate over the dictionary to define the index
for (auto index_info : index_dict)
{
dot::String index_definition = index_info.first;
dot::String index_name = index_info.second;
// Parse index definition to get a list of (ElementName,SortOrder) tuples
dot::List<std::tuple<dot::String, int>> index_tokens = IndexElementsAttributeImpl::parse_definition(index_definition, data_type);
if (index_name == nullptr) throw dot::Exception("Index name cannot be null.");
// Add to indexes for the collection
dot::IndexOptions index_opt = dot::make_index_options();
index_opt->name = index_name;
typed_collection->create_index(index_tokens, index_opt);
}
// Add the result to the collection dictionary and return
collection_dict_->add(data_type, typed_collection);
return typed_collection;
}
dot::HashSet<TemporalId> TemporalMongoDataSourceImpl::build_data_set_lookup_list(DataSet data_set_data)
{
// Delegate to the second overload
dot::HashSet<TemporalId> result = dot::make_hash_set<TemporalId>();
build_data_set_lookup_list(data_set_data, result);
return result;
}
void TemporalMongoDataSourceImpl::build_data_set_lookup_list(DataSet data_set_data, dot::HashSet<TemporalId> result)
{
// Return if the dataset is null or has no imports
if (data_set_data == nullptr) return;
// Error message if dataset has no Id or Key set
if (data_set_data->id.is_empty())
throw dot::Exception("Required TemporalId value is not set.");
if (data_set_data->get_key().is_empty())
throw dot::Exception("Required String value is not set.");
dot::Nullable<TemporalId> cutoff_time = get_cutoff_time(data_set_data->data_set);
if (cutoff_time != nullptr && data_set_data->id >= cutoff_time.value())
{
// Do not add if revision time constraint is set and is before this dataset.
// In this case the import datasets should not be added either, even if they
// do not fail the revision time constraint
return;
}
// Add self to the result
result->add(data_set_data->id);
// Add imports to the result
if (data_set_data->imports != nullptr)
{
for (TemporalId data_set_id : data_set_data->imports)
{
// Dataset cannot include itself as its import
if (data_set_data->id == data_set_id)
throw dot::Exception(dot::String::format(
"Dataset {0} with TemporalId={1} includes itself in the list of its imports."
, data_set_data->get_key(), data_set_data->id.to_string()));
if (!result->contains(data_set_id))
{
result->add(data_set_id);
// Add recursively if not already present in the hashset
dot::HashSet<TemporalId> cached_import_list = get_data_set_lookup_list(data_set_id);
for (TemporalId import_id : cached_import_list)
{
result->add(import_id);
}
}
}
}
}
void TemporalMongoDataSourceImpl::check_not_read_only(TemporalId data_set_id)
{
if (read_only)
throw dot::Exception(dot::String::format(
"Attempting write operation for data source {0} where ReadOnly flag is set.", data_source_name));
DataSetDetail data_set_detail_data = get_data_set_detail_or_empty(data_set_id);
if (data_set_detail_data != nullptr && data_set_detail_data->read_only.has_value() && data_set_detail_data->read_only.value())
throw dot::Exception(dot::String::format(
"Attempting write operation for dataset {0} where ReadOnly flag is set.", data_set_id.to_string()));
if (cutoff_time != nullptr)
throw dot::Exception(dot::String::format(
"Attempting write operation for data source {0} where "
"cutoff_time is set. Historical view of the data cannot be written to.", data_source_name));
if (data_set_detail_data != nullptr && data_set_detail_data->cutoff_time != nullptr)
throw dot::Exception(dot::String::format(
"Attempting write operation for the dataset {0} where "
"CutoffTime is set. Historical view of the data cannot be written to.", data_set_id.to_string()));
}
}
| 43.130693
| 189
| 0.635003
|
datacentricorg
|
5343d6120435da335650ff81116a483477fb7ea9
| 8,397
|
cpp
|
C++
|
src/graphics/szgrender.cpp
|
IllinoisSimulatorLab/szg
|
b9f9a2380107450c2f181ac6372427a0112b5ffe
|
[
"BSD-3-Clause"
] | 2
|
2017-01-07T23:43:03.000Z
|
2017-09-29T14:31:09.000Z
|
src/graphics/szgrender.cpp
|
IllinoisSimulatorLab/szg
|
b9f9a2380107450c2f181ac6372427a0112b5ffe
|
[
"BSD-3-Clause"
] | null | null | null |
src/graphics/szgrender.cpp
|
IllinoisSimulatorLab/szg
|
b9f9a2380107450c2f181ac6372427a0112b5ffe
|
[
"BSD-3-Clause"
] | null | null | null |
//********************************************************
// Syzygy is licensed under the BSD license v2
// see the file SZG_CREDITS for details
//********************************************************
#include "arPrecompiled.h"
#define SZG_DO_NOT_EXPORT
#include "arGraphicsClient.h"
#include "arFramerateGraph.h"
#include "arGUIWindowManager.h"
#include "arGUIXMLParser.h"
#include "arLogStream.h"
#include "arGraphicsPluginNode.h"
arGraphicsClient graphicsClient;
arFramerateGraph framerateGraph;
arGUIWindowManager* windowManager;
arGUIXMLParser* guiParser;
bool framerateThrottle = false;
bool fDrawPerformance = false;
bool fExiting = false;
bool fReload = false;
bool fPause = false;
arLock pauseLock; // with pauseVar, around fPause, between message and display threads.
arConditionVar pauseVar("szgrender-pause");
string dataPath("NULL");
string textPath("NULL");
bool loadParameters(arSZGClient& cli) {
// Use our screen's parameters.
graphicsClient.configure(&cli);
dataPath = cli.getDataPath();
graphicsClient.addDataBundlePathMap("SZG_DATA", dataPath);
graphicsClient.addDataBundlePathMap("SZG_PYTHON", cli.getDataPathPython());
arGraphicsPluginNode::setSharedLibSearchPath(cli.getAttribute("SZG_EXEC", "path"));
return true;
}
void shutdownAction() {
if (fExiting)
return;
fExiting = true;
ar_log_debug() << "szgrender shutdown.\n";
// Let the draw loop's _cliSync.consume() finish.
graphicsClient._cliSync.skipConsumption();
// exit() only from the draw loop, to avoid Win32 crashes.
}
void messageTask(void* pClient) {
arSZGClient* cli = (arSZGClient*)pClient;
string messageType, messageBody;
int messageID;
while (!fExiting &&
(messageID = cli->receiveMessage(&messageType, &messageBody)) && messageType != "quit") {
// receiveMessage() blocks in language/arStructuredDataParser.cpp getNextInternal().
// If fExiting is set to true, it should unblock and this thread should die.
if (messageType=="performance") {
fDrawPerformance = messageBody=="on";
graphicsClient.drawFrameworkObjects(fDrawPerformance);
}
else if (messageType=="log") {
(void)ar_setLogLevel( messageBody );
}
else if (messageType=="screenshot") {
// copypaste with framework/arMasterSlaveFramework.cpp
if (dataPath == "NULL") {
ar_log_error() << "szgrender screenshot failed: no SZG_DATA/path.\n";
}
else{
if (messageBody != "NULL") {
int temp[4];
ar_parseIntString(messageBody, temp, 4);
graphicsClient.requestScreenshot(dataPath, temp[0], temp[1], temp[2], temp[3]);
}
}
}
else if (messageType=="delay") {
framerateThrottle = messageBody=="on";
}
else if ( messageType == "display_name" ) {
cli->messageResponse( messageID, cli->getMode("graphics") );
}
else if (messageType=="pause") {
if (messageBody == "on") {
arGuard _(pauseLock, "szgrender messageTask pause on");
fPause = true;
}
else if (messageBody == "off") {
arGuard(pauseLock, "szgrender messageTask pause off");
fPause = false;
pauseVar.signal();
}
else
ar_log_error() << "szgrender: unexpected pause '" << messageBody << "', should be on or off.\n";
}
else if (messageType=="color") {
float c[3] = {0, 0, 0};
if (messageBody == "off") {
ar_log_remark() << "szgrender: color override off.\n";
graphicsClient.setOverrideColor(arVector3(-1, -1, -1));
}
else{
ar_parseFloatString(messageBody, c, 3);
ar_log_remark() << "szgrender screen color (" << c[0] << ", " << c[1] << ", " << c[2] << ").\n";
graphicsClient.setOverrideColor(arVector3(c));
}
}
else if (messageType=="reload") {
// Multiple reload messages might be ignored if this message thread
// gets them faster than the draw thread notices them.
// Not a problem, though, in practice: the "last" message gets processed.
fReload = true;
}
else {
cli->messageResponse( messageID, "ERROR: szgrender: unknown message type '"+messageType+"'" );
}
}
shutdownAction();
}
// GUI window callbacks. "Init GL" and "mouse" callbacks are not used.
void ar_guiWindowEvent(arGUIWindowInfo* wi) {
if (!wi)
return;
arGUIWindowManager* wm = wi->getWindowManager();
if (!wm)
return;
switch (wi->getState()) {
case AR_WINDOW_RESIZE:
wm->setWindowViewport(wi->getWindowID(), 0, 0, wi->getSizeX(), wi->getSizeY());
break;
case AR_WINDOW_CLOSE:
shutdownAction();
break;
default:
// avoid compiler warning
break;
}
}
void ar_guiWindowKeyboard(arGUIKeyInfo* ki) {
if (!ki)
return;
if (ki->getState() == AR_KEY_DOWN) {
switch (ki->getKey()) {
case AR_VK_ESC:
shutdownAction();
break;
case AR_VK_P:
fDrawPerformance = !fDrawPerformance;
graphicsClient.drawFrameworkObjects(fDrawPerformance);
break;
default:
// avoid compiler warning
break;
}
}
}
int main(int argc, char** argv) {
arSZGClient szgClient;
szgClient.simpleHandshaking(false);
const bool fInit = szgClient.init(argc, argv);
ar_log_debug() << "szgrender " << ar_versionInfo() << "szgrender " << ar_versionString();
if (!szgClient)
return szgClient.failStandalone(fInit);
string currDir;
if (!ar_getWorkingDirectory( currDir )) {
ar_log_critical() << "Failed to get working directory.\n";
} else {
ar_log_critical() << "Directory: " << currDir << ar_endl;
}
const string screenLock = szgClient.getComputerName() + "/" + szgClient.getMode("graphics");
int graphicsID = -1;
if (!szgClient.getLock(screenLock, graphicsID)) {
ar_log_critical() << "screen locked by component " << graphicsID << ".\n";
if (!szgClient.sendInitResponse(false))
cerr << "szgrender error: maybe szgserver died.\n";
return 1;
}
framerateGraph.addElement("fps", 300, 100, arVector3(1, 1, 1));
graphicsClient.addFrameworkObject(&framerateGraph);
if (!szgClient.sendInitResponse(true)) {
cerr << "szgrender error: maybe szgserver died.\n";
}
arThread dummy(messageTask, &szgClient);
// Default to a non-threaded window manager.
windowManager = new arGUIWindowManager(
ar_guiWindowEvent, ar_guiWindowKeyboard, NULL, NULL, false);
// graphicsClient configures windows and starts window threads,
// but szgRender's main() has the event loop.
graphicsClient.setWindowManager(windowManager);
if (!loadParameters(szgClient))
ar_log_remark() << "szgrender parameter load failed.\n";
graphicsClient.setNetworks(szgClient.getNetworks("graphics"));
// Start the connection threads and window threads.
graphicsClient.start(szgClient);
// Framelock assumes the window manager is single-threaded,
// so this is the display thread.
// Parse window config to decide whether or not to use framelock.
windowManager->findFramelock();
if (!szgClient.sendStartResponse(true)) {
cerr << "szgrender error: maybe szgserver died.\n";
}
while (!fExiting) {
pauseLock.lock("szgrender main loop");
while (fPause) {
pauseVar.wait(pauseLock);
}
pauseLock.unlock();
const ar_timeval time1 = ar_time();
if (fReload) {
fReload = false;
(void)loadParameters(szgClient);
// Make new windows but don't start the underlying synchronization objects.
graphicsClient.start(szgClient, false);
}
// Process scenegraph events, draw, and sync
// (via callbacks to the arSyncDataClient embedded inside the arGraphicsClient).
graphicsClient._cliSync.consume();
if (framerateThrottle) {
ar_usleep(200000);
}
windowManager->processWindowEvents();
framerateGraph.getElement("fps")->pushNewValue(
1000000.0 / ar_difftimeSafe(ar_time(), time1));
}
szgClient.messageTaskStop();
graphicsClient._cliSync.stop();
// We're the display thread. Do this before exiting.
windowManager->deactivateFramelock();
windowManager->deleteAllWindows();
return 0;
}
| 31.215613
| 105
| 0.640586
|
IllinoisSimulatorLab
|
c7282262fd465904e45bed337de6db02e61c8422
| 2,754
|
cpp
|
C++
|
BAI_12.cpp
|
anhtuanptit97/anhtuan
|
5b1d49cb21368079a8cdd4139d0e6522d054700b
|
[
"Unlicense"
] | null | null | null |
BAI_12.cpp
|
anhtuanptit97/anhtuan
|
5b1d49cb21368079a8cdd4139d0e6522d054700b
|
[
"Unlicense"
] | null | null | null |
BAI_12.cpp
|
anhtuanptit97/anhtuan
|
5b1d49cb21368079a8cdd4139d0e6522d054700b
|
[
"Unlicense"
] | null | null | null |
#include<iostream>
#include<cmath>
using namespace std;
class fraction{
private:
int num;
int den;
public:
fraction(int ,int );
fraction();
void lowterms();
void dislay();
void set_num(int tnum){
this->num=tnum;
}
void set_den(int tden){
this->den=tden;
}
void sum(fraction,fraction);
void sub(fraction,fraction);
void mul(fraction,fraction);
void div(fraction,fraction);
};
fraction::fraction(int tnum, int tden){
if(tden==0){
cout<<"Illegal fraction: division by 0"<<endl;
exit(1);
}
this->num=tnum;
this->den=tden;
}
fraction::fraction(){
this->num=1;
this->den=1;
}
void fraction::lowterms(){
long tnum, tden, temp, gcd;
tnum = labs(num);
tden = labs(den);
if(tden==0){
cout<< "Illegal fraction: division by 0"<<endl;
exit(1);
}
else if( tnum==0 ) {
num=0; den = 1;
return;
}
while(tnum != 0){
if(tnum < tden){
temp=tnum; tnum=tden; tden=temp;
}
tnum = tnum - tden;
}
gcd = tden;
num = num / gcd;
den = den / gcd;
}
void fraction::sum(fraction one,fraction two){
this->num=two.den*one.num+two.num*one.den;
this->den=one.den*two.den;
this->lowterms();
}
void fraction::sub(fraction one,fraction two){
this->num=two.den*one.num-two.num*one.den;
this->den=one.den*two.den;
this->lowterms();
}
void fraction::mul(fraction one,fraction two){
this->num=two.num*one.num;
this->den=one.den*two.den;
this->lowterms();
}
void fraction::div(fraction one,fraction two){
this->num=one.num*one.den;
this->den=one.den*two.num;
this->lowterms();
}
void fraction::dislay(){
cout << this->num<<"/"<<this->den;
}
class dislaytable{
private:
int num;
public:
dislaytable(int);
void add();
void dislay();
};
dislaytable::dislaytable(int tnum){
this->num=tnum;
}
void dislaytable::add(){
int tnum;
do{
cout<<"Input number: ";
cin >> tnum;
if(tnum!=0){
this->num=tnum;
break;
}
cout<< "Illegal fraction: division by 0"<<endl;
}while(1);
}
void dislaytable::dislay(){
fraction temp1(1,this->num);
fraction temp2(1,this->num);
cout<<"\t";
for(int i=1; i <this->num;i++){
temp1.set_num(i);
temp1.set_den(this->num);
temp1.lowterms();
temp1.dislay();
cout<<"\t";
}
cout<<endl<<"---------------------------------------------"<<endl;
for(int i=1; i <this->num;i++){
temp1.set_num(i);
temp1.set_den(this->num);
temp1.lowterms();
temp1.dislay();
cout<<"\t";
for(int j=1;j <this->num;j++){
temp1.set_num(i);
temp2.set_num(j);
temp1.set_den(this->num);
temp2.set_den(this->num);
temp1.mul(temp1,temp2);
temp1.dislay();
cout<<"\t";
}
cout<<endl;
}
}
| 19.258741
| 68
| 0.582426
|
anhtuanptit97
|
c72bca868e48f437a7b9e5dde5cd37e436ba5ea7
| 523
|
cpp
|
C++
|
Code-Chef/easy/CLEANUP.cpp
|
kishorevarma369/Competitive-Programming
|
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
|
[
"MIT"
] | 1
|
2019-05-20T14:38:05.000Z
|
2019-05-20T14:38:05.000Z
|
Code-Chef/easy/CLEANUP.cpp
|
kishorevarma369/Competitive-Programming
|
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
|
[
"MIT"
] | null | null | null |
Code-Chef/easy/CLEANUP.cpp
|
kishorevarma369/Competitive-Programming
|
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
|
[
"MIT"
] | null | null | null |
/*
Cleaning Up
*/
#include<bits/stdc++.h>
using namespace std;
void fun()
{
int m,n,k,i;
cin>>m>>n;
vector<int> v(m+1,0);
for(i=0;i<n;i++)
{
cin>>k;
v[k]=1;
}
k=0;
for(i=1;i<=m;i++)
{
if(v[i]==0)
{
if(k==0)
{
v[i]=1;
k=1;
cout<<i<<' ';
}
else k=0;
}
}
cout<<'\n';
for(i=2;i<=m;i++) if(!v[i]) cout<<i<<' ';
cout<<'\n';
}
int main(int argc, char const *argv[])
{
int n;
cin>>n;
while(n--)
{
fun();
}
return 0;
}
| 11.12766
| 43
| 0.388145
|
kishorevarma369
|
c72d04c7dcb638babe4a2cc935be8bf799e0caa8
| 652
|
cpp
|
C++
|
transpose of matrices.cpp
|
mohsin5432/CPP-basic
|
453c82cdc1b3412ee0a063cd9053c7556c80bd7a
|
[
"MIT"
] | null | null | null |
transpose of matrices.cpp
|
mohsin5432/CPP-basic
|
453c82cdc1b3412ee0a063cd9053c7556c80bd7a
|
[
"MIT"
] | null | null | null |
transpose of matrices.cpp
|
mohsin5432/CPP-basic
|
453c82cdc1b3412ee0a063cd9053c7556c80bd7a
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
main()
{
int r,c;
cout<<"ENTER THE ROWS OF MATRICES= ";
cin>>r;
cout<<"ENTER THE COLUMN OF MATRICES= ";
cin>>c;
int a[r][c];
for(int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
cout<<"Enter no= ";
cin>>a[i][j];
}
}
cout<<"\t\t\tOrignal Matrice:"<<endl;
for(int i=0;i<r;i++)
{
cout<<"\t\t\t\t";
for (int j=0;j<c;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n\n";
cout<<"\t\t\ttranspose of a matrices:"<<endl;
for(int i=0;i<r;i++)
{
cout<<"\t\t\t\t";
for (int j=0;j<c;j++)
{
cout<<a[j][i]<<" ";
}
cout<<"\n";
}
}
| 15.52381
| 47
| 0.45092
|
mohsin5432
|
c7320c0bde6cd6bc80cbc1ff77276bca42ebe908
| 20,668
|
cpp
|
C++
|
impl/opengl/webgl1es2/src/webgl1es2_shader_program.cpp
|
jfcameron/gdk-graphics
|
1b6d84e044c2c953fd7c9501e628a67e80f4da0d
|
[
"MIT"
] | null | null | null |
impl/opengl/webgl1es2/src/webgl1es2_shader_program.cpp
|
jfcameron/gdk-graphics
|
1b6d84e044c2c953fd7c9501e628a67e80f4da0d
|
[
"MIT"
] | 63
|
2019-07-22T22:49:39.000Z
|
2021-05-10T04:36:27.000Z
|
impl/opengl/webgl1es2/src/webgl1es2_shader_program.cpp
|
jfcameron/gdk-graphics
|
1b6d84e044c2c953fd7c9501e628a67e80f4da0d
|
[
"MIT"
] | 1
|
2020-06-04T07:47:50.000Z
|
2020-06-04T07:47:50.000Z
|
// © 2018 Joseph Cameron - All Rights Reserved
#include <gdkgraphics/buildinfo.h>
#include <gdk/glh.h>
#include <gdk/webgl1es2_shader_program.h>
#include <atomic>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
using namespace gdk;
static constexpr char TAG[] = "shader_program";
//! map of active textures. Allows to overwrite textures with the same names to the same units, since units are very limited.
static std::unordered_map<std::string, GLint> s_ActiveTextureUniformNameToUnit;
static short s_ActiveTextureUnitCounter(0);
const jfc::shared_proxy_ptr<gdk::webgl1es2_shader_program> webgl1es2_shader_program::PinkShaderOfDeath([]()
{
const std::string vertexShaderSource(R"V0G0N(
//Uniforms
uniform mat4 _MVP;
//VertexIn
attribute highp vec3 a_Position;
void main()
{
gl_Position = _MVP * vec4(a_Position,1.0);
}
)V0G0N");
const std::string fragmentShaderSource(R"V0G0N(
const vec4 DEATHLY_PINK = vec4(1,0.2,0.8,1);
void main()
{
gl_FragColor = DEATHLY_PINK;
}
)V0G0N");
return new gdk::webgl1es2_shader_program(vertexShaderSource, fragmentShaderSource);
});
const jfc::shared_proxy_ptr<gdk::webgl1es2_shader_program> webgl1es2_shader_program::AlphaCutOff([]()
{
const std::string vertexShaderSource(R"V0G0N(
//Uniforms
uniform mat4 _MVP;
uniform mat4 _Model;
uniform mat4 _View;
uniform mat4 _Projection;
//VertexIn
attribute highp vec3 a_Position;
attribute mediump vec2 a_UV;
//FragmentIn
varying mediump vec2 v_UV;
void main ()
{
gl_Position = _MVP * vec4(a_Position,1.0);
v_UV = a_UV;
}
)V0G0N");
const std::string fragmentShaderSource(R"V0G0N(
//Uniforms
uniform sampler2D _Texture;
uniform vec2 _UVOffset;
uniform vec2 _UVScale;
//FragmentIn
varying lowp vec2 v_UV;
lowp vec2 uv;
void main()
{
uv = v_UV;
uv += _UVOffset;
uv *= _UVScale;
vec4 frag = texture2D(_Texture, uv);
if (frag[3] < 1.0) discard;
gl_FragColor = vec4(frag.xyz, 0.5);
}
)V0G0N");
auto p = new gdk::webgl1es2_shader_program(vertexShaderSource, fragmentShaderSource);
return p;
});
static void perform_shader_code_preprocessing_done_to_both_vertex_and_fragment_stages(std::string &aSource)
{
aSource.insert(0, std::string("#define ").append(gdkgraphics_BuildInfo_TargetPlatform).append("\n"));
#if defined JFC_TARGET_PLATFORM_Emscripten
// version must be the first line in source. version must be present for WebGL platforms
aSource.insert(0, std::string("#version 100\n"));
#else
// remove precison prefixes (required by wasm)
aSource.insert(0, std::string("#define highp\n"));
aSource.insert(0, std::string("#define mediump\n"));
aSource.insert(0, std::string("#define lowp\n"));
#endif
}
static void perform_shader_code_preprocessing_done_to_only_fragment_stages(std::string &aSource)
{
#if defined JFC_TARGET_PLATFORM_Emscripten
// sets float precision, required by webgl
aSource.insert(0, std::string("precision mediump float;\n"));
#endif
}
webgl1es2_shader_program::webgl1es2_shader_program(std::string aVertexSource, std::string aFragmentSource)
: m_VertexShaderHandle([&aVertexSource]()
{
perform_shader_code_preprocessing_done_to_both_vertex_and_fragment_stages(aVertexSource);
// Compile vertex stage
const GLuint vs = glCreateShader(GL_VERTEX_SHADER);
const char *const vertex_shader = aVertexSource.c_str();
glShaderSource(vs, 1, &vertex_shader, 0);
glCompileShader(vs);
return decltype(m_VertexShaderHandle)(vs, [](const GLuint handle)
{
glDeleteShader(handle);
});
}())
, m_FragmentShaderHandle([&aFragmentSource]()
{
perform_shader_code_preprocessing_done_to_only_fragment_stages(aFragmentSource);
perform_shader_code_preprocessing_done_to_both_vertex_and_fragment_stages(aFragmentSource);
// Compile fragment stage
const char *const fragment_shader = aFragmentSource.c_str();
const GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &fragment_shader, 0);
glCompileShader(fs);
return decltype(m_FragmentShaderHandle)(fs, [](const GLuint handle)
{
glDeleteShader(handle);
});
}())
, m_ProgramHandle([this]()
{
const auto vs = m_VertexShaderHandle.get();
const auto fs = m_FragmentShaderHandle.get();
// Link the program
GLuint programHandle = glCreateProgram();
glAttachShader(programHandle, vs);
glAttachShader(programHandle, fs);
glLinkProgram(programHandle);
// Confirm no compilation/link errors
GLint status(-1);
glGetProgramiv(programHandle, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
std::ostringstream message;
message << "A shader could not be linked!\n";
static const auto decorator = [](std::ostringstream& ss, std::string log_header,
std::string &&log_msg)
{
ss << log_header << "\n" << (log_msg.size() ? log_msg : "clear") << "\n\n";
};
decorator(message, "vertex log", glh::GetShaderInfoLog(vs));
decorator(message, "fragment log", glh::GetShaderInfoLog(fs));
decorator(message, "program log", glh::GetProgramInfoLog(programHandle));
throw std::runtime_error(std::string(TAG).append(": ").append(message.str()));
}
return jfc::unique_handle<GLuint>(programHandle,
[](const GLuint handle)
{
glDeleteProgram(handle);
});
}())
{
const auto programHandle = m_ProgramHandle.get();
GLint count;
GLsizei currentNameLength;
// poll active attributes, record their names and locations for attribute enabling & creating vertex attrib pointers
{
// (c string bookkeeping) create a buffer big enough to contain the longest active attrib's name
GLint maxAttribNameLength(0);
glGetProgramiv(programHandle, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxAttribNameLength);
std::vector<GLchar> attrib_name_buffer(maxAttribNameLength);
glGetProgramiv(programHandle, GL_ACTIVE_ATTRIBUTES, &count);
for (decltype(count) i(0); i < count; ++i)
{
GLint component_count;
GLenum component_type;
glGetActiveAttrib(programHandle,
i,
attrib_name_buffer.size(), // (c string bookkeeping) max size the gl can safely write into my buffer
¤tNameLength, // (c string bookkeeping) actual char count for the current attribute's name
&component_count, // e.g: 3 //TODO: RENAME! This isnt what I tohught it was.
// Size is the number of gltypes.. so vec2 would == 1 as in 1 vec 2, not 2 floats,
// being the components... need to rename all this stuff...
&component_type, // e.g: float
&attrib_name_buffer.front()); // e.g: "a_Position"
webgl1es2_shader_program::active_attribute_info info;
info.location = i;
info.type = component_type;
info.count = component_count;
m_ActiveAttributes[std::string(attrib_name_buffer.begin(),
attrib_name_buffer.begin() + currentNameLength)] = std::move(info);
}
}
// poll active uniforms, record their names and locations for uniform value assignments
{
// (c string bookkeeping) create a buffer likely big enough to contain the longest active attrib's name
// There is a GL_ACTIVE_UNIFORM_MAX_LENGTH (equivalent of above attrib code), but I have found recent posts online
// (2010s) of programmers complaining that it is fairly common for drivers to return incorrect values,
// so I am allocating a large buffer instead.
std::vector<GLchar> uniform_name_buffer(256);
glGetProgramiv(programHandle, GL_ACTIVE_UNIFORMS, &count);
for (decltype(count) i(0); i < count; ++i)
{
GLint attribute_size;
GLenum attribute_type;
glGetActiveUniform(programHandle,
i,
uniform_name_buffer.size(), // (c string bookkeeping) max size the gl can safely write into my buffer
¤tNameLength, // (c string bookkeeping) actual char count for the current attribute's name
&attribute_size, // e.g: "1"
&attribute_type, // e.g: "texture"
&uniform_name_buffer.front()); // e.g: "u_Diffuse"
webgl1es2_shader_program::active_uniform_info info;
info.location = i;
info.type = attribute_type;
info.size = attribute_size;
m_ActiveUniforms[std::string(uniform_name_buffer.begin(), uniform_name_buffer.begin() + currentNameLength)]
= std::move(info);
}
}
}
void webgl1es2_shader_program::useProgram() const
{
static GLint s_CurrentShaderProgramHandle(-1);
if (const auto handle(m_ProgramHandle.get());
s_CurrentShaderProgramHandle != handle)
{
s_CurrentShaderProgramHandle = handle;
s_ActiveTextureUniformNameToUnit.clear();
s_ActiveTextureUnitCounter = 0;
glUseProgram(handle);
}
}
bool webgl1es2_shader_program::operator==(const webgl1es2_shader_program &b) const
{
return m_ProgramHandle == b.m_ProgramHandle;
}
bool webgl1es2_shader_program::operator!=(const webgl1es2_shader_program &b) const {return !(*this == b);}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const GLfloat aValue) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform1f(search->second.location, aValue);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const graphics_vector2_type &aValue) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform2f(search->second.location, aValue.x, aValue.y);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const graphics_vector3_type &aValue) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform3f(search->second.location, aValue.x, aValue.y, aValue.z);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const graphics_vector4_type &aValue) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform4f(search->second.location, aValue.x, aValue.y, aValue.z, aValue.w);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<GLfloat> &avalue) const
{
if (!avalue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform1fv(search->second.location, avalue.size(), &avalue[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<graphics_vector2_type> &avalue) const
{
if (!avalue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
std::vector<graphics_vector2_type::component_type> data;
data.reserve(avalue.size() * 2);
for (const auto &vec : avalue)
{
data.push_back(vec.x);
data.push_back(vec.y);
}
glUniform2fv(search->second.location, avalue.size(), &data[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<graphics_vector3_type> &avalue) const
{
if (!avalue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
std::vector<graphics_vector3_type::component_type> data;
data.reserve(avalue.size() * 3);
for (const auto &vec : avalue)
{
data.push_back(vec.x);
data.push_back(vec.y);
data.push_back(vec.z);
}
glUniform3fv(search->second.location, avalue.size(), &data[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<graphics_vector4_type> &avalue) const
{
if (!avalue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
std::vector<graphics_vector4_type::component_type> data;
data.reserve(avalue.size() * 4);
for (const auto &vec : avalue)
{
data.push_back(vec.x);
data.push_back(vec.y);
data.push_back(vec.z);
data.push_back(vec.w);
}
glUniform4fv(search->second.location, avalue.size(), &data[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const GLint aValue) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform1i(search->second.location, aValue);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string aName, const integer2_uniform_type &a) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform2i(search->second.location, a[0], a[1]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string aName, const integer3_uniform_type &a) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform3i(search->second.location, a[0], a[1], a[2]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string aName, const integer4_uniform_type &a) const
{
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform4i(search->second.location, a[0], a[1], a[2], a[3]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<GLint> &aValue) const
{
if (!aValue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniform1iv(search->second.location, aValue.size(), &aValue[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<integer2_uniform_type> &aValue) const
{
if (!aValue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
std::vector<integer2_uniform_type::value_type> data;
data.reserve(aValue.size() * 2);
for (const auto &vec : aValue)
{
data.push_back(vec[0]);
data.push_back(vec[1]);
}
glUniform2iv(search->second.location, aValue.size(), &data[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<integer3_uniform_type> &aValue) const
{
if (!aValue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
std::vector<integer3_uniform_type::value_type> data;
data.reserve(aValue.size() * 3);
for (const auto &vec : aValue)
{
data.push_back(vec[0]);
data.push_back(vec[1]);
data.push_back(vec[2]);
}
glUniform3iv(search->second.location, aValue.size(), &data[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<integer4_uniform_type> &aValue) const
{
if (!aValue.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
std::vector<integer4_uniform_type::value_type> data;
data.reserve(aValue.size() * 4);
for (const auto &vec : aValue)
{
data.push_back(vec[0]);
data.push_back(vec[1]);
data.push_back(vec[2]);
data.push_back(vec[3]);
}
glUniform3iv(search->second.location, aValue.size(), &data[0]);
return true;
}
return false;
}
/*bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const graphics_mat2x2_type &avalue) const
{
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<graphics_mat2x2_type> &avalue) const
{
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const graphics_mat3x3_type &avalue) const
{
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<graphics_mat3x3_type> &avalue) const
{
}*/
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const graphics_mat4x4_type &a) const
{
if (const auto& search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
glUniformMatrix4fv(search->second.location, 1, GL_FALSE, &a.m[0][0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const std::vector<graphics_mat4x4_type> &a) const
{
if (!a.size()) return false;
if (const auto &search = m_ActiveUniforms.find(aName); search != m_ActiveUniforms.end())
{
static constexpr auto magnitude(graphics_mat4x4_type::RowOrColumnCount);
std::vector<graphics_mat4x4_type::component_type> data;
data.reserve(a.size() * magnitude * magnitude);
for (const auto &mat : a)
{
for (int y(0); y < magnitude; ++y) for (int x(0); x < magnitude; ++x)
{
data.push_back(mat.m[y][x]);
}
}
glUniformMatrix4fv(search->second.location, 1, GL_FALSE, &data[0]);
return true;
}
return false;
}
bool webgl1es2_shader_program::try_set_uniform(const std::string &aName, const gdk::webgl1es2_texture &aTexture) const
{
if (const auto &activeUniformSearch = m_ActiveUniforms.find(aName); activeUniformSearch != m_ActiveUniforms.end())
{
const auto &activeTextureSearch = s_ActiveTextureUniformNameToUnit.find(aName);
const GLint unit = activeTextureSearch == s_ActiveTextureUniformNameToUnit.end()
? [&aName]() {
decltype(unit) next_unit = s_ActiveTextureUnitCounter++;
s_ActiveTextureUniformNameToUnit[aName] = next_unit;
return next_unit;
}()
: activeTextureSearch->second;
if (s_ActiveTextureUnitCounter < webgl1es2_shader_program::MAX_TEXTURE_UNITS)
{
//TODO: parameterize! Improve texture as well to support non2ds.
// The type (2d or cube) should be a property of the texture abstraction.
const GLenum target(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(target, aTexture.getHandle());
glUniform1i(activeUniformSearch->second.location, unit);
}
else throw std::invalid_argument(std::string("GLES2.0/WebGL1.0 only provide 8 texture units; "
"you are trying to bind too many simultaneous textures to the context: ") +
std::to_string(s_ActiveTextureUnitCounter));
return true;
}
return false;
}
std::optional<webgl1es2_shader_program::active_attribute_info> webgl1es2_shader_program::tryGetActiveAttribute(const std::string &aAttributeName) const
{
if (auto found = m_ActiveAttributes.find(aAttributeName); found != m_ActiveAttributes.end())
return found->second;
return {};
}
| 30.528804
| 151
| 0.653184
|
jfcameron
|
c732658bd36524425c901e678fe7257825e8df94
| 14,860
|
cpp
|
C++
|
source/scene/logic/scene.cpp
|
imstar15/breeze
|
8793493c1245670a66e1a098a0d010c51e7b4783
|
[
"Apache-2.0"
] | 454
|
2015-01-06T00:28:13.000Z
|
2022-03-17T04:24:39.000Z
|
source/scene/logic/scene.cpp
|
63890390/breeze
|
e9ce9fae7a3f9dc5f3f1c911a98d75707a50e6b0
|
[
"Apache-2.0"
] | 8
|
2016-06-08T21:06:03.000Z
|
2021-06-10T11:20:06.000Z
|
source/scene/logic/scene.cpp
|
63890390/breeze
|
e9ce9fae7a3f9dc5f3f1c911a98d75707a50e6b0
|
[
"Apache-2.0"
] | 214
|
2015-01-06T11:06:46.000Z
|
2022-03-13T14:29:52.000Z
|
#include "scene.h"
#include "sceneMgr.h"
#include <aoe/aoe.h>
Scene::Scene(SceneID sceneID)
{
_sceneID = sceneID;
_sceneType = SCENE_NONE;
_sceneStatus = SCENE_STATE_NONE;
}
Scene::~Scene()
{
}
GroupID Scene::getGroupID(ServiceID avatarID)
{
auto entity = getEntityByAvatarID(avatarID);
if (entity)
{
return entity->_state.groupID;
}
return InvalidGroupID;
}
void Scene::getSceneSection(SceneSection & ss)
{
ss.sceneID = _sceneID;
ss.sceneType = _sceneType;
ss.sceneState = _sceneStatus;
ss.sceneStartTime = _startTime;
ss.sceneEndTime = _endTime;
ss.serverTime = getFloatSteadyNowTime();
}
bool Scene::cleanScene()
{
//放入free列表要先clean, 减小内存占用
_sceneType = SCENE_NONE;
_sceneStatus = SCENE_STATE_NONE;
_lastEID = ServerConfig::getRef().getSceneConfig()._lineID * 1000 + 1000;
_entitys.clear();
_players.clear();
while (!_asyncs.empty()) _asyncs.pop();
_move.reset();
_skill.reset();
_ai.reset();
_script.reset();
return true;
}
bool Scene::initScene(SCENE_TYPE sceneType, MapID mapID)
{
if (_sceneStatus != SCENE_STATE_NONE)
{
LOGE("Scene::loadScene scene status error");
return false;
}
double now = getFloatNowTime();
_sceneType = sceneType;
_mapID = mapID;
_sceneStatus = SCENE_STATE_ACTIVE;
_lastEID = ServerConfig::getRef().getSceneConfig()._lineID * 1000 + 1000;
_startTime = getFloatSteadyNowTime();
_endTime = getFloatSteadyNowTime() + 600;
_move = std::make_shared<MoveSync>();
_move->init(shared_from_this());
_skill = std::make_shared<Skill>();
_skill->init(shared_from_this());
_ai = std::make_shared<AI>();
_ai->init(shared_from_this());
_script = std::make_shared<Script>();
_script->init(shared_from_this());
//load map
//load entitys
onSceneInit();
LOGD("initScene success. used time=" << getFloatNowTime() - now);
return true;
}
EntityPtr Scene::getEntity(EntityID eID)
{
auto founder = _entitys.find(eID);
if (founder == _entitys.end())
{
return nullptr;
}
return founder->second;
}
EntityPtr Scene::getEntityByAvatarID(ServiceID avatarID)
{
auto founder = _players.find(avatarID);
if (founder == _players.end())
{
return nullptr;
}
return founder->second;
}
EntityPtr Scene::makeEntity(ui64 modelID, ui64 avatarID, std::string avatarName, DictArrayKey equips,GroupID groupID)
{
EntityPtr entity = std::make_shared<Entity>();
entity->_props = DictProp();
entity->_state.curHP = entity->_props.hp;
entity->_state.eid = ++_lastEID;
entity->_state.avatarID = avatarID;
entity->_state.avatarName = avatarName;
entity->_state.modelID = modelID;
entity->_state.groupID = groupID;
entity->_state.camp = ENTITY_CAMP_NONE;
entity->_state.etype = avatarID == InvalidAvatarID ? ENTITY_AI : ENTITY_PLAYER;
entity->_state.state = ENTITY_STATE_ACTIVE;
entity->_state.master = InvalidEntityID;
entity->_state.foe = InvalidEntityID;
entity->_control.spawnpoint = { 0.0 - 30 + realRandF()*30 ,60 -30 + realRandF()*30 };
entity->_control.eid = entity->_state.eid;
entity->_control.agentNo = RVO::RVO_ERROR;
entity->_control.stateChageTime = getFloatSteadyNowTime();
entity->_move.eid = entity->_state.eid;
entity->_move.position = entity->_control.spawnpoint;
entity->_move.follow = InvalidEntityID;
entity->_move.waypoints.clear();
entity->_move.action = MOVE_ACTION_IDLE;
entity->_report.eid = entity->_state.eid;
entity->_skillSys.eid = entity->_state.eid;
return entity;
}
void Scene::addEntity(EntityPtr entity)
{
entity->_control.agentNo = _move->addAgent(entity->_move.position, entity->_control.collision);
_entitys.insert(std::make_pair(entity->_state.eid, entity));
if (entity->_state.avatarID != InvalidServiceID && entity->_state.etype == ENTITY_PLAYER)
{
_players[entity->_state.avatarID] = entity;
}
LOGD("Scene::addEntity. eid[" << entity->_state.eid << "] aid[" << entity->_state.avatarID << "][" << entity->_state.avatarName
<< "] modleID=" << entity->_state.modelID << ", camp=" << entity->_state.camp << ", etype=" << entity->_state.etype << ", state=" << entity->_state.state
<< ", agentNo=" << entity->_control.agentNo << ", hp=[" << entity->_state.curHP << "/" << entity->_state.maxHP
<< "], spawnpoint" << entity->_control.spawnpoint<< ", position=" << entity->_move.position);
AddEntityNotice notice;
notice.syncs.push_back(entity->getClientSyncData());
broadcast(notice, entity->_state.avatarID);
EntityScriptNotice sn;
sn.controls.push_back(entity->_control);
sn.skills.push_back(entity->_skillSys);
broadcast(notice, entity->_state.avatarID);
onAddEntity(entity);
}
bool Scene::removePlayer(AvatarID avatarID)
{
auto entity = getEntityByAvatarID(avatarID);
if (entity)
{
return removeEntity(entity->_state.eid);
}
return false;
}
bool Scene::removePlayerByGroupID(GroupID groupID)
{
std::set<EntityID> removes;
for (auto entity : _entitys)
{
if (entity.second->_state.etype == ENTITY_PLAYER && entity.second->_state.groupID == groupID)
{
removes.insert(entity.second->_state.eid);
}
}
for (auto eid : removes)
{
removeEntity(eid);
}
return true;
}
bool Scene::removeEntity(EntityID eid)
{
auto entity = getEntity(eid);
if (!entity)
{
LOGE("");
return false;
}
if(_move->isValidAgent(entity->_control.agentNo))
{
_move->delAgent(entity->_control.agentNo);
entity->_control.agentNo = RVO::RVO_ERROR;
}
if (entity->_state.etype == ENTITY_PLAYER)
{
_players.erase(entity->_state.avatarID);
SceneMgr::getRef().sendToWorld(SceneServerGroupStateFeedback(getSceneID(), entity->_state.groupID, SCENE_NONE));
}
_entitys.erase(eid);
RemoveEntityNotice notice;
notice.eids.push_back(eid);
broadcast(notice);
onRemoveEntity(entity);
return true;
}
bool Scene::playerAttach(ServiceID avatarID, SessionID sID)
{
EntityPtr entity = getEntityByAvatarID(avatarID);
if (!entity)
{
return false;
}
entity->_clientSessionID = sID;
LOGI("Scene::playerAttach avatarName=" << entity->_state.avatarName << " sessionID=" << sID << ", entityID=" << entity->_state.eid);
SceneSectionNotice section;
getSceneSection(section.section);
sendToClient(avatarID, section);
AddEntityNotice notice;
for (auto & e : _entitys)
{
notice.syncs.push_back(e.second->getClientSyncData());
}
if (!notice.syncs.empty())
{
sendToClient(avatarID, notice);
}
onPlayerAttach(entity);
return true;
}
bool Scene::playerDettach(ServiceID avatarID, SessionID sID)
{
auto entity = getEntityByAvatarID(avatarID);
if (entity && entity->_clientSessionID == sID)
{
LOGI("Scene::playerDettach avatarName=" << entity->_state.avatarName << " sessionID=" << sID << ", entityID=" << entity->_state.eid);
entity->_clientSessionID = InvalidSessionID;
onPlayerDettach(entity);
}
return true;
}
bool Scene::onUpdate()
{
if (getFloatSteadyNowTime() > _endTime || _players.empty())
{
return false;
}
_move->update();
_skill->update();
_ai->update();
SceneRefreshNotice notice;
EntityScriptNotice scripts;
for (auto &kv : _entitys)
{
if (kv.second->_isStateDirty)
{
notice.entityStates.push_back(kv.second->_state);
kv.second->_isStateDirty = false;
}
if (kv.second->_isMoveDirty)
{
notice.entityMoves.push_back(kv.second->_move);
kv.second->_isMoveDirty = false;
}
scripts.controls.push_back(kv.second->_control);
scripts.skills.push_back(kv.second->_skillSys);
}
if (!notice.entityStates.empty() || !notice.entityMoves.empty())
{
broadcast(notice);
}
_script->protoSync(scripts);
//after flush data
_script->update();
while (!_asyncs.empty())
{
auto func = _asyncs.front();
_asyncs.pop();
func();
}
return true;
}
void Scene::pushAsync(std::function<void()> && func)
{
_asyncs.push(std::move(func));
}
void Scene::onPlayerInstruction(ServiceID avatarID, ReadStream & rs)
{
if (avatarID == InvalidAvatarID)
{
return;
}
if (rs.getProtoID() == MoveReq::getProtoID())
{
MoveReq req;
rs >> req;
LOGD("MoveReq avatarID[" << avatarID << "] req=" << req);
auto entity = getEntity(req.eid);
if (!entity || entity->_state.avatarID != avatarID || entity->_state.etype != ENTITY_PLAYER
|| (req.action != MOVE_ACTION_IDLE && req.action == MOVE_ACTION_FOLLOW && req.action == MOVE_ACTION_PATH)
|| entity->_state.state != ENTITY_STATE_ACTIVE
)
{
sendToClient(avatarID, MoveResp(EC_ERROR, req.eid, req.action));
return;
}
if (!_move->doMove(req.eid, (MOVE_ACTION)req.action, entity->getSpeed(), req.follow, req.waypoints))
{
sendToClient(avatarID, MoveResp(EC_ERROR, req.eid, req.action));
return;
}
if (entity->_skillSys.combating)
{
entity->_skillSys.combating = false;
}
}
else if (rs.getProtoID() == UseSkillReq::getProtoID())
{
UseSkillReq req;
rs >> req;
auto entity = getEntity(req.eid);
if (!entity || entity->_state.avatarID != avatarID || entity->_state.etype != ENTITY_PLAYER || entity->_state.state != ENTITY_STATE_ACTIVE
|| ! _skill->doSkill(shared_from_this(), req.eid, req.skillID, req.dst)
)
{
sendToClient(avatarID, UseSkillResp(EC_ERROR, req.eid, req.skillID, req.dst, req.foeFirst));
}
}
else if (rs.getProtoID() == ClientCustomReq::getProtoID())
{
ClientCustomReq req;
rs >> req;
auto entity = getEntity(req.eid);
if (entity && entity->_state.avatarID == avatarID)
{
broadcast(ClientCustomNotice(req.eid, req.customID, req.fValue,req.uValue, req.sValue));
}
else
{
sendToClient(avatarID, ClientCustomResp(EC_ERROR, req.eid, req.customID));
}
}
else if (rs.getProtoID() == ClientPingTestReq::getProtoID())
{
ClientPingTestReq req;
rs >> req;
sendToClient(avatarID, ClientPingTestResp(EC_ERROR, req.seqID, req.clientTime));
}
}
std::vector<std::pair<EntityPtr, double>> Scene::searchTarget(EntityPtr caster, EPosition org, EPosition vt, ui64 searchID)
{
auto search = DBDict::getRef().getOneKeyAOESearch(searchID);
if (!search.first)
{
LOGE("Scene::searchTarget not found search config. searchID=" << searchID);
return std::vector<std::pair<EntityPtr, double>>();
}
return searchTarget(caster, org, vt, search.second);
}
bool Scene::searchMatched(const EntityPtr & master, const EntityPtr & caster, const EntityPtr & dst, const AOESearch & search)
{
if (getBitFlag(search.filter, FILTER_SELF) && master && master->_state.eid == dst->_state.eid)
{
return true;
}
if (search.etype != ENTITY_NONE && search.etype != dst->_state.etype)
{
return false;
}
if (getBitFlag(search.filter, FILTER_OTHER_FRIEND) && caster->_state.camp == dst->_state.camp)
{
if (master && master->_state.eid == dst->_state.eid)
{
return false;
}
return true;
}
if (getBitFlag(search.filter, FILTER_ENEMY_CAMP) && caster->_state.camp != dst->_state.camp && dst->_state.camp < ENTITY_CAMP_NEUTRAL)
{
return true;
}
if (getBitFlag(search.filter, FILTER_NEUTRAL_CAMP) && dst->_state.camp >= ENTITY_CAMP_NEUTRAL)
{
return true;
}
return false;
}
std::vector<std::pair<EntityPtr, double>> Scene::searchTarget(EntityPtr caster, EPosition org, EPosition vt, const AOESearch & search)
{
EntityPtr master = caster;
if (caster->_state.etype == ENTITY_FLIGHT)
{
if (caster->_state.master != InvalidEntityID)
{
master = getEntity(caster->_state.master);
}
else
{
master = nullptr;
}
}
auto ret = searchTarget(org, vt, search.isRect,
search.value1, search.value2, search.value3, search.compensate, search.clip);
if (getBitFlag(search.filter, FILTER_SELF) && master)
{
if (std::find_if(ret.begin(), ret.end(), [&master](const std::pair<EntityPtr, double> & pr) {return pr.first->_state.eid == master->_state.eid; })
== ret.end())
{
ret.push_back(std::make_pair(master, 0));
}
}
auto beginIter = std::remove_if(ret.begin(), ret.end(), [this, &search, &master, &caster](const std::pair<EntityPtr, double> & e)
{
if (searchMatched(master, caster, e.first, search))
{
return false;
}
return true;
});
ret.erase(beginIter, ret.end());
if (ret.size()> search.limitEntitys)
{
ret.resize(search.limitEntitys);
}
return ret;
}
std::vector<std::pair<EntityPtr, double>> Scene::searchTarget(EPosition org, EPosition vt, ui16 isRect, double value1, double value2, double value3, double compensate, double clip)
{
std::vector<std::pair<EntityPtr, double>> ret;
vt = normalize(vt);
org = org + vt*compensate;
value1 = value1 - compensate;
AOECheck ac;
ac.init(toTuple(org), toTuple(vt), isRect != 0, value1, value2, value3, clip);
for (auto kv : _entitys)
{
EPosition pos = kv.second->_move.position;
if (kv.second->_state.etype != ENTITY_PLAYER && kv.second->_state.etype != ENTITY_AI)
{
continue;
}
if (kv.second->_state.state != ENTITY_STATE_ACTIVE)
{
continue;
}
auto cRet = ac.check(toTuple(pos), kv.second->_control.collision);
if (std::get<0>(cRet))
{
ret.push_back(std::make_pair(kv.second, std::get<1>(cRet)));
}
}
std::sort(ret.begin(), ret.end(), [org](const std::pair<EntityPtr, double> & e1, const std::pair<EntityPtr, double> & e2){return e1.second < e2.second; });
return ret;
}
void Scene::onSceneInit()
{
}
void Scene::onAddEntity(EntityPtr entity)
{
}
void Scene::onRemoveEntity(EntityPtr entity)
{
}
void Scene::onPlayerAttach(EntityPtr entity)
{
}
void Scene::onPlayerDettach(EntityPtr entity)
{
}
| 27.166362
| 181
| 0.622813
|
imstar15
|
c733235662dafc098745f0014db4524b3674cb8f
| 394
|
cpp
|
C++
|
Engine/src/Layer_Console.cpp
|
int-Frank/BSR
|
16310147281c76ca37836b07aff2974234e09a47
|
[
"Apache-2.0"
] | 1
|
2020-01-04T20:17:42.000Z
|
2020-01-04T20:17:42.000Z
|
Engine/src/Layer_Console.cpp
|
int-Frank/BSR
|
16310147281c76ca37836b07aff2974234e09a47
|
[
"Apache-2.0"
] | null | null | null |
Engine/src/Layer_Console.cpp
|
int-Frank/BSR
|
16310147281c76ca37836b07aff2974234e09a47
|
[
"Apache-2.0"
] | null | null | null |
//@group Layers
#include "Layer_Console.h"
#include "core_Log.h"
#define LOG_MESSAGE(...) LOG_TRACE(__VA_ARGS__)
namespace Engine
{
Layer_Console::Layer_Console()
{
}
Layer_Console::~Layer_Console()
{
}
void Layer_Console::Update(float a_dt)
{
}
void Layer_Console::HandleMessage(Message * a_pMsg)
{
if (a_pMsg->GetCategory() != MC_Input)
return;
}
}
| 12.709677
| 53
| 0.659898
|
int-Frank
|
c738b91713fb49991d53ba916a740c2084e6d15c
| 4,044
|
hxx
|
C++
|
src/elle/reactor/Generator.hxx
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 521
|
2016-02-14T00:39:01.000Z
|
2022-03-01T22:39:25.000Z
|
src/elle/reactor/Generator.hxx
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 8
|
2017-02-21T11:47:33.000Z
|
2018-11-01T09:37:14.000Z
|
src/elle/reactor/Generator.hxx
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 48
|
2017-02-21T10:18:13.000Z
|
2022-03-25T02:35:20.000Z
|
#include <type_traits>
namespace elle
{
namespace reactor
{
/*----.
| End |
`----*/
template <typename T>
Generator<T>::End::End(Generator<T> const& g)
: elle::Error(elle::sprintf("%s exhausted", g))
{}
/*-------------.
| Construction |
`-------------*/
template <typename T>
template <typename Driver>
Generator<T>::Generator(Driver driver)
{
using Signature = std::function<auto (yielder const&) -> void>;
static_assert(std::is_constructible<Signature, Driver>::value, "");
ELLE_LOG_COMPONENT("elle.reactor.Generator");
auto yield = [this] (T elt) { this->_results.put(std::move(elt)); };
this->_thread.reset(
new Thread("generator",
[this, driver, yield]
{
try
{
driver(yield);
}
catch (...)
{
ELLE_TRACE("%s: handle exception: %s",
this, elle::exception_string());
this->_exception = std::current_exception();
}
this->_results.put({});
}));
}
template <typename T>
Generator<T>::Generator(Generator<T>&& generator)
: _results(std::move(generator._results))
, _thread(std::move(generator._thread))
{}
template <typename T>
Generator<T>::~Generator()
{
ELLE_LOG_COMPONENT("elle.reactor.Generator");
ELLE_TRACE("%s: destruct", this);
}
/*--------.
| Content |
`--------*/
template <typename T>
T
Generator<T>::iterator::operator *() const
{
assert(!this->_fetch);
return std::move(this->_value.get());
}
/*---------.
| Iterator |
`---------*/
template <typename T>
Generator<T>::iterator::iterator()
: _generator(nullptr)
, _fetch(true)
{}
template <typename T>
Generator<T>::iterator::iterator(Generator<T>& generator)
: _generator(&generator)
, _fetch(true)
{}
template <typename T>
bool
Generator<T>::iterator::operator !=(iterator const& other) const
{
assert(other._generator == nullptr);
if (this->_fetch)
{
this->_value = this->_generator->_results.get();
this->_fetch = false;
}
if (this->_value)
return true;
else if (this->_generator->_exception)
std::rethrow_exception(this->_generator->_exception);
else
return false;
}
template <typename T>
bool
Generator<T>::iterator::operator ==(iterator const& other) const
{
return !(*this != other);
}
template <typename T>
typename Generator<T>::iterator&
Generator<T>::iterator::operator ++()
{
this->_fetch = true;
this->_value.reset();
return *this;
}
template <typename T>
void
Generator<T>::iterator::operator ++(int)
{
++*this;
}
template <typename T>
T
Generator<T>::next()
{
if (auto res = this->_results.get())
return *res;
else
throw End(*this);
}
template <typename T>
Generator<T>
generator(std::function<void (yielder<T> const&)> const& driver)
{
return Generator<T>(driver);
}
template <typename T>
typename Generator<T>::iterator
Generator<T>::begin()
{
return typename Generator<T>::iterator(*this);
}
template <typename T>
typename Generator<T>::iterator
Generator<T>::end()
{
return typename Generator<T>::iterator();
}
template <typename T>
typename Generator<T>::const_iterator
Generator<T>::begin() const
{
return typename Generator<T>::iterator(elle::unconst(*this));
}
template <typename T>
typename Generator<T>::const_iterator
Generator<T>::end() const
{
return typename Generator<T>::iterator();
}
}
}
| 22.977273
| 74
| 0.526954
|
infinitio
|
c73cb9c65a54973505931ffed10a564f468f2d31
| 13,219
|
cpp
|
C++
|
main/IotDataMqtt.cpp
|
nkskjames/wifi_bbq_temp
|
28e9d46d64de0a83e5e0a04a6112c1f564421af6
|
[
"Apache-2.0"
] | null | null | null |
main/IotDataMqtt.cpp
|
nkskjames/wifi_bbq_temp
|
28e9d46d64de0a83e5e0a04a6112c1f564421af6
|
[
"Apache-2.0"
] | null | null | null |
main/IotDataMqtt.cpp
|
nkskjames/wifi_bbq_temp
|
28e9d46d64de0a83e5e0a04a6112c1f564421af6
|
[
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include <nvs.h>
#include <nvs_flash.h>
#include "aws_iot_config.h"
#include "aws_iot_log.h"
#include "aws_iot_version.h"
#include "aws_iot_mqtt_client_interface.h"
#include "aws_iot_shadow_interface.h"
#include "IotData.hpp"
#include "IotDataMqtt.hpp"
using namespace std;
extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start");
extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end");
extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start");
extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end");
extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start");
extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end");
extern const uint8_t certificate_and_ca_pem_crt_start[] asm("_binary_certificate_and_ca_pem_crt_start");
extern const uint8_t certificate_and_ca_pem_crt_end[] asm("_binary_certificate_and_ca_pem_crt_end");
#define MQTT_NAMESPACE "mqtt" // Namespace in NVS
#define KEY_REGISTER "registered"
#define KEY_S_VERSION "version"
#define tag "mqtt"
uint32_t s_version = 0x0100;
/**
* Save signup status
*/
static void saveRegisterStatus(bool registered) {
nvs_handle handle;
ESP_ERROR_CHECK(nvs_open(MQTT_NAMESPACE, NVS_READWRITE, &handle));
ESP_ERROR_CHECK(nvs_set_u8(handle, KEY_REGISTER, registered));
ESP_ERROR_CHECK(nvs_set_u32(handle, KEY_S_VERSION, s_version));
ESP_ERROR_CHECK(nvs_commit(handle));
ESP_LOGI(tag, "Registration saved");
nvs_close(handle);
}
bool isRegistered() {
nvs_handle handle;
uint8_t registered = false;
esp_err_t err;
uint32_t version;
err = nvs_open(MQTT_NAMESPACE, NVS_READWRITE, &handle);
if (err != 0) {
ESP_LOGE(tag, "nvs_open: %x", err);
return false;
}
// Get the version that the data was saved against.
err = nvs_get_u32(handle, KEY_S_VERSION, &version);
if (err != ESP_OK) {
ESP_LOGD(tag, "No version record found (%d).", err);
nvs_close(handle);
return false;
}
// Check the versions match
if ((version & 0xff00) != (s_version & 0xff00)) {
ESP_LOGD(tag, "Incompatible versions ... current is %x, found is %x", version, s_version);
nvs_close(handle);
return false;
}
err = nvs_get_u8(handle, KEY_REGISTER, ®istered);
if (err != ESP_OK) {
ESP_LOGD(tag, "No signup record found (%d).", err);
nvs_close(handle);
return false;
}
if (err != ESP_OK) {
ESP_LOGE(tag, "nvs_open: %x", err);
nvs_close(handle);
return -false;
}
// Cleanup
nvs_close(handle);
ESP_LOGI(tag, "Found registration");
return registered;
}
static void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) {
static const char* TAG = "shadow_disconnect";
ESP_LOGW(TAG, "MQTT Disconnect");
IoT_Error_t rc = FAILURE;
if(NULL == pClient) {
return;
}
if(aws_iot_is_autoreconnect_enabled(pClient)) {
ESP_LOGI(TAG, "Auto Reconnect is enabled, Reconnecting attempt will start now");
} else {
ESP_LOGW(TAG, "Auto Reconnect not enabled. Starting manual reconnect...");
rc = aws_iot_mqtt_attempt_reconnect(pClient);
if(NETWORK_RECONNECTED == rc) {
ESP_LOGW(TAG, "Manual Reconnect Successful");
} else {
ESP_LOGW(TAG, "Manual Reconnect Failed - %d", rc);
}
}
}
static bool shadowUpdateInProgress;
static void ShadowUpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status,
const char *pReceivedJsonDocument, void *pContextData) {
IOT_UNUSED(pThingName);
IOT_UNUSED(action);
IOT_UNUSED(pReceivedJsonDocument);
IOT_UNUSED(pContextData);
shadowUpdateInProgress = false;
static const char* TAG = "shadow_callback";
if(SHADOW_ACK_TIMEOUT == status) {
ESP_LOGE(TAG, "Update timed out");
} else if(SHADOW_ACK_REJECTED == status) {
ESP_LOGE(TAG, "Update rejected");
} else if(SHADOW_ACK_ACCEPTED == status) {
ESP_LOGI(TAG, "Update accepted");
}
}
int IotDataMqtt::signup(char* thingId,char* username) {
if (isRegistered()) { return 0; }
char cPayload[100];
//int32_t i = 0;
IoT_Error_t rc = FAILURE;
AWS_IoT_Client client;
IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;
IoT_Publish_Message_Params paramsQOS0;
ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
mqttInitParams.enableAutoReconnect = false; // We enable this later below
mqttInitParams.pHostURL = (char*)IotDataMqtt::HOST;
mqttInitParams.port = IotDataMqtt::PORT;
mqttInitParams.pDeviceCertLocation = (const char *)certificate_and_ca_pem_crt_start;
//mqttInitParams.pDeviceCertLocation = (const char *)certificate_pem_crt_start;
mqttInitParams.pDevicePrivateKeyLocation = (const char *)private_pem_key_start;
mqttInitParams.pRootCALocation = (const char *)aws_root_ca_pem_start;
mqttInitParams.mqttCommandTimeout_ms = 20000;
mqttInitParams.tlsHandshakeTimeout_ms = 5000;
mqttInitParams.isSSLHostnameVerify = true;
mqttInitParams.disconnectHandler = disconnectCallbackHandler;
mqttInitParams.disconnectHandlerData = NULL;
rc = aws_iot_mqtt_init(&client, &mqttInitParams);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "aws_iot_mqtt_init returned error : %d ", rc);
abort();
}
connectParams.keepAliveIntervalInSec = 10;
connectParams.isCleanSession = true;
connectParams.MQTTVersion = MQTT_3_1_1;
connectParams.pClientID = thingId;
connectParams.clientIDLen = (uint16_t) strlen(thingId);
connectParams.isWillMsgPresent = false;
ESP_LOGI(TAG, "Connecting to AWS...");
do {
rc = aws_iot_mqtt_connect(&client, &connectParams);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port);
vTaskDelay(1000 / portTICK_RATE_MS);
}
} while(SUCCESS != rc);
/*
* Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
* #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
* #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
*/
rc = aws_iot_mqtt_autoreconnect_set_status(&client, true);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d", rc);
abort();
}
const char *TOPIC = "topic/iot_signup";
const int TOPIC_LEN = strlen(TOPIC);
paramsQOS0.qos = QOS0;
paramsQOS0.payload = (void *) cPayload;
paramsQOS0.isRetained = 0;
rc = aws_iot_mqtt_yield(&client, 100);
sprintf(cPayload, "{\"username\" : \"%s\"}",username);
paramsQOS0.payloadLen = strlen(cPayload);
rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS0);
if (rc == MQTT_REQUEST_TIMEOUT_ERROR) {
ESP_LOGW(TAG, "QOS1 publish ack not received.");
} else {
ESP_LOGI(TAG, "Signup publish successful.");
//TODO: fix race issue
this->init(thingId);
char JsonDocumentBuffer[400];
sprintf(JsonDocumentBuffer,
"{\"state\": {\"reported\": {\"thingname\":\"%s\",\"username\":\"%s\", \"td\": [\"Temp 1\",\"Temp 2\",\"Temp 3\"], \"t\": [0,0,0], \"tl\": [0,0,0], \"tu\": [100,100,100]}}, \"clientToken\":\"%s-100\"}",
thingId,username,thingId);
this->sendraw(JsonDocumentBuffer);
this->close();
saveRegisterStatus(true);
}
return 0;
}
int IotDataMqtt::init(char* thingName) {
IoT_Error_t rc = FAILURE;
strcpy(this->thingName,thingName);
strcpy(this->thingId,thingName);
ESP_LOGI(IotDataMqtt::TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
ShadowInitParameters_t sp = ShadowInitParametersDefault;
sp.pHost = (char*)IotDataMqtt::HOST;
sp.port = IotDataMqtt::PORT;
sp.pClientCRT = (const char *)certificate_and_ca_pem_crt_start;
//sp.pClientCRT = (const char *)certificate_pem_crt_start;
sp.pClientKey = (const char *)private_pem_key_start;
sp.pRootCA = (const char *)aws_root_ca_pem_start;
sp.enableAutoReconnect = false;
sp.disconnectHandler = disconnectCallbackHandler;
ESP_LOGI(TAG, "Shadow Init");
rc = aws_iot_shadow_init(&mqttClient, &sp);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "aws_iot_shadow_init returned error %d, aborting...", rc);
abort();
}
ShadowConnectParameters_t scp = ShadowConnectParametersDefault;
//AWS recommends setting thing name equal to client id
scp.pMyThingName = this->thingName;
scp.pMqttClientId = this->thingName;
scp.mqttClientIdLen = (uint16_t) strlen(this->thingName);
ESP_LOGI(IotDataMqtt::TAG, "Shadow Connect");
rc = aws_iot_shadow_connect(&mqttClient, &scp);
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "aws_iot_shadow_connect returned error %d, aborting...", rc);
abort();
}
/*
* Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
* #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
* #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
*/
rc = aws_iot_shadow_set_autoreconnect_status(&mqttClient, true);
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "Unable to set Auto Reconnect to true - %d, aborting...", rc);
}
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "Shadow Register Delta Error");
}
return rc;
}
int IotDataMqtt::send(char* JsonDocumentBuffer, size_t sizeOfJsonDocumentBuffer, jsonStruct_t* data, int sizeData) {
IoT_Error_t rc = SUCCESS;
bool sent = false;
while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) {
rc = aws_iot_shadow_yield(&mqttClient, 200);
if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) {
rc = aws_iot_shadow_yield(&mqttClient, 1000);
// If the client is attempting to reconnect, or already waiting on a shadow update,
// we will skip the rest of the loop.
continue;
}
if (sent) {
break;
}
ESP_LOGI(IotDataMqtt::TAG, "init_json");
rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
if(SUCCESS == rc) {
ESP_LOGI(IotDataMqtt::TAG, "add_array");
rc = aws_iot_shadow_add_array_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, sizeData, data);
if(SUCCESS == rc) {
ESP_LOGI(IotDataMqtt::TAG, "finalize");
rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
if(SUCCESS == rc) {
ESP_LOGI(IotDataMqtt::TAG, "Update Shadow: %s", JsonDocumentBuffer);
rc = aws_iot_shadow_update(&mqttClient, thingName, JsonDocumentBuffer,
ShadowUpdateStatusCallback, NULL, 4, true);
shadowUpdateInProgress = true;
sent = true;
}
}
}
ESP_LOGI(TAG, "*****************************************************************************************");
}
if(SUCCESS != rc) {
ESP_LOGE(TAG, "An error occurred in the loop %d", rc);
}
return rc;
}
int IotDataMqtt::sendraw(char* JsonDocumentBuffer) {
IoT_Error_t rc = SUCCESS;
bool sent = false;
while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) {
ESP_LOGI(TAG, "yield");
rc = aws_iot_shadow_yield(&mqttClient, 100);
if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) {
ESP_LOGI(TAG, "yield2");
rc = aws_iot_shadow_yield(&mqttClient, 100);
// If the client is attempting to reconnect, or already waiting on a shadow update,
// we will skip the rest of the loop.
continue;
}
if (sent) {
break;
}
ESP_LOGI(IotDataMqtt::TAG, "Update Shadow: %s", JsonDocumentBuffer);
rc = aws_iot_shadow_update(&mqttClient, thingName, JsonDocumentBuffer,
ShadowUpdateStatusCallback, NULL, 4, true);
ESP_LOGI(TAG, "update: %d",rc);
shadowUpdateInProgress = true;
sent = true;
vTaskDelay(2000 / portTICK_RATE_MS);
ESP_LOGI(TAG, "*****************************************************************************************");
}
if(SUCCESS != rc) {
ESP_LOGE(TAG, "An error occurred in the loop %d", rc);
}
return rc;
}
int IotDataMqtt::close() {
IoT_Error_t rc = SUCCESS;
ESP_LOGI(TAG, "Disconnecting");
rc = aws_iot_shadow_disconnect(&mqttClient);
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "Disconnect error %d", rc);
}
return rc;
}
/*
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
return ESP_OK;
}
*/
| 34.069588
| 205
| 0.667827
|
nkskjames
|
c73faa6d771bdc30f574843285dbb285760bc25a
| 15,360
|
cpp
|
C++
|
onut/src/onut.cpp
|
Daivuk/ggj16
|
0ba896f3b6ece32ed3a6e190825e53e88f666d5e
|
[
"MIT"
] | null | null | null |
onut/src/onut.cpp
|
Daivuk/ggj16
|
0ba896f3b6ece32ed3a6e190825e53e88f666d5e
|
[
"MIT"
] | null | null | null |
onut/src/onut.cpp
|
Daivuk/ggj16
|
0ba896f3b6ece32ed3a6e190825e53e88f666d5e
|
[
"MIT"
] | 1
|
2019-10-19T04:49:33.000Z
|
2019-10-19T04:49:33.000Z
|
#include <cassert>
#include <mutex>
#include <sstream>
#include "Audio.h"
#include "InputDevice.h"
#include "onut.h"
#include "Window.h"
using namespace DirectX;
// Our engine services
onut::Window* OWindow = nullptr;
onut::Renderer* ORenderer = nullptr;
onut::Settings* OSettings = new onut::Settings();
onut::SpriteBatch* OSpriteBatch = nullptr;
onut::PrimitiveBatch* OPrimitiveBatch = nullptr;
onut::GamePad* g_gamePads[4] = {nullptr};
onut::EventManager* OEvent = nullptr;
onut::ContentManager* OContentManager = nullptr;
AudioEngine* g_pAudioEngine = nullptr;
onut::TimeInfo<> g_timeInfo;
onut::Synchronous<onut::Pool<>> g_mainSync;
onut::ParticleSystemManager<>* OParticles = nullptr;
Vector2 OMousePos;
onut::InputDevice* g_inputDevice = nullptr;
onut::Input* OInput = nullptr;
onut::UIContext* OUIContext = nullptr;
onut::UIControl* OUI = nullptr;
onut::Music* OMusic = nullptr;
// So commonly used stuff
float ODT = 0.f;
namespace onut
{
void createUI()
{
OUIContext = new UIContext(sUIVector2(OScreenWf, OScreenHf));
OUI = new UIControl();
OUI->retain();
OUI->widthType = eUIDimType::DIM_RELATIVE;
OUI->heightType = eUIDimType::DIM_RELATIVE;
OUIContext->onClipping = [](bool enabled, const onut::sUIRect& rect)
{
OSB->end();
ORenderer->setScissor(enabled, onut::UI2Onut(rect));
OSB->begin();
};
auto getTextureForState = [](onut::UIControl *pControl, const std::string &filename)
{
static std::string stateFilename;
stateFilename = filename;
OTexture *pTexture;
switch (pControl->getState(*OUIContext))
{
case onut::eUIState::NORMAL:
pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DISABLED:
stateFilename.insert(filename.size() - 4, "_disabled");
pTexture = OGetTexture(stateFilename.c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::HOVER:
stateFilename.insert(filename.size() - 4, "_hover");
pTexture = OGetTexture(stateFilename.c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DOWN:
stateFilename.insert(filename.size() - 4, "_down");
pTexture = OGetTexture(stateFilename.c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
}
return pTexture;
};
OUIContext->drawRect = [=](onut::UIControl *pControl, const onut::sUIRect &rect, const onut::sUIColor &color)
{
OSB->drawRect(nullptr, onut::UI2Onut(rect), onut::UI2Onut(color));
};
OUIContext->drawTexturedRect = [=](onut::UIControl *pControl, const onut::sUIRect &rect, const onut::sUIImageComponent &image)
{
OSB->drawRect(getTextureForState(pControl, image.filename),
onut::UI2Onut(rect),
onut::UI2Onut(image.color));
};
OUIContext->drawScale9Rect = [=](onut::UIControl* pControl, const onut::sUIRect& rect, const onut::sUIScale9Component& scale9)
{
const std::string &filename = scale9.image.filename;
OTexture *pTexture;
switch (pControl->getState(*OUIContext))
{
case onut::eUIState::NORMAL:
pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DISABLED:
pTexture = OGetTexture((filename + "_disabled").c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::HOVER:
pTexture = OGetTexture((filename + "_hover").c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DOWN:
pTexture = OGetTexture((filename + "_down").c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
}
if (scale9.isRepeat)
{
OSB->drawRectScaled9RepeatCenters(getTextureForState(pControl, scale9.image.filename),
onut::UI2Onut(rect),
onut::UI2Onut(scale9.padding),
onut::UI2Onut(scale9.image.color));
}
else
{
OSB->drawRectScaled9(getTextureForState(pControl, scale9.image.filename),
onut::UI2Onut(rect),
onut::UI2Onut(scale9.padding),
onut::UI2Onut(scale9.image.color));
}
};
OUIContext->drawText = [=](onut::UIControl* pControl, const onut::sUIRect& rect, const onut::sUITextComponent& text)
{
if (text.text.empty()) return;
auto align = onut::UI2Onut(text.font.align);
auto oRect = onut::UI2Onut(rect);
auto pFont = OGetBMFont(text.font.typeFace.c_str());
auto oColor = onut::UI2Onut(text.font.color);
if (pControl->getState(*OUIContext) == onut::eUIState::DISABLED)
{
oColor = {.4f, .4f, .4f, 1};
}
oColor.Premultiply();
if (pFont)
{
if (pControl->getStyleName() == "password")
{
std::string pwd;
pwd.resize(text.text.size(), '*');
if (pControl->hasFocus(*OUIContext) && ((onut::UITextBox*)pControl)->isCursorVisible())
{
pwd.back() = '_';
}
pFont->draw<>(pwd, ORectAlign<>(oRect, align), oColor, OSB, align);
}
else
{
pFont->draw<>(text.text, ORectAlign<>(oRect, align), oColor, OSB, align);
}
}
};
OUIContext->addTextCaretSolver<onut::UITextBox>("", [=](const onut::UITextBox* pTextBox, const onut::sUIVector2& localPos) -> decltype(std::string().size())
{
auto pFont = OGetBMFont(pTextBox->textComponent.font.typeFace.c_str());
if (!pFont) return 0;
auto& text = pTextBox->textComponent.text;
return pFont->caretPos(text, localPos.x - 4);
});
OWindow->onWrite = [](char c)
{
OUIContext->write(c);
};
OWindow->onKey = [](uintptr_t key)
{
OUIContext->keyDown(key);
};
OUIContext->addStyle<onut::UIPanel>("blur", [](const onut::UIPanel* pPanel, const onut::sUIRect& rect)
{
OSB->end();
ORenderer->getRenderTarget()->blur();
OSB->begin();
OSB->drawRect(nullptr, onut::UI2Onut(rect), Color(0, 0, 0, .5f));
});
}
void createServices()
{
// Random
randomizeSeed();
// Events
OEvent = new EventManager();
// Window
OWindow = new Window(OSettings->getResolution(), OSettings->getIsResizableWindow());
// DirectX
ORenderer = new Renderer(*OWindow);
// SpriteBatch
OSB = new SpriteBatch();
OPB = new PrimitiveBatch();
// Content
OContentManager = new ContentManager();
OContentManager->addDefaultSearchPaths();
// Mouse/Keyboard
g_inputDevice = new InputDevice(OWindow);
OInput = new onut::Input(OINPUT_MOUSEZ + 1);
// Gamepads
for (int i = 0; i < 4; ++i)
{
g_gamePads[i] = new GamePad(i);
g_gamePads[i]->update();
}
// Audio
#ifdef WIN32
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#endif
AUDIO_ENGINE_FLAGS eflags = AudioEngine_Default;
#ifdef _DEBUG
eflags = eflags | AudioEngine_Debug;
#endif
try
{
g_pAudioEngine = new AudioEngine(eflags);
}
catch (std::exception e)
{
}
// Particles
OParticles = new ParticleSystemManager<>();
// Register a bunch of default events
OEvent->addEvent("NavigateLeft", []
{
return OJustPressed(OLeftBtn) || OJustPressed(OLLeftBtn);
});
OEvent->addEvent("NavigateRight", []
{
return OJustPressed(ORightBtn) || OJustPressed(OLRightBtn);
});
OEvent->addEvent("NavigateUp", []
{
return OJustPressed(OUpBtn) || OJustPressed(OLUpBtn);
});
OEvent->addEvent("NavigateDown", []
{
return OJustPressed(ODownBtn) || OJustPressed(OLDownBtn);
});
OEvent->addEvent("Accept", []
{
return OJustPressed(OABtn) || OJustPressed(OStartBtn);
});
OEvent->addEvent("Cancel", []
{
return OJustPressed(OBBtn);
});
OEvent->addEvent("Start", []
{
return OJustPressed(OStartBtn);
});
OEvent->addEvent("Back", []
{
return OJustPressed(OBackBtn) || OJustPressed(OBBtn);
});
// UI Context
createUI();
// Music
OMusic = new onut::Music();
}
void cleanup()
{
delete OMusic;
delete OUIContext;
delete OParticles;
delete g_pAudioEngine;
for (int i = 0; i < 4; ++i)
{
delete g_gamePads[i];
}
delete OInput;
delete g_inputDevice;
delete OContentManager;
delete OPB;
delete OSB;
delete ORenderer;
delete OWindow;
delete OEvent;
}
// Start the engine
void run(std::function<void()> initCallback, std::function<void()> updateCallback, std::function<void()> renderCallback)
{
// Make sure we run just once
static bool alreadyRan = false;
assert(!alreadyRan);
alreadyRan = true;
createServices();
// Call the user defined init
if (initCallback)
{
initCallback();
}
// Main loop
MSG msg = {0};
while (true)
{
if (OSettings->getIsEditorMode())
{
if (GetMessage(&msg, 0, 0, 0) >= 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
break;
}
}
}
else
{
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
break;
}
}
}
// Sync to main callbacks
g_mainSync.processQueue();
// Update
if (g_pAudioEngine) g_pAudioEngine->Update();
auto framesToUpdate = g_timeInfo.update(OSettings->getIsFixedStep());
ODT = onut::getTimeInfo().getDeltaTime<float>();
while (framesToUpdate--)
{
g_inputDevice->update();
OInput->update();
POINT cur;
GetCursorPos(&cur);
ScreenToClient(OWindow->getHandle(), &cur);
OInput->mousePos.x = cur.x;
OInput->mousePos.y = cur.y;
OInput->mousePosf.x = static_cast<float>(cur.x);
OInput->mousePosf.y = static_cast<float>(cur.y);
OMousePos = OInput->mousePosf;
for (auto& gamePad : g_gamePads)
{
gamePad->update();
}
if (OUIContext->useNavigation)
{
OUI->update(*OUIContext, sUIVector2(OInput->mousePosf.x, OInput->mousePosf.y), OGamePadPressed(OABtn), false, false,
OGamePadJustPressed(OLeftBtn) || OGamePadJustPressed(OLLeftBtn),
OGamePadJustPressed(ORightBtn) || OGamePadJustPressed(OLRightBtn),
OGamePadJustPressed(OUpBtn) || OGamePadJustPressed(OLUpBtn),
OGamePadJustPressed(ODownBtn) || OGamePadJustPressed(OLDownBtn),
0.f);
}
else
{
OUI->update(*OUIContext, sUIVector2(OInput->mousePosf.x, OInput->mousePosf.y), OPressed(OINPUT_MOUSEB1), OPressed(OINPUT_MOUSEB2), OPressed(OINPUT_MOUSEB3),
false, false, false, false,
OPressed(OINPUT_LCONTROL), OInput->getStateValue(OINPUT_MOUSEZ));
}
AnimManager::getGlobalManager()->update();
OEvent->processEvents();
OParticles->update();
if (updateCallback)
{
updateCallback();
}
}
// Render
g_timeInfo.render();
ORenderer->beginFrame();
if (renderCallback)
{
renderCallback();
}
OParticles->render();
OSB->begin();
OSB->changeFiltering(onut::SpriteBatch::eFiltering::Nearest);
OUI->render(*OUIContext);
OSB->end();
ORenderer->endFrame();
}
cleanup();
}
GamePad* getGamePad(int index)
{
assert(index >= 0 && index <= 3);
return g_gamePads[index];
}
const TimeInfo<>& getTimeInfo()
{
return g_timeInfo;
}
void drawPal(const OPal& pal, OFont* pFont)
{
static const float H = 32.f;
float i = 0;
OSB->begin();
for (auto& color : pal)
{
OSB->drawRect(nullptr, {0, i, H * GOLDEN_RATIO, H}, color);
i += H;
}
if (pFont)
{
i = 0;
int index = 0;
for (auto& color : pal)
{
std::stringstream ss;
ss << index;
pFont->draw<OCenter>(ss.str(), Rect{0, i, H * GOLDEN_RATIO, H}.Center(), Color::Black);
i += H;
++index;
}
}
OSB->end();
}
}
| 33.982301
| 176
| 0.484375
|
Daivuk
|
c7415ed8fe10f663b4035c93700c36926c2e33a4
| 1,482
|
cpp
|
C++
|
tools/Container/Containerlogger.cpp
|
fstudio/Phoenix
|
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
|
[
"MIT"
] | 8
|
2015-01-23T05:41:46.000Z
|
2019-11-20T05:10:27.000Z
|
tools/Container/Containerlogger.cpp
|
fstudio/Phoenix
|
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
|
[
"MIT"
] | null | null | null |
tools/Container/Containerlogger.cpp
|
fstudio/Phoenix
|
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
|
[
"MIT"
] | 4
|
2015-05-05T05:15:43.000Z
|
2020-03-07T11:10:56.000Z
|
/*********************************************************************************************************
* Containerlogger.cpp
* Note: Phoenix Container
* Date: @2015.03
* E-mail:<forcemz@outlook.com>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include "ContainerAPI.h"
static FILE *logfp=nullptr;
static bool SetDefaultLogger()
{
wchar_t temp[4096]={0};
if(GetTempPathW(256,temp)==0)
return false;/// This Function invoke failed.
#if defined(_MSC_VER)&& _MSC_VER>=1400
wcscat_s(temp,4096,L"/Phoenix.tools.Container.defualt.v1.log");
if(_wfopen_s(&logfp,temp,L"a+")!=0)
return false;
#else
wcscat(temp,L"/Phoenix.tools.Container.defualt.v1.log");
if((logfp=wfopen(temp,L"a+"))==nullptr)
return false;
#endif
return true;
}
bool InitializeLogger()
{
return SetDefaultLogger();
}
void LoggerDestory()
{
if(logfp)
fclose(logfp);
}
void TRACEWithFile(FILE *fp,const wchar_t* format,...)
{
if(fp!=nullptr)
{
int ret;
va_list ap;
va_start(ap, format);
ret = vfwprintf_s(fp, format, ap);
va_end(ap);
}
}
void TRACE(const wchar_t* format,...)
{
if(logfp!=nullptr)
{
int ret;
va_list ap;
va_start(ap, format);
ret = vfwprintf_s(logfp, format, ap);
va_end(ap);
}
}
| 22.119403
| 107
| 0.556005
|
fstudio
|
c7449a6d1a4cda9ce40b45a470791de89486a982
| 2,630
|
cpp
|
C++
|
RegisterCodeGenerator/RegisterCodeGenerator.cpp
|
kevinwu1024/ExtremeCopy
|
de9ba1aef769d555d10916169ccf2570c69a8d01
|
[
"Apache-2.0"
] | 67
|
2020-11-12T11:51:37.000Z
|
2022-03-01T13:44:43.000Z
|
RegisterCodeGenerator/RegisterCodeGenerator.cpp
|
kevinwu1024/ExtremeCopy
|
de9ba1aef769d555d10916169ccf2570c69a8d01
|
[
"Apache-2.0"
] | 4
|
2021-04-09T08:22:06.000Z
|
2021-06-07T13:43:13.000Z
|
RegisterCodeGenerator/RegisterCodeGenerator.cpp
|
kevinwu1024/ExtremeCopy
|
de9ba1aef769d555d10916169ccf2570c69a8d01
|
[
"Apache-2.0"
] | 12
|
2020-11-12T11:51:42.000Z
|
2022-02-11T08:07:37.000Z
|
/****************************************************************************
Copyright (c) 2008-2020 Kevin Wu (Wu Feng)
github: https://github.com/kevinwu1024/ExtremeCopy
site: http://www.easersoft.com
Licensed under the Apache License, Version 2.0 License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/Apache-2.0
****************************************************************************/
#include "stdafx.h"
#include "RegisterCodeGenerator.h"
#include "RegisterCodeGeneratorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CRegisterCodeGeneratorApp
BEGIN_MESSAGE_MAP(CRegisterCodeGeneratorApp, CWinAppEx)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CRegisterCodeGeneratorApp construction
CRegisterCodeGeneratorApp::CRegisterCodeGeneratorApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CRegisterCodeGeneratorApp object
CRegisterCodeGeneratorApp theApp;
// CRegisterCodeGeneratorApp initialization
BOOL CRegisterCodeGeneratorApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
//SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CRegisterCodeGeneratorDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| 29.222222
| 104
| 0.725095
|
kevinwu1024
|
c7483cb6f45312806af90fa08caae046cdbee30b
| 274
|
cpp
|
C++
|
source/scene/entity.cpp
|
Kostu96/k2d-engine
|
8150230034cf4afc862fcc1a3c262c27d544feed
|
[
"MIT"
] | null | null | null |
source/scene/entity.cpp
|
Kostu96/k2d-engine
|
8150230034cf4afc862fcc1a3c262c27d544feed
|
[
"MIT"
] | null | null | null |
source/scene/entity.cpp
|
Kostu96/k2d-engine
|
8150230034cf4afc862fcc1a3c262c27d544feed
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2021-2022 Konstanty Misiak
*
* SPDX-License-Identifier: MIT
*/
#include "scene/entity.hpp"
namespace k2d {
Entity::Entity(entt::entity handle, Scene& scene) :
m_handle(handle),
m_sceneRef(scene)
{
}
} // namespace k2d
| 14.421053
| 55
| 0.616788
|
Kostu96
|
c74a50bad375c1f42e1c7bb3d7ac8674ae8754a4
| 4,786
|
cpp
|
C++
|
AcrosyncSwift/rsync/block/t_block_out.cpp
|
aaronvegh/AcrosyncSwift
|
469201f6d8ca407334d515260e47526c6965d008
|
[
"Unlicense"
] | null | null | null |
AcrosyncSwift/rsync/block/t_block_out.cpp
|
aaronvegh/AcrosyncSwift
|
469201f6d8ca407334d515260e47526c6965d008
|
[
"Unlicense"
] | null | null | null |
AcrosyncSwift/rsync/block/t_block_out.cpp
|
aaronvegh/AcrosyncSwift
|
469201f6d8ca407334d515260e47526c6965d008
|
[
"Unlicense"
] | null | null | null |
#include "block_out.h"
#include <stdio.h>
struct UserType1
{
int d_i;
double d_d;
};
class UserType2
{
int d_i;
double d_d;
public:
UserType2() {}
~UserType2() {}
};
class Source
{
public:
block::out<void()> out0;
block::out<void(const char*)> out1;
block::out<void(const char*, int)> out2;
block::out<void(const char*, int, char)> out3;
block::out<void(const char*, int, char, float)> out4;
block::out<void(const char*, int, char, float, double)> out5;
block::out<void(const char*, int, char, float, double, void *)> out6;
block::out<void(const char*, int, char, float, double, void *, UserType1)> out7;
block::out<void(const char*, int, char, float, double, void *, UserType1, UserType2)> out8;
// not connected
block::out<void(int, double)> out100;
block::out<void(const int &, double)> out101;
block::out<void(int, const double&)> out102;
block::out<int(int, double)> out103;
block::out<void(int&, double)> out104;
block::out<void(int, double&)> out105;
// connected to mulitple inports
block::out<void(int, double)> out200;
block::out<void(const int &, double)> out201;
block::out<void(int, const double&)> out202;
block::out<int(int, double)> out203;
block::out<void(int&, double)> out204;
block::out<void(int, double&)> out205;
void Run()
{
out0();
out1("Hello World");
out2("Hello World", 1);
out3("Hello World", 1, '2');
out4("Hello World", 1, '2', 3.0f);
out5("Hello World", 1, '2', 3.0f, 4.0);
out6("Hello World", 1, '2', 3.0f, 4.0, 0);
out7("Hello World", 1, '2', 3.0f, 4.0, 0, UserType1());
out8("Hello World", 1, '2', 3.0f, 4.0, 0, UserType1(), UserType2());
int i = 1;
double d = 2.0;
out100(1, 2.0);
out101(1, 2.0);
out102(1, 2.0);
//out103(1, 2.0);
out104(i, d);
out105(i, d);
out200(1, 2.0);
out201(1, 2.0);
out202(1, 2.0);
out203(1, 2.0);
out204(i, d);
out205(i, d);
}
};
struct Dummy
{
int d_i;
int d_double;
};
class Sink : public Dummy
{
private:
mutable int d_numCalls;
public:
Sink()
: d_numCalls(0)
{
}
int numCalls() const { return d_numCalls; }
void in0()
{
++d_numCalls;
}
void in1(const char*) const
{
++d_numCalls;
}
void in2(const char*, int)
{
++d_numCalls;
}
void in3(const char*, int, char) const
{
++d_numCalls;
}
void in4(const char*, int, char, float)
{
++d_numCalls;
}
void in5(const char*, int, char, float, double) const
{
++d_numCalls;
}
void in6(const char*, int, char, float, double, void *)
{
++d_numCalls;
}
void in7(const char*, int, char, float, double, void *, UserType1) const
{
++d_numCalls;
}
void in8(const char*, int, char, float, double, void *, UserType1, UserType2)
{
++d_numCalls;
}
void in200(int, double)
{
++d_numCalls;
}
void in201(const int&, double)
{
++d_numCalls;
}
void in202(int, const double&)
{
++d_numCalls;
}
int in203(int, double)
{
++d_numCalls;
return d_numCalls;
}
void in204(int&, double)
{
++d_numCalls;
}
void in205(int, double&)
{
++d_numCalls;
}
};
int main(int argc, char *argv[])
{
{
Source source;
Sink sink;
source.out0.connect(&sink, &Sink::in0);
source.out1.connect(&sink, &Sink::in1);
source.out2.connect(&sink, &Sink::in2);
source.out3.connect(&sink, &Sink::in3);
source.out4.connect(&sink, &Sink::in4);
source.out5.connect(&sink, &Sink::in5);
source.out6.connect(&sink, &Sink::in6);
source.out7.connect(&sink, &Sink::in7);
source.out8.connect(&sink, &Sink::in8);
source.out200.connect(&sink, &Sink::in200);
source.out200.connect(&sink, &Sink::in200);
source.out201.connect(&sink, &Sink::in201);
source.out201.connect(&sink, &Sink::in201);
source.out202.connect(&sink, &Sink::in202);
source.out202.connect(&sink, &Sink::in202);
source.out203.connect(&sink, &Sink::in203);
source.out203.connect(&sink, &Sink::in203);
source.out204.connect(&sink, &Sink::in204);
source.out204.connect(&sink, &Sink::in204);
source.out205.connect(&sink, &Sink::in205);
source.out205.connect(&sink, &Sink::in205);
source.Run();
printf("Member functions of Sink have been called %d times\n", sink.numCalls());
}
return 0;
}
| 23.93
| 95
| 0.547221
|
aaronvegh
|
c75b9297fc5af22e94dd59a6431d3def2205444e
| 14,738
|
cpp
|
C++
|
jack/common/JackAudioAdapterInterface.cpp
|
KimJeongYeon/jack2_android
|
4a8787be4306558cb52e5379466c0ed4cc67e788
|
[
"BSD-3-Clause-No-Nuclear-Warranty"
] | 47
|
2015-01-04T21:47:07.000Z
|
2022-03-23T16:27:16.000Z
|
vendor/samsung/external/jack/common/JackAudioAdapterInterface.cpp
|
cesarmo759/android_kernel_samsung_msm8916
|
f19717ef6c984b64a75ea600a735dc937b127c25
|
[
"Apache-2.0"
] | 3
|
2015-02-04T21:40:11.000Z
|
2019-09-16T19:53:51.000Z
|
jack/common/JackAudioAdapterInterface.cpp
|
KimJeongYeon/jack2_android
|
4a8787be4306558cb52e5379466c0ed4cc67e788
|
[
"BSD-3-Clause-No-Nuclear-Warranty"
] | 7
|
2015-05-17T08:22:52.000Z
|
2021-08-07T22:36:17.000Z
|
/*
Copyright (C) 2008 Grame
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#include "JackAudioAdapter.h"
#ifndef MY_TARGET_OS_IPHONE
#include "JackLibSampleRateResampler.h"
#endif
#include "JackTime.h"
#include "JackError.h"
#include <stdio.h>
namespace Jack
{
#ifdef JACK_MONITOR
void MeasureTable::Write(int time1, int time2, float r1, float r2, int pos1, int pos2)
{
int pos = (++fCount) % TABLE_MAX;
fTable[pos].time1 = time1;
fTable[pos].time2 = time2;
fTable[pos].r1 = r1;
fTable[pos].r2 = r2;
fTable[pos].pos1 = pos1;
fTable[pos].pos2 = pos2;
}
void MeasureTable::Save(unsigned int fHostBufferSize, unsigned int fHostSampleRate, unsigned int fAdaptedSampleRate, unsigned int fAdaptedBufferSize)
{
FILE* file = fopen("JackAudioAdapter.log", "w");
int max = (fCount) % TABLE_MAX - 1;
for (int i = 1; i < max; i++) {
fprintf(file, "%d \t %d \t %d \t %f \t %f \t %d \t %d \n",
fTable[i].delta, fTable[i].time1, fTable[i].time2,
fTable[i].r1, fTable[i].r2, fTable[i].pos1, fTable[i].pos2);
}
fclose(file);
// No used for now
// Adapter timing 1
file = fopen("AdapterTiming1.plot", "w");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 2 title \"Ringbuffer error\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 3 title \"Ringbuffer error with timing correction\" with lines");
fprintf(file, "\n unset multiplot\n");
fprintf(file, "set output 'AdapterTiming1.svg\n");
fprintf(file, "set terminal svg\n");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 2 title \"Consumer interrupt period\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 3 title \"Producer interrupt period\" with lines\n");
fprintf(file, "unset multiplot\n");
fprintf(file, "unset output\n");
fclose(file);
// Adapter timing 2
file = fopen("AdapterTiming2.plot", "w");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"resampling ratio\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 4 title \"Ratio 1\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 5 title \"Ratio 2\" with lines");
fprintf(file, "\n unset multiplot\n");
fprintf(file, "set output 'AdapterTiming2.svg\n");
fprintf(file, "set terminal svg\n");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"resampling ratio\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 4 title \"Ratio 1\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 5 title \"Ratio 2\" with lines\n");
fprintf(file, "unset multiplot\n");
fprintf(file, "unset output\n");
fclose(file);
// Adapter timing 3
file = fopen("AdapterTiming3.plot", "w");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 6 title \"Frames position in consumer ringbuffer\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 7 title \"Frames position in producer ringbuffer\" with lines");
fprintf(file, "\n unset multiplot\n");
fprintf(file, "set output 'AdapterTiming3.svg\n");
fprintf(file, "set terminal svg\n");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 6 title \"Frames position in consumer ringbuffer\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 7 title \"Frames position in producer ringbuffer\" with lines\n");
fprintf(file, "unset multiplot\n");
fprintf(file, "unset output\n");
fclose(file);
}
#endif
void JackAudioAdapterInterface::GrowRingBufferSize()
{
fRingbufferCurSize *= 2;
}
void JackAudioAdapterInterface::AdaptRingBufferSize()
{
if (fHostBufferSize > fAdaptedBufferSize) {
fRingbufferCurSize = 4 * fHostBufferSize;
} else {
fRingbufferCurSize = 4 * fAdaptedBufferSize;
}
}
void JackAudioAdapterInterface::ResetRingBuffers()
{
if (fRingbufferCurSize > DEFAULT_RB_SIZE) {
fRingbufferCurSize = DEFAULT_RB_SIZE;
}
for (int i = 0; i < fCaptureChannels; i++) {
fCaptureRingBuffer[i]->Reset(fRingbufferCurSize);
}
for (int i = 0; i < fPlaybackChannels; i++) {
fPlaybackRingBuffer[i]->Reset(fRingbufferCurSize);
}
}
void JackAudioAdapterInterface::Reset()
{
ResetRingBuffers();
fRunning = false;
}
#ifdef MY_TARGET_OS_IPHONE
void JackAudioAdapterInterface::Create()
{}
#else
void JackAudioAdapterInterface::Create()
{
//ringbuffers
fCaptureRingBuffer = new JackResampler*[fCaptureChannels];
fPlaybackRingBuffer = new JackResampler*[fPlaybackChannels];
if (fAdaptative) {
AdaptRingBufferSize();
jack_info("Ringbuffer automatic adaptative mode size = %d frames", fRingbufferCurSize);
} else {
if (fRingbufferCurSize > DEFAULT_RB_SIZE) {
fRingbufferCurSize = DEFAULT_RB_SIZE;
}
jack_info("Fixed ringbuffer size = %d frames", fRingbufferCurSize);
}
for (int i = 0; i < fCaptureChannels; i++ ) {
fCaptureRingBuffer[i] = new JackLibSampleRateResampler(fQuality);
fCaptureRingBuffer[i]->Reset(fRingbufferCurSize);
}
for (int i = 0; i < fPlaybackChannels; i++ ) {
fPlaybackRingBuffer[i] = new JackLibSampleRateResampler(fQuality);
fPlaybackRingBuffer[i]->Reset(fRingbufferCurSize);
}
if (fCaptureChannels > 0) {
jack_log("ReadSpace = %ld", fCaptureRingBuffer[0]->ReadSpace());
}
if (fPlaybackChannels > 0) {
jack_log("WriteSpace = %ld", fPlaybackRingBuffer[0]->WriteSpace());
}
}
#endif
void JackAudioAdapterInterface::Destroy()
{
for (int i = 0; i < fCaptureChannels; i++) {
delete(fCaptureRingBuffer[i]);
}
for (int i = 0; i < fPlaybackChannels; i++) {
delete (fPlaybackRingBuffer[i]);
}
delete[] fCaptureRingBuffer;
delete[] fPlaybackRingBuffer;
}
int JackAudioAdapterInterface::PushAndPull(float** inputBuffer, float** outputBuffer, unsigned int frames)
{
bool failure = false;
fRunning = true;
// Finer estimation of the position in the ringbuffer
int delta_frames = (fPullAndPushTime > 0) ? (int)((float(long(GetMicroSeconds() - fPullAndPushTime)) * float(fAdaptedSampleRate)) / 1000000.f) : 0;
double ratio = 1;
// TODO : done like this just to avoid crash when input only or output only...
if (fCaptureChannels > 0) {
ratio = fPIControler.GetRatio(fCaptureRingBuffer[0]->GetError() - delta_frames);
} else if (fPlaybackChannels > 0) {
ratio = fPIControler.GetRatio(fPlaybackRingBuffer[0]->GetError() - delta_frames);
}
#ifdef JACK_MONITOR
if (fCaptureRingBuffer && fCaptureRingBuffer[0] != NULL)
fTable.Write(fCaptureRingBuffer[0]->GetError(), fCaptureRingBuffer[0]->GetError() - delta_frames, ratio, 1/ratio, fCaptureRingBuffer[0]->ReadSpace(), fCaptureRingBuffer[0]->ReadSpace());
#endif
// Push/pull from ringbuffer
for (int i = 0; i < fCaptureChannels; i++) {
fCaptureRingBuffer[i]->SetRatio(ratio);
if (inputBuffer[i]) {
if (fCaptureRingBuffer[i]->WriteResample(inputBuffer[i], frames) < frames) {
failure = true;
}
}
}
for (int i = 0; i < fPlaybackChannels; i++) {
fPlaybackRingBuffer[i]->SetRatio(1/ratio);
if (outputBuffer[i]) {
if (fPlaybackRingBuffer[i]->ReadResample(outputBuffer[i], frames) < frames) {
failure = true;
}
}
}
// Reset all ringbuffers in case of failure
if (failure) {
jack_error("JackAudioAdapterInterface::PushAndPull ringbuffer failure... reset");
if (fAdaptative) {
GrowRingBufferSize();
jack_info("Ringbuffer size = %d frames", fRingbufferCurSize);
}
ResetRingBuffers();
return -1;
} else {
return 0;
}
}
int JackAudioAdapterInterface::PullAndPush(float** inputBuffer, float** outputBuffer, unsigned int frames)
{
fPullAndPushTime = GetMicroSeconds();
if (!fRunning)
return 0;
int res = 0;
// Push/pull from ringbuffer
for (int i = 0; i < fCaptureChannels; i++) {
if (inputBuffer[i]) {
if (fCaptureRingBuffer[i]->Read(inputBuffer[i], frames) < frames) {
res = -1;
}
}
}
for (int i = 0; i < fPlaybackChannels; i++) {
if (outputBuffer[i]) {
if (fPlaybackRingBuffer[i]->Write(outputBuffer[i], frames) < frames) {
res = -1;
}
}
}
return res;
}
int JackAudioAdapterInterface::SetHostBufferSize(jack_nframes_t buffer_size)
{
fHostBufferSize = buffer_size;
if (fAdaptative) {
AdaptRingBufferSize();
}
return 0;
}
int JackAudioAdapterInterface::SetAdaptedBufferSize(jack_nframes_t buffer_size)
{
fAdaptedBufferSize = buffer_size;
if (fAdaptative) {
AdaptRingBufferSize();
}
return 0;
}
int JackAudioAdapterInterface::SetBufferSize(jack_nframes_t buffer_size)
{
SetHostBufferSize(buffer_size);
SetAdaptedBufferSize(buffer_size);
return 0;
}
int JackAudioAdapterInterface::SetHostSampleRate(jack_nframes_t sample_rate)
{
fHostSampleRate = sample_rate;
fPIControler.Init(double(fHostSampleRate) / double(fAdaptedSampleRate));
return 0;
}
int JackAudioAdapterInterface::SetAdaptedSampleRate(jack_nframes_t sample_rate)
{
fAdaptedSampleRate = sample_rate;
fPIControler.Init(double(fHostSampleRate) / double(fAdaptedSampleRate));
return 0;
}
int JackAudioAdapterInterface::SetSampleRate(jack_nframes_t sample_rate)
{
SetHostSampleRate(sample_rate);
SetAdaptedSampleRate(sample_rate);
return 0;
}
void JackAudioAdapterInterface::SetInputs(int inputs)
{
jack_log("JackAudioAdapterInterface::SetInputs %d", inputs);
fCaptureChannels = inputs;
}
void JackAudioAdapterInterface::SetOutputs(int outputs)
{
jack_log("JackAudioAdapterInterface::SetOutputs %d", outputs);
fPlaybackChannels = outputs;
}
int JackAudioAdapterInterface::GetInputs()
{
//jack_log("JackAudioAdapterInterface::GetInputs %d", fCaptureChannels);
return fCaptureChannels;
}
int JackAudioAdapterInterface::GetOutputs()
{
//jack_log ("JackAudioAdapterInterface::GetOutputs %d", fPlaybackChannels);
return fPlaybackChannels;
}
} // namespace
| 37.501272
| 198
| 0.612838
|
KimJeongYeon
|
c75d6532c3edff8bcbab0d8cf565f8e658b95386
| 2,744
|
cpp
|
C++
|
Codechef/dec challenge 2017/CHEFHAM.cpp
|
dipta007/Competitive-Programming
|
998d47f08984703c5b415b98365ddbc84ad289c4
|
[
"MIT"
] | 6
|
2018-10-15T18:45:05.000Z
|
2022-03-29T04:30:10.000Z
|
Codechef/dec challenge 2017/CHEFHAM.cpp
|
dipta007/Competitive-Programming
|
998d47f08984703c5b415b98365ddbc84ad289c4
|
[
"MIT"
] | null | null | null |
Codechef/dec challenge 2017/CHEFHAM.cpp
|
dipta007/Competitive-Programming
|
998d47f08984703c5b415b98365ddbc84ad289c4
|
[
"MIT"
] | 4
|
2018-01-07T06:20:07.000Z
|
2019-08-21T15:45:59.000Z
|
#pragma comment(linker, "/stack:640000000")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
// g++ -g -O2 -std=gnu++11 A.cpp
// ./a.out
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
int t;
cin >> t;
for(int ci=1; ci<=t; ci++)
{
int n;
cin >> n;
int a[n], sa[n], sba[n];
for(int i=0; i<n; i++)
{
cin >> a[i];
sa[i] = a[i];
sba[i] = a[i];
}
sort(sa, sa+n);
sort(sba, sba+n);
reverse(sba, sba+n);
//cout << n << endl;
if(n==1)
{
cout << 0 << endl;
cout << a[0] << endl;
continue;
}
else if(n==2)
{
if(a[0] == a[1]) cout << 0 << endl;
else cout << 2 << endl;
cout << a[1] << " " << a[0] << endl;
continue;
}
else if(n==3)
{
if(a[0]==a[1])
{
cout << 2 << endl;
cout << a[2] << " " << a[0] << " " << a[1] << endl;
}
else if(a[1] == a[2])
{
cout << 2 << endl;
cout << a[1] << " " << a[0] << " " << a[2] << endl;
}
else
{
if(a[0] == a[2]) cout << 2 << endl;
else cout << 3 << endl;
cout << a[2] << " " << a[0] << " " << a[1] << endl;
}
continue;
}
cout << n << endl;
int in = 0;
for(int i=0; i<n; i++)
{
if(sa[i]==sba[i])
{
swap(sba[i], sba[in]);
in = n-1;
}
}
map < int, int > mp1, mp2;
for(int i=0; i<n; i++)
{
if(mp1[sa[i]] != 0)
{
mp2[sa[i]] = sba[i];
continue;
}
mp1[ sa[i] ] = sba[i];
}
int b[n];
for(int i=0; i<n; i++)
{
if(mp1[a[i]]==0)
{
b[i] = mp2[a[i]];
continue;
}
b[i] = mp1[ a[i] ];
mp1[ a[i] ] = 0;
}
for(int i=0; i<n; i++)
{
if(i) cout << " ";
cout << b[i];
}
cout << endl;
}
return 0;
}
| 20.029197
| 67
| 0.34293
|
dipta007
|
c75f385c1ed02bf476e70989d760aa477b4e43f7
| 3,025
|
cpp
|
C++
|
src/Main.cpp
|
innatewonder/onyx
|
fffb16ab068871fe3d948fa64eff81ce1dc31524
|
[
"MIT"
] | null | null | null |
src/Main.cpp
|
innatewonder/onyx
|
fffb16ab068871fe3d948fa64eff81ce1dc31524
|
[
"MIT"
] | null | null | null |
src/Main.cpp
|
innatewonder/onyx
|
fffb16ab068871fe3d948fa64eff81ce1dc31524
|
[
"MIT"
] | null | null | null |
#include "CommonPrecompiled.h"
#include "NetworkEngine.h"
#include "OnyxTransfer.h"
#include "HTTP.h"
#include "UDPBase.h"
#include "TCPBase.h"
#include "ByteArray.h"
//handle closing connections
//handle timeouts
//handle sending queue
//handle arbitrary connect requests
int main(int argc, char** argv)
{
ArgParser args(argc, argv);
args.AddCommand("-p", "-port", true);
args.AddCommand("-s", "-serv");
args.AddCommand("-sa", "-serverAddr", false, true);
args.AddCommand("-sp", "-serverPort", false, true);
args.AddCommand("-f", "-folder", false, true);
args.AddCommand("-tcp", "-tcp");
args.AddCommand("-w", "-http");
args.Parse();
auto array = Networking::ByteWriter();
array.WriteS16(-5);
array.WriteU32(7052);
array.WriteU16(89);
array.WriteS32(-8787);
array.WriteF32(56.329864f);
auto buff = array.GetData();
auto buffSize = array.GetSize();
LOG("buffsize " << buffSize)
auto readArray = Networking::ByteReader(buff, buffSize);
s16 v1 = readArray.ReadS16();
u32 v2 = readArray.ReadU32();
u16 v3 = readArray.ReadU16();
s32 v4 = readArray.ReadS32();
f32 v5 = readArray.ReadF32();
LOG(v1 << " " << v2 << " " << v3 << " " << v4 << " " << v5);
return 0;
int port = 0;
if(args.Has("-p"))
{
port = args.Get("-port")->val.iVal;
}
auto engine = new Networking::NetworkEngine();
engine->Initialize(args);
auto serverAddr = Networking::Address("localhost", "10294");
if(args.Has("-sa") && args.Has("-sp"))
{
LOG("Got server from command line");
serverAddr.SetAddress(args.Get("-sa")->val.sVal, args.Get("-sp")->val.sVal);
}
if(args.Has("-folder"))
{
LOG("Adding onyx reader with given folder");
String folder = args.Get("-folder")->val.sVal;
auto reader = new Filesystem::FilesystemReader();
reader->OpenFolder(folder, true);
reader->OpenFile("10294.onyx");
if(args.Has("-serv"))
{
engine->AddProtocol(
new Networking::OnyxServer()
);
while(1)
{
engine->Update(0.016f);
SLEEP_MILLI(5);
}
}
else
{
engine->AddProtocol(
new Networking::OnyxClient(serverAddr, reader->GetFolder(folder))
);
engine->Update(0.f);
}
}
else if(args.Has("-w"))
{
LOG("serving web on " << port);
engine->AddProtocol(
new Networking::HTTP(port)
);
}
else if(args.Has("-serv"))
{
LOG("serving on port " << port);
if(args.Has("-tcp"))
{
LOG("TCP");
engine->AddProtocol(
new Networking::TCPBase(port)
);
}
else
{
engine->AddProtocol(
new Networking::UDPBase(port)
);
}
}
else
{
LOG("Connecting to server at: " << serverAddr)
if(args.Has("-tcp"))
{
LOG("TCP");
engine->AddProtocol(
new Networking::TCPBase(serverAddr, port)
);
}
else
{
engine->AddProtocol(
new Networking::UDPBase(serverAddr, port)
);
}
}
delete engine;
return 0;
}
| 21.453901
| 80
| 0.584793
|
innatewonder
|
c75fe3c2eaa69eaa41aaa26580ad41719fc37422
| 4,546
|
cpp
|
C++
|
day12/day12-tests/day12-tests.cpp
|
MattHarrington/advent-of-code-2019
|
8733d2692c4d619d1db3b82645032eebca934334
|
[
"MIT"
] | null | null | null |
day12/day12-tests/day12-tests.cpp
|
MattHarrington/advent-of-code-2019
|
8733d2692c4d619d1db3b82645032eebca934334
|
[
"MIT"
] | null | null | null |
day12/day12-tests/day12-tests.cpp
|
MattHarrington/advent-of-code-2019
|
8733d2692c4d619d1db3b82645032eebca934334
|
[
"MIT"
] | null | null | null |
// https://adventofcode.com/2019/day/12
#include <catch.hpp>
#include <numeric>
#include "day12-lib.h"
TEST_CASE("sample after 1 timestep should be correct", "[part_one]") {
const std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
const std::vector<Moon> moons_after_one_timestep{
Moon{{2,-1,1}, {3,-1,-1}},
Moon{{3,-7,-4}, {1,3,3}},
Moon{{1,-7,5}, {-3,1,-3}},
Moon{{2,2,0}, {-1,-3,1}}
};
REQUIRE(timestep(sample_moons) == moons_after_one_timestep);
}
TEST_CASE("sample after 10 timesteps should be correct", "[part_one]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
const std::vector<Moon> moons_after_10_timesteps{
Moon{{2,1,-3}, {-3,-2,1}},
Moon{{1,-8,0}, {-1,1,3}},
Moon{{3,-6,1}, {3,2,-3}},
Moon{{2,0,4}, {1,-1,-1}}
};
for (int i{ 0 }; i < 10; ++i) {
sample_moons = timestep(sample_moons);
}
REQUIRE(sample_moons == moons_after_10_timesteps);
}
TEST_CASE("energy of sample moon 1 should be 36", "[part_one]") {
const Moon moon{ {2,1,-3}, {-3,-2,1} };
REQUIRE(get_total_energy(moon) == 36);
}
TEST_CASE("energy of sample moon 2 should be 45", "[part_one]") {
const Moon moon{ {1,-8,0}, {-1,1,3} };
REQUIRE(get_total_energy(moon) == 45);
}
TEST_CASE("energy after 10 timesteps should be 179", "[part_one]") {
const std::vector<Moon> moons_after_10_timesteps{
Moon{{2,1,-3}, {-3,-2,1}},
Moon{{1,-8,0}, {-1,1,3}},
Moon{{3,-6,1}, {3,2,-3}},
Moon{{2,0,4}, {1,-1,-1}}
};
const int total_energy{ std::accumulate(begin(moons_after_10_timesteps), end(moons_after_10_timesteps),
0, [](int t, Moon m) noexcept {return t + get_total_energy(m); }) };
REQUIRE(total_energy == 179);
}
TEST_CASE("sample moons should repeat x value at timestep 18", "[part_two]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
int step{ 0 };
do {
sample_moons = timestep(sample_moons);
++step;
} while (sample_moons.at(0).position.x != -1 || sample_moons.at(1).position.x != 2
|| sample_moons.at(2).position.x != 4 || sample_moons.at(3).position.x != 3
|| sample_moons.at(0).velocity.x_velocity == sample_moons.at(1).velocity.x_velocity ==
sample_moons.at(2).velocity.x_velocity == sample_moons.at(3).velocity.x_velocity == 0);
REQUIRE(step == 18);
}
TEST_CASE("sample moons should repeat y value at timestep 28", "[part_two]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
int step{ 0 };
do {
sample_moons = timestep(sample_moons);
++step;
} while (sample_moons.at(0).position.y != 0 || sample_moons.at(1).position.y != -10 ||
sample_moons.at(2).position.y != -8 || sample_moons.at(3).position.y != 5
|| sample_moons.at(0).velocity.y_velocity == sample_moons.at(1).velocity.y_velocity ==
sample_moons.at(2).velocity.y_velocity == sample_moons.at(3).velocity.y_velocity == 0);
REQUIRE(step == 28);
}
TEST_CASE("sample moons should repeat z value at timestep 44", "[part_two]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
int step{ 0 };
do {
sample_moons = timestep(sample_moons);
++step;
} while (sample_moons.at(0).position.z != 2 || sample_moons.at(1).position.z != -7 ||
sample_moons.at(2).position.z != 8 || sample_moons.at(3).position.z != -1
|| sample_moons.at(0).velocity.z_velocity == sample_moons.at(1).velocity.z_velocity ==
sample_moons.at(2).velocity.z_velocity == sample_moons.at(3).velocity.z_velocity == 0);
REQUIRE(step == 44);
}
TEST_CASE("sample moons should repeat state at timestep 2722", "[part_two]") {
// 18, 28, and 44 are results from other TEST_CASEs
constexpr int repeat_timestep_x_y{ std::lcm(18,28) };
constexpr int repeat_timestep_xy_z{ std::lcm(repeat_timestep_x_y, 44) };
REQUIRE(repeat_timestep_xy_z == 2772);
}
| 35.515625
| 107
| 0.568412
|
MattHarrington
|
c76028d3464e5ff58ddd818e7f2967162a374edd
| 1,248
|
cpp
|
C++
|
ABC193/d.cpp
|
KoukiNAGATA/c-
|
ae51bacb9facb936a151dd777beb6688383a2dcd
|
[
"MIT"
] | null | null | null |
ABC193/d.cpp
|
KoukiNAGATA/c-
|
ae51bacb9facb936a151dd777beb6688383a2dcd
|
[
"MIT"
] | 3
|
2021-03-31T01:39:25.000Z
|
2021-05-04T10:02:35.000Z
|
ABC193/d.cpp
|
KoukiNAGATA/c-
|
ae51bacb9facb936a151dd777beb6688383a2dcd
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i <= n; i++)
#define FORR(i, m, n) for (int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v + n)
#define MAX 100000
#define inf 1000000007
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;
using Graph = vector<vector<int>>;
ll score(string s)
{
vector<ll> cnt(10);
// cnt[0] = 0, cnt[1] = 1, ..., cnt[9] = 9
iota(cnt.begin(), cnt.end(), 0);
// 見つかった枚数分だけ*10する
for (char c : s)
cnt[c - '0'] *= 10;
// 配列の合計値を求める
return accumulate(cnt.begin(), cnt.end(), 0);
}
int main()
{
ll k;
string s, t;
cin >> k >> s >> t;
vector<ll> cnt(10, k);
for (char c : s + t)
cnt[c - '0']--;
ll win = 0;
// x, yの組について全探索
FOR(x, 1, 9)
{
FOR(y, 1, 9)
{
s.back() = '0' + x;
t.back() = '0' + y;
if (score(s) <= score(t))
continue;
win += cnt[x] * (cnt[y] - (x == y));
}
}
cout << fixed << setprecision(10) << double(win) / ((9 * k - 8) * (9 * k - 9)) << "\n";
}
| 25.469388
| 91
| 0.459936
|
KoukiNAGATA
|
c760b548acedc9bd42a014357a84a0c6ce7f791a
| 1,086
|
cpp
|
C++
|
rules/gen/txt_to_cpp.cpp
|
hleclerc/nsmake
|
01c246311cb37d6d85776db87e413c61c692c9dd
|
[
"Apache-2.0"
] | null | null | null |
rules/gen/txt_to_cpp.cpp
|
hleclerc/nsmake
|
01c246311cb37d6d85776db87e413c61c692c9dd
|
[
"Apache-2.0"
] | null | null | null |
rules/gen/txt_to_cpp.cpp
|
hleclerc/nsmake
|
01c246311cb37d6d85776db87e413c61c692c9dd
|
[
"Apache-2.0"
] | null | null | null |
#include "Hpipe/Stream.h"
#include <iostream>
#include <fstream>
using namespace std;
int usage( const char *prg, const char *msg, int res ) {
if ( msg )
std::cerr << msg << std::endl;
std::cerr << "Usage:" << std::endl;
std::cerr << " " << prg << " cpp_var_name input_file" << std::endl;
return res;
}
int main( int argc, char **argv ) {
if ( argc != 3 )
return usage( argv[ 0 ], "nb args", 1 );
// std::ofstream fo( argv[ 1 ] );
std::ifstream fi( argv[ 1 ] );
if ( ! fi ) {
std::cerr << "Impossible to open file '" << argv[ 1 ] << "'" << std::endl;
return 2;
}
std::cout << "char " << argv[ 2 ] << "[] = {";
for( int i = 0; ; ++i ) {
char c = fi.get();
if ( fi.eof() )
c = 0;
if ( i )
std::cout << ", ";
if ( i % 16 == 0 )
std::cout << "\n ";
std::cout << (int)c;
if ( fi.eof() ) {
if ( i )
std::cout << "\n";
break;
}
}
std::cout << "};\n";
return 0;
}
| 23.608696
| 82
| 0.411602
|
hleclerc
|
c7633337f43003899682b90cd4316ad6daca03c4
| 1,086
|
cpp
|
C++
|
1144/f.cpp
|
vladshablinsky/algo
|
815392708d00dc8d3159b4866599de64fa9d34fa
|
[
"MIT"
] | 1
|
2021-10-24T00:46:37.000Z
|
2021-10-24T00:46:37.000Z
|
1144/f.cpp
|
vladshablinsky/algo
|
815392708d00dc8d3159b4866599de64fa9d34fa
|
[
"MIT"
] | null | null | null |
1144/f.cpp
|
vladshablinsky/algo
|
815392708d00dc8d3159b4866599de64fa9d34fa
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <vector>
#include <tuple>
using namespace std;
const int MAXN = 200005;
int color[MAXN];
vector<int> g[MAXN];
vector<pair<int, int>> edges;
void dfs(int v, int p, bool &possible) {
if (!possible) {
return;
}
color[v] = color[p] + 1;
color[v] -= 2 * (color[v] > 2);
for (auto to: g[v]) {
if (to != p) {
if (color[to] == color[v]) {
possible = false;
return;
} else if (!color[to]) {
dfs(to, v, possible);
}
}
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
bool possible = true;
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d %d", &u, &v);
--u; --v;
g[u].push_back(v);
g[v].push_back(u);
edges.push_back({u, v});
}
dfs(0, 0, possible);
if (!possible) {
printf("NO\n");
} else {
printf("YES\n");
for (auto &edge: edges) {
int u, v;
std::tie(u, v) = edge;
if (color[u] < color[v]) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
return 0;
}
| 16.208955
| 40
| 0.470534
|
vladshablinsky
|
c7636f874fafc3092c263ec4a4953b8f1f445cfd
| 2,877
|
cpp
|
C++
|
utils/Window.cpp
|
jensmcatanho/directx-playground
|
3611343a47ab67025e2ea79337c8dde81760d7b8
|
[
"MIT"
] | null | null | null |
utils/Window.cpp
|
jensmcatanho/directx-playground
|
3611343a47ab67025e2ea79337c8dde81760d7b8
|
[
"MIT"
] | null | null | null |
utils/Window.cpp
|
jensmcatanho/directx-playground
|
3611343a47ab67025e2ea79337c8dde81760d7b8
|
[
"MIT"
] | null | null | null |
/*
-----------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2018 Jean Michel Catanho
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 "utils/Window.h"
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
namespace utils {
Window::Window() {
WNDCLASSEX windowClass;
ZeroMemory(&windowClass, sizeof(WNDCLASSEX));
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = GetModuleHandle(NULL);
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.lpszClassName = "WindowClass1";
RegisterClassEx(&windowClass);
}
Window::~Window() {
Release();
}
DWORD Window::Create(std::string title, int screenWidth, int screenHeight) {
RECT clientRect = { 0, 0, screenWidth, screenHeight };
AdjustWindowRect(&clientRect, WS_OVERLAPPEDWINDOW, FALSE);
int width = clientRect.right - clientRect.left;
int height = clientRect.bottom - clientRect.top;
int xPos = (GetSystemMetrics(SM_CXSCREEN) - width) / 2;
int yPos = (GetSystemMetrics(SM_CYSCREEN) - height) / 2;
m_WindowHandler = CreateWindowEx(NULL, "WindowClass1", title.c_str(), WS_OVERLAPPEDWINDOW, xPos, yPos, width, height, NULL, NULL, GetModuleHandle(NULL), NULL);
if (m_WindowHandler == NULL) {
return GetLastError();
}
ShowWindow(m_WindowHandler, SW_SHOW);
return 0;
}
void Window::Release() {
if (IsWindow(m_WindowHandler)) {
if (!DestroyWindow(m_WindowHandler)) {
m_WindowHandler = NULL;
}
}
}
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
| 32.693182
| 160
| 0.719152
|
jensmcatanho
|
c76cff58a164cf3f068a00c8527048a0d819ffd5
| 2,757
|
cc
|
C++
|
src/rtc_audio_track_impl.cc
|
necnecnec/libwebrtc
|
220cc87ac678ff0675b16397f46a6a35ecd2ba9c
|
[
"MIT"
] | null | null | null |
src/rtc_audio_track_impl.cc
|
necnecnec/libwebrtc
|
220cc87ac678ff0675b16397f46a6a35ecd2ba9c
|
[
"MIT"
] | null | null | null |
src/rtc_audio_track_impl.cc
|
necnecnec/libwebrtc
|
220cc87ac678ff0675b16397f46a6a35ecd2ba9c
|
[
"MIT"
] | null | null | null |
#include "rtc_audio_track_impl.h"
namespace libwebrtc {
AudioTrackImpl::AudioTrackImpl(
rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track)
: rtc_track_(audio_track),_renderer(nullptr) {
RTC_LOG(INFO) << __FUNCTION__ << ": ctor ";
if(rtc_track_){
strncpy(id_, rtc_track_->id().c_str(), sizeof(id_));
strncpy(kind_, rtc_track_->kind().c_str(), sizeof(kind_));
rtc_track_->AddSink(this);
}
}
AudioTrackImpl::~AudioTrackImpl() {
if(rtc_track_)
rtc_track_->RemoveSink(this);
RTC_LOG(INFO) << __FUNCTION__ << ": dtor ";
}
// AudioTrackSinkInterface implementation.
void AudioTrackImpl:: OnData(const void* audio_data,
int bits_per_sample,
int sample_rate,
size_t number_of_channels,
size_t number_of_frames,
absl::optional<int64_t> absolute_capture_timestamp_ms){
if(_renderer){
_renderer->OnData( audio_data,
static_cast<int>( bits_per_sample),
static_cast<int>(sample_rate),
static_cast<int>(number_of_channels),
static_cast<int>(number_of_frames));
}
}
void AudioTrackImpl::OnRenderData(const void* audio_samples,
const size_t num_samples,
const size_t bytes_per_sample,
const size_t num_channels,
const uint32_t samples_per_sec){
// if(_renderer){
// _renderer->OnData( audio_samples,
// static_cast<int>( bytes_per_sample)*8,
// static_cast<int>(samples_per_sec),
// static_cast<int>(num_channels),
// static_cast<int>(num_samples));
// }
}
void AudioTrackImpl::OnCaptureData(const void* audio_samples,
const size_t nSamples,
const size_t nBytesPerSample,
const size_t nChannels,
const uint32_t samples_per_sec){
if(_renderer){
_renderer->OnData( audio_samples,
static_cast<int>( nSamples)*8,
static_cast<int>(nBytesPerSample),
static_cast<int>(nChannels),
static_cast<int>(samples_per_sec));
}
}
void AudioTrackImpl::AddRenderer(
RTCAudioRenderer* renderer) {
_renderer=renderer;
}
void AudioTrackImpl::RemoveRenderer(
RTCAudioRenderer* renderer) {
_renderer=nullptr;
}
} // namespace libwebrtc
| 34.4625
| 78
| 0.544432
|
necnecnec
|
c7713a701cf02015259eaccddf1a573248ecd771
| 8,548
|
cpp
|
C++
|
mpi_communication_partition/mpi_analysis.cpp
|
tudasc/CommPart
|
f5e6739d69d4ca8dd6528cb9657df398a9f0caa8
|
[
"Apache-2.0"
] | 3
|
2021-04-04T01:12:47.000Z
|
2021-06-07T14:27:45.000Z
|
mpi_communication_partition/mpi_analysis.cpp
|
tudasc/CommPart
|
f5e6739d69d4ca8dd6528cb9657df398a9f0caa8
|
[
"Apache-2.0"
] | null | null | null |
mpi_communication_partition/mpi_analysis.cpp
|
tudasc/CommPart
|
f5e6739d69d4ca8dd6528cb9657df398a9f0caa8
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2021 Tim Jammer
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 "mpi_analysis.h"
#include "mpi_functions.h"
#include "debug.h"
#include "helper.h"
#include "llvm/Analysis/CFG.h"
using namespace llvm;
bool is_waitall_matching(ConstantInt *begin_index, ConstantInt *match_index,
CallBase *call) {
assert(begin_index->getType() == match_index->getType());
assert(call->getCalledFunction() == mpi_func->mpi_waitall);
assert(call->getNumArgOperands() == 3);
//Debug(call->dump(); errs() << "Is this waitall matching?";);
if (auto *count = dyn_cast<ConstantInt>(call->getArgOperand(0))) {
auto begin = begin_index->getSExtValue();
auto match = match_index->getSExtValue();
auto num_req = count->getSExtValue();
if (begin + num_req > match && match >= begin) {
// proven, that this request is part of the requests waited for by the
// call
//Debug(errs() << " TRUE\n";);
return true;
}
}
// could not prove true
//Debug(errs() << " FALSE\n";);
return false;
}
std::vector<CallBase*> get_matching_waitall(AllocaInst *request_array,
ConstantInt *index) {
std::vector<CallBase*> result;
for (auto u : request_array->users()) {
if (auto *call = dyn_cast<CallBase>(u)) {
if (call->getCalledFunction() == mpi_func->mpi_wait
&& index->isZero()) {
// may use wait like this
result.push_back(call);
}
if (call->getCalledFunction() == mpi_func->mpi_waitall) {
if (is_waitall_matching(ConstantInt::get(index->getType(), 0),
index, call)) {
result.push_back(call);
}
}
} else if (auto *gep = dyn_cast<GetElementPtrInst>(u)) {
if (gep->getNumIndices() == 2 && gep->hasAllConstantIndices()) {
auto *index_it = gep->idx_begin();
ConstantInt *i0 = dyn_cast<ConstantInt>(&*index_it);
index_it++;
ConstantInt *index_in_array = dyn_cast<ConstantInt>(&*index_it);
if (i0->isZero()) {
for (auto u2 : gep->users()) {
if (auto *call = dyn_cast<CallBase>(u2)) {
if (call->getCalledFunction() == mpi_func->mpi_wait
&& index == index_in_array) {
// may use wait like this
result.push_back(call);
}
if (call->getCalledFunction()
== mpi_func->mpi_waitall) {
if (is_waitall_matching(index_in_array, index,
call)) {
result.push_back(call);
}
}
}
}
} // end if index0 == 0
} // end if gep has simple structure
}
}
return result;
}
std::vector<CallBase*> get_corresponding_wait(CallBase *call) {
// errs() << "Analyzing scope of \n";
// call->dump();
std::vector<CallBase*> result;
unsigned int req_arg_pos = 6;
if (call->getCalledFunction() == mpi_func->mpi_Ibarrier) {
assert(call->getNumArgOperands() == 2);
req_arg_pos = 1;
} else {
assert(
call->getCalledFunction() == mpi_func->mpi_Isend
|| call->getCalledFunction() == mpi_func->mpi_Ibsend
|| call->getCalledFunction() == mpi_func->mpi_Issend
|| call->getCalledFunction() == mpi_func->mpi_Irsend
|| call->getCalledFunction() == mpi_func->mpi_Irecv
|| call->getCalledFunction()
== mpi_func->mpi_Iallreduce);
assert(call->getNumArgOperands() == 7);
}
Value *req = call->getArgOperand(req_arg_pos);
// req->dump();
if (auto *alloc = dyn_cast<AllocaInst>(req)) {
for (auto *user : alloc->users()) {
if (auto *other_call = dyn_cast<CallBase>(user)) {
if (other_call->getCalledFunction() == mpi_func->mpi_wait) {
assert(other_call->getNumArgOperands() == 2);
assert(
other_call->getArgOperand(0) == req
&& "First arg of MPi wait is MPI_Request");
// found end of scope
// errs() << "possible ending of scope here \n";
// other_call->dump();
result.push_back(other_call);
}
}
}
}
// scope detection in basic waitall
// ofc at some point of pointer arithmetic, we cannot follow it
else if (auto *gep = dyn_cast<GetElementPtrInst>(req)) {
if (gep->isInBounds()) {
if (auto *req_array = dyn_cast<AllocaInst>(
gep->getPointerOperand())) {
if (gep->getNumIndices() == 2 && gep->hasAllConstantIndices()) {
auto *index_it = gep->idx_begin();
ConstantInt *i0 = dyn_cast<ConstantInt>(&*index_it);
index_it++;
ConstantInt *index_in_array = dyn_cast<ConstantInt>(
&*index_it);
if (i0->isZero()) {
auto temp = get_matching_waitall(req_array,
index_in_array);
result.insert(result.end(), temp.begin(), temp.end());
} // end it index0 == 0
} // end if gep has a simple structure
else {
// debug
Debug(gep->dump();
errs()
<< "This structure is currently too complicated to analyze";);
}
}
} else { // end if inbounds
gep->dump();
errs()
<< "Strange, out of bounds getelemptr instruction should not "
"happen in this case\n";
}
}
if (result.empty()) {
errs() << "could not determine scope of \n";
call->dump();
/*
errs() << "Assuming it will finish at mpi_finalize.\n"
<< "The Analysis result is still valid, although the chance of "
"false positives is higher\n";
*/
// our analysis need to treat it as a blocking op
result.push_back(call);
}
// mpi finalize will end all communication nontheles
for (auto *user : mpi_func->mpi_finalize->users()) {
if (auto *finalize_call = dyn_cast<CallBase>(user)) {
if (llvm::isPotentiallyReachable(call, finalize_call, nullptr,
analysis_results->getDomTree(call->getFunction()),
analysis_results->getLoopInfo(call->getFunction()))) {
result.push_back(finalize_call);
}
}
}
return result;
}
//returns the call where the operation is completed locally
// e.g. the corresponding wait ot the ooperation itself for blocking communication
Instruction* get_local_completion_point(CallBase *mpi_call) {
if (mpi_call->getCalledFunction() == mpi_func->mpi_Ibarrier
|| mpi_call->getCalledFunction() == mpi_func->mpi_Isend
|| mpi_call->getCalledFunction() == mpi_func->mpi_Ibsend
|| mpi_call->getCalledFunction() == mpi_func->mpi_Issend
|| mpi_call->getCalledFunction() == mpi_func->mpi_Irsend
|| mpi_call->getCalledFunction() == mpi_func->mpi_Irecv
|| mpi_call->getCalledFunction() == mpi_func->mpi_Iallreduce) {
auto possible_completion_points = get_corresponding_wait(mpi_call);
return get_first_instruction(possible_completion_points);
} else { // blocking operations
assert(
mpi_call->getCalledFunction() == mpi_func->mpi_send
|| mpi_call->getCalledFunction() == mpi_func->mpi_recv);
return mpi_call;
}
}
//TODO if A overlaps B, B overlaps A -> caching the results might be possible to not build the result again and again
// maybe even an own analysis pass?
// returns operations that may locally overlap (will not include self)
std::vector<CallBase*> find_overlapping_operations(CallBase *mpi_call) {
std::vector<CallBase*> result;
auto *completion_point = get_local_completion_point(mpi_call);
for (auto *mpi_function : mpi_func->get_used_send_and_recv_functions()) {
for (auto *u : mpi_function->users()) {
if (auto *other_call = dyn_cast<CallBase>(u)) {
assert(other_call->getCalledFunction() == mpi_function);
auto *other_completion_point = get_local_completion_point(
other_call);
if (other_completion_point
== get_first_instruction(other_completion_point,
mpi_call)
|| completion_point
== get_first_instruction(completion_point,
other_call)) {
// if one is finished before the other: no overlap
} else {
// if it is in between
if (nullptr
!= get_first_instruction(other_completion_point,
mpi_call)
|| nullptr
!= get_first_instruction(completion_point,
other_call)) {
// if there is another defined order:
// overlapping
result.push_back(other_call);
} else {
// no defined order: can not prove overlapping
}
}
}
}
}
//TODO this dopes not capture the calls that start before the
return result;
}
| 30.528571
| 117
| 0.662962
|
tudasc
|
c773a26acdf8a1ac1ba5af48ff7657f56e8fa0e6
| 14,785
|
cpp
|
C++
|
src/genlib/util/gmtdate.cpp
|
xiyusullos/upnpsdk
|
a1e280530338220a91668e6e6f2f07ccbc0c1382
|
[
"BSD-3-Clause"
] | null | null | null |
src/genlib/util/gmtdate.cpp
|
xiyusullos/upnpsdk
|
a1e280530338220a91668e6e6f2f07ccbc0c1382
|
[
"BSD-3-Clause"
] | null | null | null |
src/genlib/util/gmtdate.cpp
|
xiyusullos/upnpsdk
|
a1e280530338220a91668e6e6f2f07ccbc0c1382
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000 Intel Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither name of Intel Corporation nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 INTEL 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.
//
///////////////////////////////////////////////////////////////////////////
// $Revision: 1.1.1.3 $
// $Date: 2001/06/15 00:22:16 $
// gmtdate.cc
#include "../../inc/tools/config.h"
#ifdef INTERNAL_WEB_SERVER
#if EXCLUDE_WEB_SERVER == 0
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <values.h>
#include <genlib/util/gmtdate.h>
#include <genlib/util/miscexceptions.h>
static char g_Days[7][4] =
{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
static char* g_Invalid = "INV";
static char g_Months[12][4] =
{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };
struct NameInfo
{
char* name;
int length;
};
#define NUM_MONTHS 12
static NameInfo MonthTable[NUM_MONTHS] =
{
{ "January", 7 },
{ "February", 8 },
{ "March", 5 },
{ "April", 5 },
{ "May", 3 },
{ "June", 4 },
{ "July", 4 },
{ "August", 6 },
{ "September", 9 },
{ "October", 7 },
{ "November", 8 },
{ "December", 8 },
};
#define NUM_DAYSPERWEEK 7
static NameInfo DayOfWeekTable[NUM_DAYSPERWEEK] =
{
{ "Sunday", 6 },
{ "Monday", 6 },
{ "Tuesday", 7 },
{ "Wednesday", 9 },
{ "Thursday", 8 },
{ "Friday", 6 },
{ "Saturday", 8 },
};
static int SearchNameInfo( IN const char* name,
IN NameInfo* nameTable, IN int tableLen,
OUT int* charsRead, OUT int* fullLengthMatch )
{
int i;
NameInfo *info = NULL;
bool fullMatch = false;
int len = 0;
assert( nameTable != NULL );
assert( tableLen > 0 );
if ( name == NULL )
{
return -1;
}
try
{
for ( i = 0; i < tableLen; i++ )
{
info = &nameTable[i];
// try full match
if ( strncasecmp(name, info->name, info->length) == 0 )
{
throw 1; // 1: full match
}
if ( strncasecmp(name, info->name, 3) == 0 )
{
throw 2; // 2: partial match
}
}
throw -1; // no match
}
catch ( int code )
{
switch ( code )
{
case 1: // full match
len = info->length;
fullMatch = true;
break;
case 2: // partial match
len = 3;
fullMatch = false;
break;
case -1: // no match
i = -1;
break;
}
if ( code > 0 )
{
if ( fullLengthMatch != NULL )
{
*fullLengthMatch = (fullMatch == true);
}
if ( charsRead != NULL )
{
*charsRead = len;
}
}
}
assert( (i == -1) || (i >= 0 && i < tableLen) );
return i;
}
// input: monthStr: 3-letter or full month
// returns month=0..11 or -1 on failure
// output:
// charsRead - num chars that match the month
// fullNameMatch - full name match(1) or 3-letter match(0)
//
int ParseMonth( IN const char* monthStr,
OUT int* charsRead, OUT int* fullNameMatch )
{
return SearchNameInfo( monthStr, MonthTable, NUM_MONTHS,
charsRead, fullNameMatch );
}
// input: dayOfWeek: 3-letter or full day of week ("mon" etc)
// returns dayOfWeek=0..6 or -1 on failure
// output:
// charsRead - num chars that match the month
// fullNameMatch - full name match(1) or 3-letter match(0)
//
int ParseDayOfWeek( IN const char* dayOfWeek,
OUT int* charsRead, OUT int* fullNameMatch )
{
return SearchNameInfo( dayOfWeek, DayOfWeekTable,
NUM_DAYSPERWEEK, charsRead, fullNameMatch );
}
const char* GetDayOfWeekStr( int day )
{
if ( day >= 0 && day <= 6 )
{
return g_Days[ day ];
}
else
{
return g_Invalid;
}
}
const char* GetMonthStr( unsigned month )
{
if ( month >= 0 && month <= 11 )
{
return g_Months[ month ];
}
else
{
return g_Invalid;
}
}
// converts date to string format: RFC 1123 format:
// Sun, 06 Nov 1994 08:49:37 GMT
// String returned must be freed using free() function
// returns NULL if date is NULL
char* DateToString( const struct tm* date )
{
if ( date == NULL )
return NULL;
// max year supported = 2^32 = 4294967295 = 10 digits
const int DATESTRLEN = 35 + 1;
char *s;
s = (char *)malloc( DATESTRLEN );
if ( s == NULL )
{
throw OutOfMemoryException( "DateToString()" );
}
sprintf( s, "%s, %02d %s %d %02d:%02d:%02d GMT",
GetDayOfWeekStr(date->tm_wday), date->tm_mday,
GetMonthStr(date->tm_mon), date->tm_year + 1900,
date->tm_hour, date->tm_min, date->tm_sec );
return s;
}
// returns -1 if invalid num, or -ve num
static int ReadStrNum( IN const char* str, OUT int* numCharsRead )
{
int val;
char *endptr;
val = (int)strtol( str, &endptr, 10 );
if ( val < 0 || val == MAXINT )
{
return -1;
}
*numCharsRead = endptr - str;
if ( *numCharsRead == 0 )
{
return -1;
}
return val;
}
enum
{
DATIME_SPACE,
DATIME_COMMA,
DATIME_DASH,
DATIME_WDAY,
DATIME_FULLWDAY,
DATIME_DAY,
DATIME_MONTH,
DATIME_YEAR,
DATIME_YEAR2DIGIT,
DATIME_TIME,
DATIME_GMT
};
// parse: DIGIT DIGIT
// returns -1 on error, 0..99 on success
static int ParseTwoDigits( const char* s )
{
char numStr[3];
char* endptr;
for ( int i = 0; i < 2; i++ )
{
if ( !isdigit(numStr[i] = s[i]) )
{
return -1;
}
}
numStr[2] = 0;
return strtol( s, &endptr, 10 );
}
// parses time in fmt hh:mm:ss, military fmt
// returns 0 on success; -1 on error
int ParseTime( const char* s, int* hour, int* minute, int* second )
{
int h, m, sec;
// hour
h = ParseTwoDigits( s );
if ( !(h >= 0 && h <= 23) )
{
return -1;
}
if ( s[2] != ':' )
{
return -1;
}
// min
m = ParseTwoDigits( s + 3 );
if ( !(m >= 0 && m <= 59) )
{
return -1;
}
if ( s[5] != ':' )
{
return -1;
}
// sec
sec = ParseTwoDigits( s + 6 );
if ( !(sec >= 0 && sec <= 60) )
{
return -1;
}
*hour = h;
*minute = m;
*second = sec;
return 0;
}
static int ParseDatePattern( char* pattern, int length,
const char *s,
struct tm* dateTime, int* numCharsParsed )
{
int i;
int charsParsed;
int fullNameMatch;
const char* saveS = s;
int spaceCount;
// skip white space
while ( *s == ' ' || *s == '\t' )
{
s++;
}
for ( i = 0; i < length; i++ )
{
switch (pattern[i])
{
case DATIME_SPACE:
{
// multiple spaces
spaceCount = 0;
while ( *s == ' ' )
{
s++;
spaceCount++;
}
if ( spaceCount == 0 )
{
return -1;
}
break;
}
case DATIME_COMMA:
{
if ( *s++ != ',' )
{
return -1;
}
break;
}
case DATIME_DASH:
{
if ( *s++ != '-' )
{
return -1;
}
break;
}
case DATIME_WDAY:
case DATIME_FULLWDAY:
{
dateTime->tm_wday = ParseDayOfWeek( s, &charsParsed,
&fullNameMatch );
if ( (dateTime->tm_wday == -1) ||
(pattern[i] == DATIME_WDAY && fullNameMatch) ||
(pattern[i] == DATIME_FULLWDAY && !fullNameMatch)
)
{
return -1;
}
s += charsParsed; // point to next char
break;
}
case DATIME_DAY:
{
int mday;
mday = ReadStrNum( s, &charsParsed );
if ( mday <= 0 || mday > 31 )
{
return -1;
}
dateTime->tm_mday = mday;
s += charsParsed;
break;
}
case DATIME_MONTH:
{
int mon;
mon = ParseMonth( s, &charsParsed, &fullNameMatch );
if ( mon < 0 || (fullNameMatch && mon != 4) )
{
return -1;
}
dateTime->tm_mon = mon;
s += charsParsed;
break;
}
case DATIME_YEAR:
case DATIME_YEAR2DIGIT:
{
int year;
year = ReadStrNum( s, &charsParsed );
if ( pattern[i] == DATIME_YEAR )
{
year -= 1900;
if ( year < 0 )
return -1;
}
else if ( year < 0 || year > 99 )
{
// only 2-digit year allowed
return -1;
}
dateTime->tm_year = year;
s += charsParsed;
break;
}
case DATIME_TIME:
{
if ( ParseTime(s, &dateTime->tm_hour, &dateTime->tm_min,
&dateTime->tm_sec) == -1 )
{
return -1;
}
s += 8; // 8 chars for hh:mm:ss
break;
}
case DATIME_GMT:
{
if ( *s++ != 'G' )
return -1;
if ( *s++ != 'M' )
return -1;
if ( *s++ != 'T' )
return -1;
break;
}
}
}
if ( numCharsParsed != NULL )
{
*numCharsParsed = s - saveS;
}
return 0; // success
}
int ParseRFC850DateTime( IN const char* str,
OUT struct tm* dateTime, OUT int* numCharsParsed )
{
static char pattern[] =
{ DATIME_FULLWDAY, DATIME_COMMA, DATIME_SPACE,
DATIME_DAY, DATIME_DASH,
DATIME_MONTH, DATIME_DASH,
DATIME_YEAR2DIGIT, DATIME_SPACE,
DATIME_TIME, DATIME_SPACE,
DATIME_GMT
};
assert( dateTime != NULL );
if ( str == NULL )
{
return -1;
}
return ParseDatePattern( pattern, sizeof(pattern), str,
dateTime, numCharsParsed );
}
int ParseRFC1123DateTime( IN const char* str,
OUT struct tm* dateTime, OUT int* numCharsParsed )
{
static char pattern[] =
{ DATIME_WDAY, DATIME_COMMA, DATIME_SPACE,
DATIME_DAY, DATIME_SPACE,
DATIME_MONTH, DATIME_SPACE,
DATIME_YEAR, DATIME_SPACE,
DATIME_TIME, DATIME_SPACE,
DATIME_GMT };
assert( dateTime != NULL );
if ( str == NULL )
{
return -1;
}
return ParseDatePattern( pattern, sizeof(pattern), str,
dateTime, numCharsParsed );
}
int ParseAsctimeFmt( IN const char* str,
OUT struct tm* dateTime, OUT int* numCharsParsed )
{
static char pattern[] =
{ DATIME_WDAY, DATIME_SPACE,
DATIME_MONTH, DATIME_SPACE,
DATIME_DAY, DATIME_SPACE,
DATIME_TIME, DATIME_SPACE,
DATIME_YEAR
};
assert( dateTime != NULL );
if ( str == NULL )
{
return -1;
}
return ParseDatePattern( pattern, sizeof(pattern), str,
dateTime, numCharsParsed );
}
int ParseDateTime( IN const char* str, OUT struct tm* dateTime,
int *numCharsParsed )
{
assert( dateTime != NULL );
if ( str == NULL )
{
return -1;
}
const char* s = str;
int charsParsed;
int fullNameMatch;
int wday;
// get week day
wday = ParseDayOfWeek( s, &charsParsed, &fullNameMatch );
if ( wday == -1 )
{
return -1;
}
s += charsParsed; // point to next char
if ( fullNameMatch )
{
// 850 fmt
return ParseRFC850DateTime( str, dateTime, numCharsParsed );
}
else
{
if ( *s == ',' )
{
// 1123 format
return ParseRFC1123DateTime( str, dateTime, numCharsParsed );
}
else if ( *s == ' ' )
{
// asctime() fmt
return ParseAsctimeFmt( str, dateTime, numCharsParsed );
}
else
{
return -1;
}
}
}
#endif
#endif
| 23.923948
| 78
| 0.473115
|
xiyusullos
|
c773cab98a04d4ec89cf473d13a51c3c94a504bb
| 989
|
cpp
|
C++
|
415.cpp
|
Alex-Amber/LeetCode
|
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
|
[
"MIT"
] | null | null | null |
415.cpp
|
Alex-Amber/LeetCode
|
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
|
[
"MIT"
] | null | null | null |
415.cpp
|
Alex-Amber/LeetCode
|
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size(), n2 = num2.size();
string& res = n1 > n2 ? num1 : num2;
int n_res = max(n1, n2);
int d = 1;
int sum, carry = 0;
while (d <= n_res) {
if (n1 - d < 0) {
sum = (int)(num2[n2 - d] - '0') + carry;
carry = sum / 10;
res[n_res - d] = (sum % 10) + '0';
}
else if (n2 - d < 0) {
sum = (int)(num1[n1 - d] - '0') + carry;
carry = sum / 10;
res[n_res - d] = (sum % 10) + '0';
}
else {
sum = (int)(num1[n1 -d] - '0') + (int)(num2[n2 - d] - '0') + carry;
carry = sum / 10;
res[n_res - d] = (sum % 10) + '0';
}
d++;
}
if (carry)
res.insert(res.begin(), (char)(carry + '0'));
return res;
}
};
| 30.90625
| 83
| 0.352882
|
Alex-Amber
|
c7774acc26ee69cd68346806e0b3051d0f1e8f67
| 2,365
|
cc
|
C++
|
modules/kernel/src/heap/HeapMergeRight.cc
|
eryjus/century-os
|
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
|
[
"BSD-3-Clause"
] | 12
|
2018-12-03T15:16:52.000Z
|
2022-03-16T21:07:13.000Z
|
modules/kernel/src/heap/HeapMergeRight.cc
|
eryjus/century-os
|
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
|
[
"BSD-3-Clause"
] | null | null | null |
modules/kernel/src/heap/HeapMergeRight.cc
|
eryjus/century-os
|
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
|
[
"BSD-3-Clause"
] | 2
|
2018-11-13T01:30:41.000Z
|
2021-08-12T18:22:26.000Z
|
//===================================================================================================================
//
// HeapMergeRight.cc -- Merge the freeing block with the block to the right if free as well
//
// Copyright (c) 2017-2020 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// Merge the freeing block with the block to the right if free as well
//
// ------------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2012-Jul-26 Initial version
// 2012-Sep-16 Leveraged from Century
// 2012-Sep-23 #90 Fixed issue with calc'ing the right footer
// 2013-Sep-12 #101 Resolve issues splint exposes
// 2013-Sep-13 #74 Rewrite Debug.h to use assertions and write to TTY_LOG
// 2018-Sep-01 Initial 0.1.0 ADCL Copy this file from century32 to century-os
// 2019-Feb-08 Initial 0.3.0 ADCL Relocated
//
//===================================================================================================================
#include "types.h"
#include "heap.h"
//
// -- Merge a new hole with the existing hols on the right side of this one in memory
// -------------------------------------------------------------------------------
OrderedList_t *HeapMergeRight(KHeapHeader_t *hdr)
{
KHeapFooter_t *rightFtr;
KHeapHeader_t *rightHdr;
if (!assert(hdr != NULL)) HeapError("Bad Header passed into HeapMergeRight()", "");
rightHdr = (KHeapHeader_t *)((byte_t *)hdr + hdr->size);
rightFtr = (KHeapFooter_t *)((byte_t *)rightHdr + rightHdr->size - sizeof(KHeapFooter_t));
if ((byte_t *)rightFtr + sizeof(KHeapFooter_t) > kHeap->endAddr) return 0;
HeapValidateHdr(rightHdr, "rightHeader in HeapMergeRight()");
if (!rightHdr->_magicUnion.isHole) return 0; // make sure the left block is a hole
HeapReleaseEntry(rightHdr->entry);
hdr->size += rightHdr->size;
rightFtr->hdr = hdr;
hdr->_magicUnion.isHole = rightFtr->_magicUnion.isHole = 1;
return HeapNewListEntry(hdr, 0);
}
| 43.796296
| 117
| 0.487104
|
eryjus
|
c77a2675fd08425e1ec08030da1a2e71a45bbaa0
| 5,264
|
cpp
|
C++
|
src/l_Message.cpp
|
benzap/Kampf
|
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
|
[
"Zlib"
] | 2
|
2018-05-13T05:27:29.000Z
|
2018-05-29T06:35:57.000Z
|
src/l_Message.cpp
|
benzap/Kampf
|
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
|
[
"Zlib"
] | null | null | null |
src/l_Message.cpp
|
benzap/Kampf
|
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
|
[
"Zlib"
] | null | null | null |
#include "l_Message.hpp"
Message* lua_pushmessage(lua_State *L, Message* message) {
if (message == nullptr) {
message = Messenger::getInstance()->appendMessage();
}
Message ** messagePtr = static_cast<Message**>
(lua_newuserdata(L, sizeof(Message*)));
*messagePtr = message;
luaL_getmetatable(L, LUA_USERDATA_MESSAGE);
lua_setmetatable(L, -2);
return message;
}
Message* lua_tomessage(lua_State *L, int index) {
Message* message = *static_cast<Message**>
(luaL_checkudata(L, index, LUA_USERDATA_MESSAGE));
if (message == NULL) {
luaL_error(L, "Provided userdata is not of type 'Message'");
}
return message;
}
boolType lua_ismessage(lua_State* L, int index) {
if (lua_isuserdata(L, index)) {
auto chk = lua_isUserdataType(L, index, LUA_USERDATA_MESSAGE);
return chk;
}
return false;
}
// static int l_Message_Message(lua_State *L) {
// auto message = lua_pushmessage(L);
// return 1;
// }
static int l_Message_isMessage(lua_State *L) {
if (lua_ismessage(L, -1)) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
static int l_Message_getID(lua_State *L) {
auto message = lua_tomessage(L, 1);
lua_pushnumber(L, message->getID());
return 1;
}
static int l_Message_getType(lua_State *L) {
auto message = lua_tomessage(L, 1);
enumMessageType messageType = message->getType();
lua_pushstring(L, message->getTypeString().c_str());
return 1;
}
static int l_Message_setType(lua_State *L) {
auto message = lua_tomessage(L, 1);
stringType type = luaL_checkstring(L, 2);
message->setTypeString(type);
return 0;
}
static int l_Message_getFirstEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->firstEntity != nullptr) {
lua_pushentity(L, message->firstEntity);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setFirstEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto entity = lua_toentity(L, 2);
message->firstEntity = entity;
return 0;
}
static int l_Message_getFirstComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->firstComponent != nullptr) {
lua_pushcomponent(L, message->firstComponent);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setFirstComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto component = lua_tocomponent(L, 2);
message->firstComponent = component;
return 0;
}
static int l_Message_getSecondEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->secondEntity != nullptr) {
lua_pushentity(L, message->secondEntity);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setSecondEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto entity = lua_toentity(L, 2);
message->secondEntity = entity;
return 0;
}
static int l_Message_getSecondComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->secondComponent != nullptr) {
lua_pushcomponent(L, message->secondComponent);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setSecondComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto component = lua_tocomponent(L, 2);
message->secondComponent = component;
return 0;
}
static int l_Message_getCustomAttribute(lua_State *L) {
auto message = lua_tomessage(L, 1);
stringType keyname = luaL_checkstring(L, 2);
//todo, check if attribute exists
auto customAttribute = message->customData[keyname];
lua_pushcustomAttribute(L, new CustomAttribute(customAttribute));
return 1;
}
static int l_Message_setCustomAttribute(lua_State *L) {
auto message = lua_tomessage(L, 1);
stringType keyname = luaL_checkstring(L, 2);
auto customAttribute = lua_tocustomAttribute(L, 3);
message->customData[keyname] = customAttribute;
return 0;
}
static const struct luaL_Reg l_Message_registry [] = {
//{"Message", l_Message_Message},
{"isMessage", l_Message_isMessage},
{NULL, NULL}
};
static const struct luaL_Reg l_Message [] = {
{"getID", l_Message_getID},
{"getType", l_Message_getType},
{"setType", l_Message_setType},
{"getFirstEntity", l_Message_getFirstEntity},
{"setFirstEntity", l_Message_setFirstEntity},
{"getFirstComponent", l_Message_getFirstComponent},
{"setFirstComponent", l_Message_setFirstComponent},
{"getSecondEntity", l_Message_getSecondEntity},
{"setSecondEntity", l_Message_setSecondEntity},
{"getSecondComponent", l_Message_getSecondComponent},
{"setSecondComponent", l_Message_setSecondComponent},
{"getCustomAttribute", l_Message_getCustomAttribute},
{"get", l_Message_getCustomAttribute},
{"setCustomAttribute", l_Message_setCustomAttribute},
{"set", l_Message_setCustomAttribute},
{NULL, NULL}
};
int luaopen_message(lua_State *L) {
luaL_newmetatable(L, LUA_USERDATA_MESSAGE);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, l_Message);
lua_pop(L, 1);
luaL_register(L, KF_LUA_LIBNAME, l_Message_registry);
return 1;
}
| 26.059406
| 69
| 0.68807
|
benzap
|
c781a264b8c9f44ea27c91ae2e2cea265d325a26
| 593
|
cpp
|
C++
|
a2.cpp
|
rene-d/singleton
|
21615b8a49b97289c499a2f3c639400ff9dfb60f
|
[
"Unlicense"
] | null | null | null |
a2.cpp
|
rene-d/singleton
|
21615b8a49b97289c499a2f3c639400ff9dfb60f
|
[
"Unlicense"
] | null | null | null |
a2.cpp
|
rene-d/singleton
|
21615b8a49b97289c499a2f3c639400ff9dfb60f
|
[
"Unlicense"
] | null | null | null |
// c'est le fichier embêtant...
// il contient un singleton qu'il faut à tout prix initialiser
#include "toto.h"
#include <iostream>
using namespace std;
extern int main_use; // déclaré dans z.cpp (exécutable)
extern int internal_use; // déclaré dans a1.cpp (ce module)
// la classe du singleton
class A
{
public:
A()
{
++main_use;
++internal_use;
cout << __FUNCTION__ << endl;
}
};
// le singleton pourri
static A a;
// une fonction quelconque
const char *a2()
{
return __FUNCTION__;
}
// une variable quelconque
int init_a2;
| 16.472222
| 66
| 0.639123
|
rene-d
|
c7828544598a63a600ca68615866fd1d4672f91d
| 734
|
cpp
|
C++
|
Leetcode Solution/HashMap/Medium/1487. Making File Names Unique.cpp
|
bilwa496/Placement-Preparation
|
bd32ee717f671d95c17f524ed28b0179e0feb044
|
[
"MIT"
] | 169
|
2021-05-30T10:02:19.000Z
|
2022-03-27T18:09:32.000Z
|
Leetcode Solution/HashMap/Medium/1487. Making File Names Unique.cpp
|
bilwa496/Placement-Preparation
|
bd32ee717f671d95c17f524ed28b0179e0feb044
|
[
"MIT"
] | 1
|
2021-10-02T14:46:26.000Z
|
2021-10-02T14:46:26.000Z
|
Leetcode Solution/HashMap/Medium/1487. Making File Names Unique.cpp
|
bilwa496/Placement-Preparation
|
bd32ee717f671d95c17f524ed28b0179e0feb044
|
[
"MIT"
] | 44
|
2021-05-30T19:56:29.000Z
|
2022-03-17T14:49:00.000Z
|
class Solution {
public:
vector<string> getFolderNames(vector<string>& names) {
unordered_map<string,int> mp;
vector<string> ans;
int j;
for(int i=0;i<names.size();i++)
{
j = mp[names[i]];
string temp = names[i];
while(mp[temp]>0)
{
temp = names[i] + '(' + to_string(j++) + ')' ;
mp[names[i]] = j;
}
ans.push_back(temp);
mp[temp]++;
}
return ans;
}
};
| 25.310345
| 82
| 0.30109
|
bilwa496
|
c783d231aa59021045a62d029399844437262bc2
| 157
|
hpp
|
C++
|
basics/maxdecltypedecay.hpp
|
hanlulugeren/C-templates
|
17181f1e99207430236623e70504b4aecd40afe9
|
[
"MIT"
] | null | null | null |
basics/maxdecltypedecay.hpp
|
hanlulugeren/C-templates
|
17181f1e99207430236623e70504b4aecd40afe9
|
[
"MIT"
] | null | null | null |
basics/maxdecltypedecay.hpp
|
hanlulugeren/C-templates
|
17181f1e99207430236623e70504b4aecd40afe9
|
[
"MIT"
] | null | null | null |
#include<type_traits>
template<typename T1,typename T2>
auto max(T1 a,T2 b) -> typename std::decay< decltype(true ? a:b)>::type
{
return b < a ? a :b;
}
| 22.428571
| 71
| 0.656051
|
hanlulugeren
|
c788705efdbde2f2cec2993a22c8449d8b0573c9
| 12,737
|
cpp
|
C++
|
QuadtreeCollision/main.cpp
|
kgomathi2910/Quad-Trees
|
70059b66a93a9491f435c99d2cd811e0e0df3337
|
[
"MIT"
] | null | null | null |
QuadtreeCollision/main.cpp
|
kgomathi2910/Quad-Trees
|
70059b66a93a9491f435c99d2cd811e0e0df3337
|
[
"MIT"
] | null | null | null |
QuadtreeCollision/main.cpp
|
kgomathi2910/Quad-Trees
|
70059b66a93a9491f435c99d2cd811e0e0df3337
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<math.h>
#include<sstream>
#include<string>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
#define SCREEN_W 600
#define SCREEN_H 600
#define LEVEL_MAX 4
#define CAPACITY 5 //efficiency changes with capacity
#define PI 3.14159265
#define SPEED 0.5f
string intToString(int num)
{
static stringstream toStringConverter;
static string tempString;
toStringConverter.clear();
toStringConverter << num;
toStringConverter >> tempString;
//take num and convert it to string and store in tempString
return tempString;
}
class Rectangle
{
public:
float x;
float y;
float w;
float h;
Rectangle(float x, float y, float w, float h)
{
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
bool intersects(const Rectangle &other) const
{
return !(x - w > other.x + other.w || x + w < other.x - other.w || y - h > other.y + other.h || y + h < other.y - other.h);
}
void draw(RenderTarget &t)
{
static Vertex vertices[5];
vertices[0] = Vertex(Vector2f(x - w, y - h), Color::Magenta);
vertices[1] = Vertex(Vector2f(x + w, y - h), Color::Magenta);
vertices[2] = Vertex(Vector2f(x - w, y + h), Color::Magenta);
vertices[3] = Vertex(Vector2f(x + w, y + h), Color::Magenta);
vertices[4] = Vertex(Vector2f(x - w, y - h), Color::Magenta);
t.draw(vertices, 5, LineStrip);
}
};
class Entity : public Rectangle
{
public:
bool collides;
float angle;
Entity(float x, float y, float w, float h) : Rectangle(x, y, w, h)
{
collides = false;
angle = 0;
}
void Move()
{
x += cos(angle / 180 * PI) * SPEED;
y += sin(angle / 180 * PI) * SPEED;
if(x < w)
{
x = w;
angle = 180 - angle;
angle += rand() % 21 - 10;
}
else if(x > SCREEN_W - w)
{
x = SCREEN_W - w;
angle = 180 - angle;
angle += rand() % 21 - 10;
}
if(y < h)
{
y = h;
angle = -angle;
angle += rand() % 21 - 10;
}
else if(y > SCREEN_H - h)
{
y = SCREEN_H - h;
angle = -angle;
angle += rand() % 21 - 10;
}
}
};
class QuadTree {
private:
QuadTree *NorthWest;
QuadTree *NorthEast;
QuadTree *SouthWest;
QuadTree *SouthEast;
Rectangle boundaries;
bool divided;
size_t capacity;
size_t level;
vector<Entity*> children;
void subdivide()
{
static Vector2f halfSize;
halfSize.x = boundaries.w / 2.0f;
halfSize.y = boundaries.h / 2.0f;
NorthWest = new QuadTree(Rectangle(boundaries.x - halfSize.x, boundaries.y - halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
NorthEast = new QuadTree(Rectangle(boundaries.x + halfSize.x, boundaries.y - halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
SouthWest = new QuadTree(Rectangle(boundaries.x - halfSize.x, boundaries.y + halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
SouthEast = new QuadTree(Rectangle(boundaries.x + halfSize.x, boundaries.y + halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
divided = true;
}
public:
QuadTree(const Rectangle &_boundaries, size_t capacity, size_t level) : boundaries(_boundaries)
{
NorthWest = NULL;
NorthEast = NULL;
SouthWest = NULL;
SouthEast = NULL;
divided = false;
this->capacity = capacity;
this->level = level;
if(this->level >= LEVEL_MAX)
{
this->capacity = 0;
}
}
~QuadTree()
{
if(divided)
{
delete NorthWest;
delete NorthEast;
delete SouthWest;
delete SouthEast;
}
}
void query(const Rectangle &area, vector<Entity*> &found) const
{
if(!area.intersects(boundaries))
{
return;
}
if(divided)
{
NorthWest->query(area, found);
NorthEast->query(area, found);
SouthWest->query(area, found);
SouthEast->query(area, found);
}
else
{
for(size_t i = 0; i < children.size(); ++i)
{
if(area.intersects(*children[i]))
{
found.push_back(children[i]);
}
}
}
}
void insert(Entity *e)
{
if(!boundaries.intersects(*e))
{
return;
}
if(!divided)
{
children.push_back(e);
if(children.size() > capacity && capacity != 0 )
{
subdivide();
vector<Entity*>::iterator it = children.begin();
while(it != children.end())
{
NorthWest->insert(*it);
NorthEast->insert(*it);
SouthWest->insert(*it);
SouthEast->insert(*it);
it = children.erase(it);
}
}
}
else
{
NorthWest->insert(e);
NorthEast->insert(e);
SouthWest->insert(e);
SouthEast->insert(e);
}
}
void draw(RenderTarget &t)
{
if(divided)
{
static Vertex vertices[4];
vertices[0] = Vertex(Vector2f(boundaries.x, boundaries.y - boundaries.h), Color::White);
vertices[1] = Vertex(Vector2f(boundaries.x, boundaries.y + boundaries.h), Color::White);
vertices[2] = Vertex(Vector2f(boundaries.x - boundaries.w, boundaries.y), Color::White);
vertices[3] = Vertex(Vector2f(boundaries.x + boundaries.w, boundaries.y), Color::White);
t.draw(vertices, 4, Lines);
NorthWest->draw(t);
NorthEast->draw(t);
SouthWest->draw(t);
SouthEast->draw(t);
}
}
size_t checkCollision()
{
size_t collisionCount = 0;
if(divided)
{
collisionCount += NorthWest->checkCollision();
collisionCount += NorthEast->checkCollision();
collisionCount += SouthWest->checkCollision();
collisionCount += SouthEast->checkCollision();
}
else
{
//check if 2 entities collide
for(vector<Entity*>::iterator i = children.begin(); i != children.end(); ++i)
{
for(vector<Entity*>::iterator j = i; j != children.end(); ++j)
{
if(i != j && (*i)->intersects(**j))
{
(*i)->collides = true;
(*j)->collides = true;
}
++collisionCount;
}
}
}
return collisionCount;
}
};
int main()
{
srand(time(0));
RenderWindow window(sf::VideoMode(SCREEN_W + 200, SCREEN_H), "Collision Plot Using Quad Trees");
QuadTree *tree;
Entity *entity;
vector<Entity*> entities;
vector<Entity*> found;
RectangleShape shape;
shape.setOutlineColor(Color::Blue);
int width = 5, height = 5;
float timeTree, timeBrute;
int countTree, countBrute;
Clock timer; //measures elapsed time
Font font; //loading and manipulating character fonts
font.loadFromFile("AlexBrush-Regular.ttf"); //downloaded AxelBrush
Text text;//for text - we need font
text.setFont(font);
text.setCharacterSize(20);
text.setColor(Color::Yellow);
while(window.isOpen())
{
Event e;
while(window.pollEvent(e))
{
if(e.type == Event::Closed)
{
window.close();
}
else if(e.type == Event::MouseButtonPressed && e.mouseButton.button == Mouse::Left)
{
for(int i = 0; i < 10; ++i)
{
entity = new Entity(Mouse::getPosition(window).x, Mouse::getPosition(window).y, width, height);
entity->angle = rand() % 360; //angle
entities.push_back(entity);
}
}
else if (e.type == Event::MouseWheelScrolled)
{
if(Keyboard::isKeyPressed(Keyboard::LShift))
{
width += e.mouseWheelScroll.delta * 5;
}
else
{
height += e.mouseWheelScroll.delta * 5;
}
}
}
tree = new QuadTree(Rectangle(SCREEN_W / 2, SCREEN_H / 2, SCREEN_W / 2, SCREEN_H / 2), CAPACITY, 0);
timeTree = 0;
for(vector<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it)
{
(*it)->Move();
(*it)->collides = false;
timer.restart();
tree->insert(*it);
timeTree += timer.restart().asMicroseconds();
}
countTree = tree->checkCollision();
timeTree += timer.restart().asMicroseconds();
countBrute = 0;
timer.restart();
for(vector<Entity*>::iterator i = entities.begin(); i != entities.end(); ++i)
{
for(vector<Entity*>::iterator j = i; j != entities.end(); ++j)
{
if(i != j && (*i)->intersects(**j))
{
(*j)->collides = true;
(*j)->collides = true;
}
++countBrute;
}
}
timeBrute = timer.restart().asMicroseconds();
window.clear();
shape.setOutlineThickness(-1);
for(Entity *e : entities)
{
shape.setPosition(e->x, e->y);
shape.setSize(Vector2f(e->w * 2, e->h * 2));
shape.setOrigin(e->w, e->h);
shape.setFillColor(e->collides?Color::Red:Color::Green);
window.draw(shape);
}
tree->draw(window);
shape.setOutlineThickness(0);
shape.setPosition(Mouse::getPosition(window).x, Mouse::getPosition(window).y);
shape.setSize(Vector2f(width * 2, height * 2));
shape.setOrigin(width, height);
shape.setFillColor(Color(255, 255, 0, 50));
window.draw(shape);
text.setString("Tree count: " + intToString(countTree) +
"\nBrute force count: " + intToString(countBrute) +
"\nTree time: " + intToString(timeTree) +
"\nBrute force time:" + intToString(timeBrute) +
"\nTree is " +
intToString(round(timeBrute / timeTree)) + "times faster");
text.setPosition(SCREEN_W + 10, 20);
window.draw(text);
window.display();
}
for(int i = 0; i < entities.size(); ++i)
{
delete entities[i];
}
delete tree;
return 0;
}
| 34.705722
| 151
| 0.437544
|
kgomathi2910
|
c78a0d53574181ae16ab39a3b8605730b2426cfa
| 4,768
|
cpp
|
C++
|
Source/ShooterGame/Weapons/ShooterWeapon_Melee.cpp
|
ugsgame/ShooterPrototype
|
48fbc5401f52bd6d0b7f5b9bda8399c929eab4b9
|
[
"Apache-2.0"
] | 1
|
2019-07-16T09:46:54.000Z
|
2019-07-16T09:46:54.000Z
|
Source/ShooterGame/Weapons/ShooterWeapon_Melee.cpp
|
ugsgame/ShooterPrototype
|
48fbc5401f52bd6d0b7f5b9bda8399c929eab4b9
|
[
"Apache-2.0"
] | null | null | null |
Source/ShooterGame/Weapons/ShooterWeapon_Melee.cpp
|
ugsgame/ShooterPrototype
|
48fbc5401f52bd6d0b7f5b9bda8399c929eab4b9
|
[
"Apache-2.0"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "ShooterGame.h"
#include "ShooterWeapon_Melee.h"
AShooterWeapon_Melee::AShooterWeapon_Melee(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
CollisionComp1P = ObjectInitializer.CreateDefaultSubobject<UCapsuleComponent>(this, "CapsuleComp1P");
CollisionComp1P->InitCapsuleSize(5.0f, 10.0f);
CollisionComp1P->AlwaysLoadOnClient = true;
CollisionComp1P->AlwaysLoadOnServer = true;
CollisionComp1P->bTraceComplexOnMove = true;
CollisionComp1P->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
CollisionComp1P->SetCollisionObjectType(COLLISION_WEAPON);
CollisionComp1P->SetCollisionResponseToAllChannels(ECR_Ignore);
CollisionComp1P->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap);
CollisionComp1P->SetupAttachment(GetMesh1P());
CollisionComp1P->OnComponentBeginOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapBegin);
CollisionComp1P->OnComponentEndOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapEnd);
CollisionComp3P = ObjectInitializer.CreateDefaultSubobject<UCapsuleComponent>(this, "CapsuleComp3P");
CollisionComp3P->InitCapsuleSize(5.0f, 10.0f);
CollisionComp3P->AlwaysLoadOnClient = true;
CollisionComp3P->AlwaysLoadOnServer = true;
CollisionComp3P->bTraceComplexOnMove = true;
CollisionComp3P->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
CollisionComp3P->SetCollisionObjectType(COLLISION_WEAPON);
CollisionComp3P->SetCollisionResponseToAllChannels(ECR_Ignore);
CollisionComp3P->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap);
CollisionComp3P->SetupAttachment(GetMesh3P());
CollisionComp3P->OnComponentBeginOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapBegin);
CollisionComp3P->OnComponentEndOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapEnd);
CollisionComp = CollisionComp1P;
bHitWithStartFire = true;
}
void AShooterWeapon_Melee::PostInitializeComponents()
{
Super::PostInitializeComponents();
CollisionComp1P->MoveIgnoreActors.Add(Instigator);
CollisionComp1P->MoveIgnoreActors.Add(this);
CollisionComp3P->MoveIgnoreActors.Add(Instigator);
CollisionComp3P->MoveIgnoreActors.Add(this);
this->ApplyWeaponConfig(MeleeWeaponData);
}
void AShooterWeapon_Melee::ApplyWeaponConfig(FMeleeWeaponData& Data)
{
Data.MeleeClass = AShooterWeapon_Melee::StaticClass();
}
void AShooterWeapon_Melee::OnImpact(const FHitResult& HitResult)
{
//TODO:Spawn effect
}
void AShooterWeapon_Melee::SetHitEnable(bool Enable)
{
if (Enable)
{
CollisionComp->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
}
else
{
CollisionComp->SetCollisionEnabled(ECollisionEnabled::NoCollision);
}
}
void AShooterWeapon_Melee::FireWeapon()
{
}
void AShooterWeapon_Melee::OnStartFire()
{
Super::OnStartFire();
if (bHitWithStartFire)
{
SetHitEnable(true);
}
}
void AShooterWeapon_Melee::OnStopFire()
{
Super::OnStopFire();
if (bHitWithStartFire)
{
SetHitEnable(false);
}
}
void AShooterWeapon_Melee::AttachMeshToPawn()
{
Super::AttachMeshToPawn();
CollisionComp1P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
CollisionComp3P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
if (MyPawn != NULL)
{
MyPawn->IsFirstPerson() ? CollisionComp = CollisionComp1P : CollisionComp = CollisionComp3P;
CollisionComp1P->MoveIgnoreActors.Add(MyPawn);
CollisionComp3P->MoveIgnoreActors.Add(MyPawn);
}
}
bool AShooterWeapon_Melee::ShouldDealDamage(AActor* TestActor) const
{
// if we're an actor on the server, or the actor's role is authoritative, we should register damage
if (TestActor)
{
if (GetNetMode() != NM_Client ||
TestActor->Role == ROLE_Authority ||
TestActor->GetTearOff())
{
return true;
}
}
return false;
}
void AShooterWeapon_Melee::DealDamage(const FHitResult& Impact)
{
FPointDamageEvent PointDmg;
PointDmg.DamageTypeClass = MeleeWeaponData.DamageType;
PointDmg.HitInfo = Impact;
PointDmg.Damage = MeleeWeaponData.MeleeDamage;
if (MyPawn)
{
Impact.GetActor()->TakeDamage(PointDmg.Damage, PointDmg, MyPawn->Controller, this);
this->OnImpact(Impact);
}
}
void AShooterWeapon_Melee::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
// Other Actor is the actor that triggered the event. Check that is not ourself.
if ((OtherActor != nullptr) && (OtherActor != this) && (OtherComp != nullptr))
{
//TODO:handle damage
if (ShouldDealDamage(OtherActor))
{
DealDamage(SweepResult);
}
}
}
void AShooterWeapon_Melee::OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
}
| 28.213018
| 200
| 0.79719
|
ugsgame
|
c78db1a32fb4d1c35d70ed2abda77ab9e691ed89
| 3,725
|
hpp
|
C++
|
src/poutreBase/poutreChronos.hpp
|
ThomasRetornaz/poutre
|
21717ce1da24515dd208f711d6e7c38095ba8ecf
|
[
"BSL-1.0"
] | null | null | null |
src/poutreBase/poutreChronos.hpp
|
ThomasRetornaz/poutre
|
21717ce1da24515dd208f711d6e7c38095ba8ecf
|
[
"BSL-1.0"
] | null | null | null |
src/poutreBase/poutreChronos.hpp
|
ThomasRetornaz/poutre
|
21717ce1da24515dd208f711d6e7c38095ba8ecf
|
[
"BSL-1.0"
] | null | null | null |
//==============================================================================
// Copyright (c) 2015 - Thomas Retornaz //
// thomas.retornaz@mines-paris.org //
// Distributed under the Boost Software License, Version 1.0. //
// See accompanying file LICENSE.txt or copy at //
// http://www.boost.org/LICENSE_1_0.txt //
//==============================================================================
#ifndef POUTRE_CHRONOS_HPP__
#define POUTRE_CHRONOS_HPP__
/**
* @file poutreChronos.hpp
* @author Thomas Retornaz
* @brief Define helper objects around std::chrono facilities
*
*
*/
#include <poutreBase/poutreBase.hpp>
#include <chrono>
#include <ctime>
#include <iostream>
#include <sstream>
namespace poutre
{
/**
* @addtogroup timer_group Timing facilities
* @ingroup poutre_base_group
*@{
*/
/**
* @brief Simple Timer class (wrapping std::chronos) with classical
* start,stop interface and serialisation capabilites
* @todo think about multi-threading
*/
class BASE_API Timer // see http://en.cppreference.com/w/cpp/chrono/c/clock
{
public:
using high_resolution_clock = std::chrono::high_resolution_clock;
using double_milliseconds = std::chrono::duration<double, std::milli>; // switch to other duration through
// template<rep,duration> ?
using timerep = double_milliseconds::rep; // todo use
// decltype(auto)
//! ctor
Timer(void);
//! dor
~Timer(void) POUTRE_NOEXCEPT;
//! Start the timing action
void Start() POUTRE_NOEXCEPT;
//! Stop the timing action
void Stop() POUTRE_NOEXCEPT;
//! Grab wall time accumulated in ms
const timerep GetCumulativeTime() const POUTRE_NOEXCEPT;
//! Grab wall mean time of iteration in ms
const timerep GetMeanTime() const POUTRE_NOEXCEPT;
//! Grab cpu time accumulated in ms
const timerep GetCumulativeCPUTime() const POUTRE_NOEXCEPT;
//! Grab wall mean time of iteration in ms
const timerep GetMeanCpuTime() const POUTRE_NOEXCEPT;
//! Grab number off triggered start
const std::size_t NbIter() const POUTRE_NOEXCEPT;
//! String serialization
const std::string to_str() const POUTRE_NOEXCEPT;
//! Reset the chrono
void Reset() POUTRE_NOEXCEPT;
private:
std::chrono::high_resolution_clock::time_point m_start; //! start wall time
timerep m_accu; //! accumulate wall time over all iteration
std::clock_t m_start_cputime; //! start cpu time
std::clock_t m_accu_cputime; //! accumulate cpu time
std::size_t m_nbiter; //! nb iteration
};
//! Timer stream serialization
BASE_API std::ostream &operator<<(std::ostream &os, Timer &timer);
/**
* @brief Scoped (RAII) timer, start and stop of embedded timer are automatically triggered
*
* @todo think about multi-threading
*/
class BASE_API ScopedTimer
{
private:
Timer &m_timer; //! Inner timer
public:
//! ctor
ScopedTimer(Timer &itimer);
//! dtor
~ScopedTimer(void);
};
} // namespace poutre
/**
//! @} doxygroup: timer_group
*/
#endif // POUTRE_CHRONOS_HPP__
| 32.391304
| 113
| 0.54255
|
ThomasRetornaz
|
c78e71eb1d401394d83cd4dcbfea3a706a3cd27c
| 637
|
cpp
|
C++
|
engine/core/Concurency/Task.cpp
|
TristanFish/SuperBongoEngine
|
3a6c67c0aa0c6b4f75e353690016b8f91d813717
|
[
"MIT"
] | null | null | null |
engine/core/Concurency/Task.cpp
|
TristanFish/SuperBongoEngine
|
3a6c67c0aa0c6b4f75e353690016b8f91d813717
|
[
"MIT"
] | null | null | null |
engine/core/Concurency/Task.cpp
|
TristanFish/SuperBongoEngine
|
3a6c67c0aa0c6b4f75e353690016b8f91d813717
|
[
"MIT"
] | null | null | null |
#include "Task.h"
#include "Thread.h"
Task::Task(): E_Priority(ETaskPriority::Low), E_TaskType(ETaskType::TT_GENERAL), B_HasBeenCompleted(false)
{
}
Task::Task(ETaskPriority newPriority, ETaskType newType) : E_Priority(newPriority), E_TaskType(newType), B_HasBeenCompleted(false)
{
}
Task::Task(std::shared_ptr<Task> copyTask) : E_Priority(copyTask->E_Priority),E_TaskType(ETaskType::TT_GENERAL), F_Function(copyTask->F_Function), B_HasBeenCompleted(false)
{
}
Task::~Task()
{
}
void Task::RunTask()
{
F_Function();
B_HasBeenCompleted = true;
}
void Task::SetTask(std::function<void()> newFunc)
{
F_Function = newFunc;
}
| 17.216216
| 172
| 0.739403
|
TristanFish
|
c794ca9c70a0d9ab1f63dc13ebc98459b81b8971
| 40,116
|
cpp
|
C++
|
src/plugins/assembly/gstpartassembly.cpp
|
AIoT-IST/EVA_Show-Case
|
14474d97c233b4740c8216ba6564454cd954129c
|
[
"MIT"
] | 4
|
2021-05-26T07:14:50.000Z
|
2022-01-10T00:15:32.000Z
|
src/plugins/assembly/gstpartassembly.cpp
|
maxpark/EVA_Show-Case
|
c21fdf7d81efaaf4b63b071eeaf8911791336058
|
[
"MIT"
] | 2
|
2021-06-07T16:00:14.000Z
|
2021-07-06T13:35:38.000Z
|
src/plugins/assembly/gstpartassembly.cpp
|
maxpark/EVA_Show-Case
|
c21fdf7d81efaaf4b63b071eeaf8911791336058
|
[
"MIT"
] | 3
|
2021-08-19T02:27:59.000Z
|
2022-01-10T07:40:22.000Z
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include "gstpartassembly.h"
#include <ctime>
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <vector>
#include "gstadmeta.h"
#include "utils.h"
#define NANO_SECOND 1000000000.0
GST_DEBUG_CATEGORY_STATIC (gst_partassembly_debug_category);
#define GST_CAT_DEFAULT gst_partassembly_debug_category
static void gst_partassembly_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec);
static void gst_partassembly_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec);
static void gst_partassembly_dispose (GObject * object);
static void gst_partassembly_finalize (GObject * object);
static void gst_partassembly_before_transform (GstBaseTransform * trans, GstBuffer * buffer);
static gboolean gst_partassembly_start (GstBaseTransform * trans);
static gboolean gst_partassembly_stop (GstBaseTransform * trans);
static gboolean gst_partassembly_set_info (GstVideoFilter * filter, GstCaps * incaps, GstVideoInfo * in_info, GstCaps * outcaps, GstVideoInfo * out_info);
static GstFlowReturn gst_partassembly_transform_frame_ip (GstVideoFilter * filter, GstVideoFrame * frame);
static void mapGstVideoFrame2OpenCVMat(Gstpartassembly *partassembly, GstVideoFrame *frame, GstMapInfo &info);
static void getDetectedBox(Gstpartassembly *partassembly, GstBuffer* buffer);
static int getPartIndexInBomList(Gstpartassembly *partassembly, const std::string& partName);
static bool twoSidesCheck(Gstpartassembly *partassembly, int partIndex, int eachSideExistNumber);
static void doAlgorithm(Gstpartassembly *partassembly, GstBuffer* buffer);
static void drawObjects(Gstpartassembly *partassembly);
static void drawStatus(Gstpartassembly *partassembly);
std::vector<bool> assemblyActionVector = {
false, // put 1 semi-product in container
false, // put 2 light-guide-cover in semi-finished-products(left and right)
false, // put 2 small-board-side-B in semi-finished-products(left and right)
false, // screw on 4 screws(2 on left, 2 on right)
false, // put wire on
false, // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
false}; // Complete
std::vector<double> processingTime = {
0, // put 1 semi-product in container
0, // put 2 light-guide-cover in semi-finished-products(left and right)
0, // put 2 small-board-side-B in semi-finished-products(left and right)
0, // screw on 4 screws(2 on left, 2 on right)
0, // put wire on
0, // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
0}; // Complete
std::vector<float> processingRegularTime = {
10, // put 1 semi-product in container
10, // put 2 light-guide-cover in semi-finished-products(left and right)
6, // put 2 small-board-side-B in semi-finished-products(left and right)
10, // screw on 4 screws(2 on left, 2 on right)
5, // put wire on
5, // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
5}; // Complete
std::vector<std::string> assemblyActionInfoVector = {
"semi-product in container", // put 1 semi-product in container
"2 light-guide-cover(left and right)", // put 2 light-guide-cover in semi-finished-products(left and right)
"2 small-board-side-B(left and right)", // put 2 small-board-side-B in semi-finished-products(left and right)
"screw on 4 screws(2 on left, 2 on right)", // screw on 4 screws(2 on left, 2 on right)
"put wire on", // put wire on
"final visual inspection", // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
"completion"}; // Complete
struct _GstpartassemblyPrivate
{
std::vector<std::string> bomList;
std::vector<Material*> bomMaterial;
int indexOfSemiProductContainer;
int indexOfSemiProduct;
int bestIndexObjectOfSemiProduct;
bool partsDisplay;
bool informationDisplay;
bool alert;
gchar* targetType;
gchar* alertType;
int resetSeconds;
};
enum
{
PROP_0,
PROP_TARGET_TYPE,
PROP_ALERT_TYPE,
PROP_PARTS_DISPLAY,
PROP_INFORMATION_DISPLAY,
PROP_RESET
};
#define DEBUG_INIT GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, "gstpartassembly", 0, "debug category for gstpartassembly element");
G_DEFINE_TYPE_WITH_CODE(Gstpartassembly, gst_partassembly, GST_TYPE_VIDEO_FILTER, G_ADD_PRIVATE(Gstpartassembly) DEBUG_INIT)
/* pad templates */
/* FIXME: add/remove formats you can handle */
#define VIDEO_SRC_CAPS \
GST_VIDEO_CAPS_MAKE("{ BGR }")
/* FIXME: add/remove formats you can handle */
#define VIDEO_SINK_CAPS \
GST_VIDEO_CAPS_MAKE("{ BGR }")
/* class initialization */
static void gst_partassembly_class_init (GstpartassemblyClass * klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GstBaseTransformClass *base_transform_class = GST_BASE_TRANSFORM_CLASS (klass);
GstVideoFilterClass *video_filter_class = GST_VIDEO_FILTER_CLASS (klass);
/* Setting up pads and setting metadata should be moved to
base_class_init if you intend to subclass this class. */
gst_element_class_add_pad_template (GST_ELEMENT_CLASS(klass),
gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
gst_caps_from_string (VIDEO_SRC_CAPS)));
gst_element_class_add_pad_template (GST_ELEMENT_CLASS(klass),
gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
gst_caps_from_string (VIDEO_SINK_CAPS)));
gst_element_class_set_static_metadata (GST_ELEMENT_CLASS(klass),
"Adlink part assembly video filter", "Filter/Video", "An ADLINK Part-Assembly demo video filter", "Dr. Paul Lin <paul.lin@adlinktech.com>");
gobject_class->set_property = gst_partassembly_set_property;
gobject_class->get_property = gst_partassembly_get_property;
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_TARGET_TYPE,
g_param_spec_string ("target-type", "Target-Type", "The target type name used in this element for processing.", "NONE"/*DEFAULT_TARGET_TYPE*/, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALERT_TYPE,
g_param_spec_string ("alert-type", "Alert-Type", "The alert type name represents the event occurred. Two alert types are offered:\n\t\t\t(1)\"idling\", which means OP is idling;\n\t\t\t(2)\"completed\", which means the assembly is completed.", "idling\0", (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PARTS_DISPLAY,
g_param_spec_boolean("parts-display", "Parts-display", "Show detected parts in frame.", TRUE, G_PARAM_READWRITE));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_INFORMATION_DISPLAY,
g_param_spec_boolean("information-display", "Information-display", "Show the assembly process status.", TRUE, G_PARAM_READWRITE));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_RESET,
g_param_spec_int("reset-time", "reset counting duration time", "Reset the counting time every defined seconds when only checking assembly.", 0, 100, 25, G_PARAM_READWRITE));
gobject_class->dispose = gst_partassembly_dispose;
gobject_class->finalize = gst_partassembly_finalize;
base_transform_class->before_transform = GST_DEBUG_FUNCPTR(gst_partassembly_before_transform);
base_transform_class->start = GST_DEBUG_FUNCPTR (gst_partassembly_start);
base_transform_class->stop = GST_DEBUG_FUNCPTR (gst_partassembly_stop);
video_filter_class->set_info = GST_DEBUG_FUNCPTR (gst_partassembly_set_info);
video_filter_class->transform_frame_ip = GST_DEBUG_FUNCPTR (gst_partassembly_transform_frame_ip);
}
static void gst_partassembly_init (Gstpartassembly *partassembly)
{
/*< private >*/
partassembly->priv = (GstpartassemblyPrivate *)gst_partassembly_get_instance_private (partassembly);
// *** define the required parts name, their required number and order to assemble
std::vector<std::string> partNameVector = {
"background",
"container-parts",
"container-semi-finished-products",
"light-guide-cover",
"screw",
"screwed-on",
"semi-finished-products",
"small-board-side-A",
"small-board-side-B",
"wire"};
std::vector<int> partRequiredNumberVector = {0, 0, 1, 2, 0, 4, 1, 0, 2, 1};
std::vector<int> partAssembleOrderVector = {-1, -1, -1, 1, -1, 3, 0, -1, 2, 4}; // -1: omit to check; 0~n: assemble order
partassembly->bom = BASIC_INFORMATION::BOM(partNameVector, partRequiredNumberVector, partAssembleOrderVector);
// ***
// initialize the materials
for(unsigned int i = 0; i < partassembly->bom.NameVector.size(); i++)
{
if(partRequiredNumberVector[i] > 0)
{
partassembly->priv->bomList.push_back(partassembly->bom.NameVector[i]);
partassembly->priv->bomMaterial.push_back(new Material(partassembly->bom.NumberVector[i], partassembly->bom.OrderVector[i]));
}
}
partassembly->priv->partsDisplay = true;
partassembly->priv->informationDisplay = true;
partassembly->priv->alert = false;
partassembly->priv->resetSeconds = 25;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
partassembly->alertTick = 0;
partassembly->runningTime = 0;
partassembly->priv->targetType = "NONE\0";//DEFAULT_TARGET_TYPE;
partassembly->priv->alertType = "idling\0";//DEFAULT_ALERT_TYPE;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
}
void gst_partassembly_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (object);
GST_DEBUG_OBJECT (partassembly, "set_property");
switch (property_id)
{
case PROP_TARGET_TYPE:
{
partassembly->priv->targetType = g_value_dup_string(value);
break;
}
case PROP_ALERT_TYPE:
{
partassembly->priv->alertType = g_value_dup_string(value);
break;
}
case PROP_PARTS_DISPLAY:
{
partassembly->priv->partsDisplay = g_value_get_boolean(value);
if(partassembly->priv->partsDisplay)
GST_MESSAGE("Display part objects is enabled!");
break;
}
case PROP_INFORMATION_DISPLAY:
{
partassembly->priv->informationDisplay = g_value_get_boolean(value);
if(partassembly->priv->informationDisplay)
GST_MESSAGE("Display assembly information is enabled!");
break;
}
case PROP_RESET:
{
partassembly->priv->resetSeconds = g_value_get_int(value);
break;
}
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
void gst_partassembly_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (object);
GST_DEBUG_OBJECT (partassembly, "get_property");
switch (property_id)
{
case PROP_TARGET_TYPE:
//g_value_set_string (value, weardetection->priv->targetType.c_str());
g_value_set_string (value, partassembly->priv->targetType);
break;
case PROP_ALERT_TYPE:
//g_value_set_string (value, partassembly->priv->alertType.c_str());
g_value_set_string (value, partassembly->priv->alertType);
break;
case PROP_PARTS_DISPLAY:
g_value_set_boolean(value, partassembly->priv->partsDisplay);
break;
case PROP_INFORMATION_DISPLAY:
g_value_set_boolean(value, partassembly->priv->informationDisplay);
break;
case PROP_RESET:
g_value_set_int(value, partassembly->priv->resetSeconds);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
void gst_partassembly_dispose (GObject * object)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (object);
GST_DEBUG_OBJECT (partassembly, "dispose");
/* clean up as possible. may be called multiple times */
G_OBJECT_CLASS (gst_partassembly_parent_class)->dispose (object);
}
void gst_partassembly_finalize (GObject * object)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY(object);
GST_DEBUG_OBJECT (partassembly, "finalize");
/* clean up object here */
G_OBJECT_CLASS (gst_partassembly_parent_class)->finalize (object);
}
static gboolean gst_partassembly_start (GstBaseTransform * trans)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (trans);
GST_DEBUG_OBJECT (partassembly, "start");
return TRUE;
}
static gboolean gst_partassembly_stop (GstBaseTransform * trans)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (trans);
partassembly->priv->alert = false;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
GST_DEBUG_OBJECT (partassembly, "stop");
return TRUE;
}
static gboolean gst_partassembly_set_info (GstVideoFilter * filter, GstCaps * incaps, GstVideoInfo * in_info, GstCaps * outcaps, GstVideoInfo * out_info)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (filter);
GST_DEBUG_OBJECT (partassembly, "set_info");
return TRUE;
}
static void gst_partassembly_before_transform (GstBaseTransform * trans, GstBuffer * buffer)
{
long base_time = (GST_ELEMENT (trans))->base_time;
long current_time = gst_clock_get_time((GST_ELEMENT (trans))->clock);
Gstpartassembly *partassembly = GST_PARTASSEMBLY (trans);
partassembly->runningTime = (current_time - base_time)/NANO_SECOND;
}
static GstFlowReturn gst_partassembly_transform_frame_ip (GstVideoFilter * filter, GstVideoFrame * frame)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (filter);
GstMapInfo info;
GST_DEBUG_OBJECT (partassembly, "transform_frame_ip");
gst_buffer_map(frame->buffer, &info, GST_MAP_READ);
// map frame data from stream to partassembly srcMat
mapGstVideoFrame2OpenCVMat(partassembly, frame, info);
// get inference detected persons
getDetectedBox(partassembly, frame->buffer);
// do algorithm
doAlgorithm(partassembly, frame->buffer);
// draw part objects
if(partassembly->priv->partsDisplay)
drawObjects(partassembly);
// draw assembly information
if(partassembly->priv->informationDisplay)
drawStatus(partassembly);
gst_buffer_unmap(frame->buffer, &info);
return GST_FLOW_OK;
}
static void mapGstVideoFrame2OpenCVMat(Gstpartassembly *partassembly, GstVideoFrame *frame, GstMapInfo &info)
{
if(partassembly->srcMat.cols == 0 || partassembly->srcMat.rows == 0)
partassembly->srcMat = cv::Mat(frame->info.height, frame->info.width, CV_8UC3, info.data);
else if((partassembly->srcMat.cols != frame->info.width) || (partassembly->srcMat.rows != frame->info.height))
{
partassembly->srcMat.release();
partassembly->srcMat = cv::Mat(frame->info.height, frame->info.width, CV_8UC3, info.data);
}
else
partassembly->srcMat.data = info.data;
}
static void getDetectedBox(Gstpartassembly *partassembly, GstBuffer* buffer)
{
// reset the status
for (auto& value : partassembly->priv->bomMaterial)
{
value->ClearStatus();
}
partassembly->priv->indexOfSemiProductContainer = -1;
GstAdBatchMeta *meta = gst_buffer_get_ad_batch_meta(buffer);
if (meta == NULL)
GST_MESSAGE("Adlink metadata is not exist!");
else
{
AdBatch &batch = meta->batch;
bool frame_exist = batch.frames.size() > 0 ? true : false;
if(frame_exist)
{
VideoFrameData frame_info = batch.frames[0];
int detectionBoxResultNumber = frame_info.detection_results.size();
int width = partassembly->srcMat.cols;
int height = partassembly->srcMat.rows;
// full iterated all object to find "container-parts" exists alert-type(target-type used in this element)
if(partassembly->targetTypeChecked == false)
{
partassembly->targetTypeChecked = (std::string(partassembly->priv->targetType).compare("NONE"/*DEFAULT_TARGET_TYPE*/) == 0);
if(!partassembly->targetTypeChecked) // target-type was set by user
{
for(unsigned int i = 0 ; i < (uint)detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
// check alert type was set
if(detection_result.meta.find(partassembly->priv->targetType) != std::string::npos)
{
partassembly->targetTypeChecked = true;
break;
}
}
}
}
// if partassembly->targetTypeChecked is true, check whether to reset or not
if(partassembly->targetTypeChecked == true)
{
for(unsigned int i = 0 ; i < (uint)detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
// check alert type was set
if(detection_result.meta.find("empty") != std::string::npos)
{
partassembly->partContainerIsEmpty = true;
}
}
}
for(unsigned int i = 0 ; i < (uint)detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
// check target type is required or set
if(partassembly->targetTypeChecked)
{
int materialIndex = getPartIndexInBomList(partassembly, detection_result.obj_label);
if(materialIndex != -1)
{
int x1 = (int)(width * detection_result.x1);
int y1 = (int)(height * detection_result.y1);
int x2 = (int)(width * detection_result.x2);
int y2 = (int)(height * detection_result.y2);
partassembly->priv->bomMaterial[materialIndex]->Add(x1, y1, x2, y2, detection_result.prob);
// container index
if(detection_result.obj_label.compare("container-semi-finished-products") == 0)
partassembly->priv->indexOfSemiProductContainer = materialIndex;
// semi-product index
if(detection_result.obj_label.compare("semi-finished-products") == 0)
partassembly->priv->indexOfSemiProduct = materialIndex;
}
}
}
}
}
// Check overlap if required in the future
// add the check overlap code here to remove multi-detected objects.
if(partassembly->priv->indexOfSemiProduct > 0) // more than one semi-product
partassembly->priv->bestIndexObjectOfSemiProduct = partassembly->priv->bomMaterial[partassembly->priv->indexOfSemiProduct]->GetBestScoreObjectIndex();
}
static int getPartIndexInBomList(Gstpartassembly *partassembly, const std::string& partName)
{
std::vector<std::string>::iterator it = std::find(partassembly->priv->bomList.begin(), partassembly->priv->bomList.end(), partName);
if(it != partassembly->priv->bomList.end())
return std::distance(partassembly->priv->bomList.begin(), it);
else
return -1;
}
static bool twoSidesCheck(Gstpartassembly *partassembly, int partIndex, int eachSideExistNumber)
{
// get semi-product points vector
std::vector<int> containerPointsVector = partassembly->priv->bomMaterial[partassembly->priv->indexOfSemiProduct]->GetPosition(partassembly->priv->bestIndexObjectOfSemiProduct);
// central vertical line of semi-product
int verticalCenter = (containerPointsVector[0] + containerPointsVector[2]) / 2;
// calculate each side object number
int numLeft = 0;
int numRight = 0;
int objectNumber = partassembly->priv->bomMaterial[partIndex]->GetObjectNumber();
for(int i = 0; i < objectNumber; ++i)
{
std::vector<int> objectPointsVector = partassembly->priv->bomMaterial[partIndex]->GetPosition(i);
if(objectPointsVector[0] < verticalCenter)
numLeft++;
else
numRight++;
}
bool sideCheck = numLeft == eachSideExistNumber && numRight == eachSideExistNumber ? true : false;
return sideCheck;
}
static void doAlgorithm(Gstpartassembly *partassembly, GstBuffer* buffer)
{
// get base time of this element from last startTick
long base_time = (GST_ELEMENT (partassembly))->base_time;
// If metadata does not exist, return directly.
GstAdBatchMeta *meta = gst_buffer_get_ad_batch_meta(buffer);
if (meta == NULL)
{
g_message("Adlink metadata is not exist!");
return;
}
AdBatch &batch = meta->batch;
bool frame_exist = batch.frames.size() > 0 ? true : false;
// if(partassembly->priv->alert == true)
// if((gst_clock_get_time((GST_ELEMENT (partassembly))->clock) - base_time)/NANO_SECOND > 5)
// partassembly->priv->alert = false;
if(partassembly->priv->alert == true)
{
if(partassembly->runningTime - partassembly->alertTick > 5)
{
partassembly->priv->alert = false;
}
}
// Check whether materials are in the container and semi-product
// Get container
int containerId = partassembly->priv->indexOfSemiProductContainer;
if(containerId < 0)
return;
std::vector<int> rectContainerVector;
if(partassembly->priv->bomMaterial[containerId]->GetObjectNumber() > 0)
rectContainerVector = partassembly->priv->bomMaterial[containerId]->GetRectangle(0);
if(rectContainerVector.size() != 4)
{
g_info("No Semi product container detected.");
return;
}
// Container index is containerId in bomMaterial, take the first object one as the container
std::vector<cv::Point> containerPointsVec = partassembly->priv->bomMaterial[containerId]->GetObjectPoints(0);
// Get semi-product
// check semi-product
if(partassembly->priv->bestIndexObjectOfSemiProduct < 0)
{
g_info("No Semi product detected.");
return;
}
int semiProductId = partassembly->priv->indexOfSemiProduct;
int bestIndexObjectOfSemiProduct = partassembly->priv->bestIndexObjectOfSemiProduct;
std::vector<cv::Point> semiProductPointsVec = partassembly->priv->bomMaterial[semiProductId]->GetObjectPoints(bestIndexObjectOfSemiProduct);
//Check each material is in the container and required number
int requiredMaterialNumber = partassembly->priv->bomMaterial.size();
int totalPartsNum = 0;
for(unsigned int materialID = 0; materialID < (uint)requiredMaterialNumber; ++materialID)
{
int totalObjectNumber = partassembly->priv->bomMaterial[materialID]->GetObjectNumber();
std::vector<cv::Point> intersectionPolygon;
int numberInSemiProduct = 0;
for(unsigned int objID = 0; objID < (uint)totalObjectNumber; objID++)
{
std::vector<cv::Point> objectPointsVec = partassembly->priv->bomMaterial[materialID]->GetObjectPoints(objID);
float intersectAreaWithContainer = cv::intersectConvexConvex(containerPointsVec, objectPointsVec, intersectionPolygon, true);
float intersectAreaWithSemiProduct = cv::intersectConvexConvex(semiProductPointsVec, objectPointsVec, intersectionPolygon, true);
if(intersectAreaWithContainer > 0 && intersectAreaWithSemiProduct > 0)
{
numberInSemiProduct++;
totalPartsNum++;
partassembly->priv->bomMaterial[materialID]->SetPartNumber(numberInSemiProduct);
}
}
}
// check is there exist any object in semi-product container.
// if only exist semi-product container, reset all parameters and return
if((totalPartsNum == 2 && partassembly->partContainerIsEmpty == true) // 1 container-semi-finished-products + 1 semi-finished-products
|| (totalPartsNum == 2 && partassembly->priv->alert == true)) // when empty and already alert
{
partassembly->priv->alert = false;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
return;
}
// If this is single assembly, check the reset criteria
if (std::string(partassembly->priv->targetType).compare("NONE") == 0)
{
double totalElapsedTime = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
totalElapsedTime += processingTime[i];
if((totalPartsNum == 2 && partassembly->lastTotalNumber > 8) || totalElapsedTime > partassembly->priv->resetSeconds)
{
partassembly->priv->alert = false;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
return;
}
}
partassembly->lastTotalNumber = totalPartsNum;
//get check assembly action
int checkAction = -1;
for(unsigned int i = 0; i < assemblyActionVector.size(); ++i)
{
if(!assemblyActionVector[i])
{
checkAction = i;
break;
}
}
switch(checkAction)
{
case 0: // put 1 semi-product in container
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
if(partassembly->priv->bomMaterial[semiProductId]->CheckNumber())
{
partassembly->priv->bomMaterial[semiProductId]->SetIndexInBox(checkAction);
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put semi-product in container done.");
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 1: // put 2 light-guide-cover in semi-finished-products(left and right)
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "light-guide-cover");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
if(twoSidesCheck(partassembly, id, 1)) // Simply check each one should be at left and right side.
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put light-guide-cover done.");
}
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 2: // put 2 small-board-side-B in semi-finished-products(left and right)
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "small-board-side-B");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
if(twoSidesCheck(partassembly, id, 1)) // Simply check each one should be at left and right side.
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put small-board-side-B done.");
}
else
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 3: // screw on 4 screws(2 on left, 2 on right)
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "screwed-on");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
if(twoSidesCheck(partassembly, id, 2)) // Simply check each two should be at left and right side.
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Screw on screws done.");
}
else
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 4: // put wire on
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "wire");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put wire done.");
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 5: // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
bool checkFinal = true;
// 2 small-board-side-B
int id = getPartIndexInBomList(partassembly, "small-board-side-B");
checkFinal &= partassembly->priv->bomMaterial[id]->CheckNumber() && twoSidesCheck(partassembly, id, 1);
// 4 screw on
id = getPartIndexInBomList(partassembly, "screwed-on");
checkFinal &= partassembly->priv->bomMaterial[id]->CheckNumber() && twoSidesCheck(partassembly, id, 2);
// 1 wire
id = getPartIndexInBomList(partassembly, "wire");
checkFinal &= partassembly->priv->bomMaterial[id]->CheckNumber();
if(checkFinal)
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Visual inspection done.");
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 6: // complete
GST_MESSAGE("Assembly completed");
assemblyActionVector[checkAction] = true;
break;
default:
//std::cout << "no action need to check.\n";
break;
}
if(frame_exist && containerId != -1)
{
// Check regular time
for(unsigned int i = 0; i < assemblyActionVector.size() ; ++i)
{
if(processingTime[i] > processingRegularTime[i] && partassembly->priv->alert == false)
{
GST_MESSAGE("put idling alert message.");
partassembly->priv->alert = true;
std::string alertMessage = "," + std::string(partassembly->priv->alertType) + "<" + return_current_time_and_date() + ">";
meta->batch.frames[0].detection_results[containerId].meta += alertMessage;
//partassembly->alertTick = cv::getTickCount();
partassembly->alertTick = partassembly->runningTime;
}
}
// If completed, set alert
if(checkAction == assemblyActionVector.size() - 1)
{
std::string alertMessage = "," + std::string("Completed") + "<" + return_current_time_and_date() + ">";
meta->batch.frames[0].detection_results[containerId].meta += alertMessage;
GST_MESSAGE("put Completed alert message.");
}
}
}
static void drawObjects(Gstpartassembly *partassembly)
{
int width = partassembly->srcMat.cols;
int height = partassembly->srcMat.rows;
float scale = 0.025;
int font = cv::FONT_HERSHEY_COMPLEX;
//double font_scale = 0.5;
double font_scale = std::min(width, height)/(25/scale);
int thickness = 2;
int indexOfContainer = partassembly->priv->indexOfSemiProductContainer;
if(indexOfContainer < 0)
return;
if(partassembly->priv->indexOfSemiProductContainer >= 0)
{
int numOfContainer = partassembly->priv->bomMaterial[indexOfContainer]->GetObjectNumber();
if(numOfContainer <= 0)
return;
}
std::vector<cv::Point> containerPointsVec = partassembly->priv->bomMaterial[indexOfContainer]->GetObjectPoints(0);
std::vector<cv::Point> intersectionPolygon;
for(unsigned int i = 0; i < partassembly->priv->bomMaterial.size(); ++i)
{
int numberOfObjectInMaterial = partassembly->priv->bomMaterial[i]->GetObjectNumber();
for(unsigned int index = 0; index < (uint)numberOfObjectInMaterial; index++)
{
std::vector<int> pointsVector = partassembly->priv->bomMaterial[i]->GetPosition(index);
if(pointsVector.size() > 0)
{
std::vector<cv::Point> objectPointsVec = partassembly->priv->bomMaterial[i]->GetObjectPoints(index);
float intersectArea = cv::intersectConvexConvex(containerPointsVec, objectPointsVec, intersectionPolygon, true);
if(intersectArea > 0)
{
int x1 = pointsVector[0];
int y1 = pointsVector[1];
int x2 = pointsVector[2];
int y2 = pointsVector[3];
// draw rectangle
cv::rectangle(partassembly->srcMat, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0), 2);
// put label name
cv::putText(partassembly->srcMat, partassembly->priv->bomList[i], cv::Point(x1, y1), font, font_scale, cv::Scalar(0, 255, 255), thickness, 8, 0);
}
}
}
}
}
static void drawStatus(Gstpartassembly *partassembly)
{
int width = partassembly->srcMat.cols;
int height = partassembly->srcMat.rows;
float scale = 0.02;
int font = cv::FONT_HERSHEY_COMPLEX;
//double font_scale = 1;
double font_scale = std::min(width, height)/(25/scale);
int thickness = 1;
cv::Scalar contentInfoColor = cv::Scalar(255, 255, 255);
cv::Scalar actionDoneColor = cv::Scalar(0, 255, 0);
cv::Scalar actionProcessColor = cv::Scalar(0, 255, 255);
int startX = width * 0.03;
int startY = height * 0.5;
//int heightShift = 35;
int heightShift = cv::getTextSize("Text", font, font_scale, thickness, 0).height * 1.5;
bool metProcessingAction = false;
double totalElapsedTime = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
startY += heightShift;
totalElapsedTime += processingTime[i];
std::string timeString = " [" + round2String(processingTime[i], 3) + " s]";
if(!assemblyActionVector[i] && !metProcessingAction)
{
metProcessingAction = true;
cv::putText(partassembly->srcMat, assemblyActionInfoVector[i] + timeString, cv::Point(startX, startY), font, font_scale, actionProcessColor, thickness * 2, 4, 0);
cv::circle (partassembly->srcMat, cv::Point(startX - width * 0.015, startY - heightShift / 4), heightShift / 2.5, actionProcessColor, -1, cv::LINE_8, 0);
}
else if(assemblyActionVector[i])
{
cv::putText(partassembly->srcMat, assemblyActionInfoVector[i] + timeString, cv::Point(startX, startY), font, font_scale, actionDoneColor, thickness, 4, 0);
}
else
{
cv::putText(partassembly->srcMat, assemblyActionInfoVector[i] + timeString, cv::Point(startX, startY), font, font_scale, contentInfoColor, thickness, 4, 0);
}
}
// show total elapsed time
startY += heightShift;
cv::putText(partassembly->srcMat, "total elapsed time = " + round2String(totalElapsedTime, 3) + " s", cv::Point(startX, startY), font, font_scale, cv::Scalar(30, 144, 255), thickness, 4, 0);
// show alert
if(partassembly->priv->alert)
{
startY += 2 * heightShift;
cv::putText(partassembly->srcMat, " idling !!", cv::Point(startX, startY), font, font_scale * 2, cv::Scalar(0, 0, 255), thickness * 2, 4, 0);
}
}
| 41.399381
| 351
| 0.635083
|
AIoT-IST
|
c7955b06d771c30961059c9dbbdc62196053fa3d
| 12,843
|
cpp
|
C++
|
src/app_eth.cpp
|
tsc19/fring
|
2418ce1b27892f2f5c256f94ae0c5fc376cfa72c
|
[
"Apache-2.0"
] | 3
|
2019-11-06T09:05:07.000Z
|
2021-04-11T08:46:57.000Z
|
src/app_eth.cpp
|
tsc19/fring
|
2418ce1b27892f2f5c256f94ae0c5fc376cfa72c
|
[
"Apache-2.0"
] | null | null | null |
src/app_eth.cpp
|
tsc19/fring
|
2418ce1b27892f2f5c256f94ae0c5fc376cfa72c
|
[
"Apache-2.0"
] | null | null | null |
#include "app_eth.h"
// constructors
BaseAppETH::BaseAppETH(std::string ip, unsigned short port, std::string id) {
this->node = std::make_shared<Node>(id, ip, port);
this->node_table = std::make_shared<NodeTableETH>(id);
}
// getters
std::shared_ptr<Node> BaseAppETH::get_node() {
return this->node;
}
std::shared_ptr<NodeTableETH> BaseAppETH::get_node_table() {
return this->node_table;
}
std::shared_ptr<PeerManagerETH> BaseAppETH::get_peer_manager() {
return this->peer_manager;
}
// public functions
void BaseAppETH::form_structure(int num_nodes_in_dist, int num_cnodes_in_dist,
int num_nodes_in_city, int num_cnodes_in_city,
int num_nodes_in_state, int num_cnodes_in_state,
int num_nodes_in_country, int num_cnodes_in_country,
int num_nodes_in_continent, int num_continents,
int num_cnodes_in_continent,
unsigned short starting_port_number) {
// form network topology based ID
std::string id_in_dist = this->node->get_id().substr(ID_SINGLE_START, ID_SINGLE_LEN);
std::string dist_id = this->node->get_id().substr(ID_DISTRICT_START, ID_DISTRICT_LEN);
std::string city_id = this->node->get_id().substr(ID_CITY_START, ID_CITY_LEN);
std::string state_id = this->node->get_id().substr(ID_STATE_START, ID_STATE_LEN);
std::string country_id = this->node->get_id().substr(ID_COUNTRY_START, ID_COUNTRY_LEN);
std::string continent_id = this->node->get_id().substr(ID_CONTINENT_START, ID_CONTINENT_LEN);
int num_dists_in_city, num_cities_in_state, num_states_in_country, num_countries_in_continent;
num_dists_in_city = num_nodes_in_city/num_cnodes_in_dist;
if (num_dists_in_city == 0)
num_dists_in_city = 1;
num_cities_in_state = num_nodes_in_state/num_cnodes_in_city;
if (num_cities_in_state == 0)
num_cities_in_state = 1;
num_states_in_country = num_nodes_in_country/num_cnodes_in_state;
if (num_states_in_country == 0)
num_states_in_country = 1;
num_countries_in_continent = num_nodes_in_continent/num_cnodes_in_country;
if (num_countries_in_continent == 0)
num_countries_in_continent = 1;
int num_nodes_total = num_continents * num_countries_in_continent * num_states_in_country * num_cities_in_state * num_dists_in_city * num_nodes_in_dist;
// set node table
std::vector<std::shared_ptr<Node>> table;
// generate random neighbors to connect
std::unordered_set<int> neighbor_ids;
int self_order = convert_ID_string_to_int(this->node->get_id(),
num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent);
neighbor_ids.insert((self_order+1) % num_nodes_total);
for (int i = 0; i < TABLE_SIZE_ETH; i++) {
int id = rand() % num_nodes_total;
if (neighbor_ids.find(id) == neighbor_ids.end() && id != self_order) {
neighbor_ids.insert(id);
} else {
i--;
}
}
// int to string
std::stringstream ss;
int counter = 0;
for (int continent_counter = 0; continent_counter < num_continents; continent_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_CONTINENT_LEN) << std::setfill('0') << continent_counter;
continent_id = ss.str();
for (int country_counter = 0; country_counter < num_countries_in_continent; country_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_COUNTRY_LEN) << std::setfill('0') << country_counter;
country_id = ss.str();
for (int state_counter = 0; state_counter < num_states_in_country; state_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_STATE_LEN) << std::setfill('0') << state_counter;
state_id = ss.str();
for (int city_counter = 0; city_counter < num_cities_in_state; city_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_CITY_LEN) << std::setfill('0') << city_counter;
city_id = ss.str();
for (int district_counter = 0; district_counter < num_dists_in_city; district_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_DISTRICT_LEN) << std::setfill('0') << district_counter;
dist_id = ss.str();
for (int i = 0; i < num_nodes_in_dist; i++) {
ss.str("");
ss.clear();
ss << std::setw(ID_SINGLE_LEN) << std::setfill('0') << i;
id_in_dist = ss.str();
std::string node_id = continent_id + country_id + state_id + city_id + dist_id + id_in_dist;
int order = convert_ID_string_to_int(node_id,
num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent);
if (neighbor_ids.find(order) != neighbor_ids.end() && node_id != this->node->get_id()) {
unsigned short port = starting_port_number + order;
Node node(node_id, "127.0.0.1", port);
if (order == self_order+1)
table.insert(table.begin(), std::make_shared<Node>(node));
else
table.push_back(std::make_shared<Node>(node));
}
counter++;
}
}
}
}
}
}
this->node_table->set_table(table);
return;
}
void BaseAppETH::start(const std::string &start_time, int num_nodes_in_dist, int num_cnodes_in_dist,
int num_nodes_in_city, int num_cnodes_in_city,
int num_nodes_in_state, int num_cnodes_in_state,
int num_nodes_in_country, int num_cnodes_in_country,
int num_nodes_in_continent, int num_continents,
int num_cnodes_in_continent,
unsigned short starting_port_number) {
std::cout << "Setting up NodeTable for node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
std::cout << "Establishing structure on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
// form the geographical structure
this->form_structure(num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent, num_continents,
num_cnodes_in_continent,
starting_port_number);
std::cout << "Structure established on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
std::cout << "Node Tables on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
for (auto peer : this->node_table->get_table()) {
std::cout << "Peer - " + peer->get_id() + " " + peer->get_ip() + ":" + std::to_string(peer->get_port()) << "\n";
}
this->peer_manager = std::make_shared<PeerManagerETH>(node, node_table, start_time);
// set gossip mode
this->peer_manager->set_mode(PeerManagerETH::PUSH); // PUSH version
// this->peer_manager->set_mode(PeerManagerETH::PULL); // PULL version
std::cout << "Starting ETH PeerManager on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
this->peer_manager->start();
return;
}
void BaseAppETH::stop() {
this->peer_manager->stop();
return;
}
void BaseAppETH::broadcast(const std::string &data) {
this->peer_manager->broadcast(data, TTL_ETH, "");
return;
}
int main(int argc, char** argv) {
srand(std::atoi(argv[2]) + time(NULL));
if (argc != 17) {
std::cout << "Wrong arguments. Correct usage: "
<< "./app_eth ip_addr port_num id "
<< "num_nodes_in_dist num_cnodes_in_dist "
<< "num_nodes_in_city num_cnodes_in_city "
<< "num_nodes_in_state num_cnodes_in_state "
<< "num_nodes_in_country num_cnodes_in_country "
<< "num_nodes_in_continent num_cnodes_in_continent "
<< "num_continents"
<< "starting_port_num start_time\n";
return 0;
}
std::string ip = argv[1];
unsigned short port = (unsigned short) std::atoi(argv[2]);
std::string id = argv[3];
// information used for network topology establishment (only used for evaluation)
int num_nodes_in_dist = std::atoi(argv[4]);
int num_cnodes_in_dist = std::atoi(argv[5]);
int num_nodes_in_city = std::atoi(argv[6]);
int num_cnodes_in_city = std::atoi(argv[7]);
int num_nodes_in_state = std::atoi(argv[8]);
int num_cnodes_in_state = std::atoi(argv[9]);
int num_nodes_in_country = std::atoi(argv[10]);
int num_cnodes_in_country = std::atoi(argv[11]);
int num_nodes_in_continent = std::atoi(argv[12]);
int num_cnodes_in_continent = std::atoi(argv[13]);
int num_continents = std::atoi(argv[14]);
int starting_port_number = std::atoi(argv[15]);
std::string start_time = argv[16];
// initialize the app
std::cout << "Creating ETH base application on node [ID: " + id + "] [IP: " + ip + "] [" + std::to_string(port) + "]\n";
BaseAppETH app = BaseAppETH(ip, port, id);
// start the app service
std::cout << "Starting ETH base service on node [ID: " + id + "] [IP: " + ip + "] [" + std::to_string(port) + "]\n";
app.start(start_time, num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent, num_continents,
num_cnodes_in_continent,
starting_port_number);
// message record logging
std::ofstream ofs;
ofs.open("../test/log/" + start_time + "/" + app.get_node()->get_id() + ".csv");
if (ofs.is_open()) {
ofs << Message::csv_header << "\n";
ofs.close();
} else {
std::cout << "Error opening file\n";
}
// broadcast a message
int order = convert_ID_string_to_int(id, num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent);
if (order == 1) {
//int num_messages_to_broadcast = 2;
//int mean_interval = 10;
//int variance = 2;
int random_sleep_time = 5; // rand() % 180;
std::this_thread::sleep_for (std::chrono::seconds(random_sleep_time));
std::cout << "Slept for " << random_sleep_time << " seconds\n";
std::cout << "Broadcasting message ...\n";
// for (int i = 0; i < num_messages_to_broadcast-1; i++) {
// std::cout << "Broadcast a message of size " << data_of_block_size.length() / 1000 << "kb\n";
// app.broadcast(data_of_block_size);
// std::this_thread::sleep_for (std::chrono::seconds(mean_interval-variance + rand() % variance));
// }
app.broadcast(data_of_block_size);
}
// block
app.stop();
return 0;
}
| 46.032258
| 173
| 0.56926
|
tsc19
|
c7961212cb8b85c10114c83869a245f0d7803c16
| 403
|
cpp
|
C++
|
CLIHelperTests/group_argument_is.cpp
|
BitCruncher0/CLIHelper
|
9ea8e6b5f14f038c143c4e552fad8e1394556a9d
|
[
"Apache-2.0"
] | 1
|
2022-01-10T23:47:40.000Z
|
2022-01-10T23:47:40.000Z
|
CLIHelperTests/group_argument_is.cpp
|
BitCruncher0/CLIHelper
|
9ea8e6b5f14f038c143c4e552fad8e1394556a9d
|
[
"Apache-2.0"
] | null | null | null |
CLIHelperTests/group_argument_is.cpp
|
BitCruncher0/CLIHelper
|
9ea8e6b5f14f038c143c4e552fad8e1394556a9d
|
[
"Apache-2.0"
] | null | null | null |
#include "CppUTest/TestHarness.h"
#include "../cli.hpp"
#include <string>
#include <fstream>
#include <vector>
using std::string;
using std::vector;
TEST_GROUP(ArgumentIs)
{
};
TEST(ArgumentIs, Returns_true_if_Nth_argument_is_key)
{
CHECK_EQUAL(false, argumentIs("a", 0, "a b"));
CHECK_EQUAL(true, argumentIs("b", 0, "a b"));
CHECK_EQUAL(true, argumentIs("d", 2, "a b c d"));
}
| 13.433333
| 53
| 0.662531
|
BitCruncher0
|
c796986e874e270f30946139916ed110eb4622db
| 3,423
|
cpp
|
C++
|
tools/pathanalyzer/pathanalyzer_spacer_test.cpp
|
JanWielemaker/pharos
|
8789a3a5ef4e6094ce0b989d8d987d1fe2102d3e
|
[
"RSA-MD"
] | 3
|
2015-07-15T08:43:56.000Z
|
2021-02-28T17:53:52.000Z
|
tools/pathanalyzer/pathanalyzer_spacer_test.cpp
|
sei-ccohen/pharos
|
78d08494a5c0bffff3789cae7acc538303b1926c
|
[
"RSA-MD"
] | null | null | null |
tools/pathanalyzer/pathanalyzer_spacer_test.cpp
|
sei-ccohen/pharos
|
78d08494a5c0bffff3789cae7acc538303b1926c
|
[
"RSA-MD"
] | null | null | null |
// Copyright 2018-2019 Carnegie Mellon University. See LICENSE file for terms.
#include <libpharos/spacer.hpp>
#include "pathanalyzer_test_config.hpp"
using namespace pharos;
using namespace pharos::ir;
const DescriptorSet* global_ds = nullptr;
// -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
// Instantiate tests with parameters read from the configuration file
INSTANTIATE_TEST_CASE_P(PathAnalyzerTestParameters, PATestFixture,
::testing::ValuesIn(test_config),
PATestFixture::PrintToStringParamName());
// -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
// Start parameterized test cases for path finding
// XXX put this somewhere better
ImportRewriteSet get_imports () {
return {
// Because of in-lining, we may need to jump over a call to path_goal to reach the one we
// selected. As a result we need to include time.
std::make_pair ("bogus.so", "time"),
std::make_pair ("bogus.so", "rand"),
std::make_pair ("bogus.so", "_Znwm"),
std::make_pair ("MSVCR100D.dll", "rand"),
std::make_pair ("ucrtbased.dll", "rand")
};
}
TEST_P(PATestFixture, TestSpacer) {
PATestConfiguration test = GetParam();
if (test.name=="" || test.start==INVALID_ADDRESS ||
(test.goal==INVALID_ADDRESS && test.bad==INVALID_ADDRESS)) {
FAIL() << "Improper test configuration!";
return;
}
try {
PharosZ3Solver z3;
z3.set_timeout(10000);
if (test.seed != 0) {
z3.set_seed(test.seed);
}
std::stringstream log_ss;
log_ss << test.name << ".smt";
z3.set_log_name(log_ss.str());
SpacerAnalyzer sa(*global_ds, z3, get_imports(), "spacer");
if (test.goal!=INVALID_ADDRESS) {
ASSERT_TRUE(z3::sat == std::get<0>(sa.find_path_hierarchical(test.start, test.goal)))
<< "Could not find expected path using SPACER!";
}
else if (test.bad!=INVALID_ADDRESS) {
ASSERT_FALSE(z3::sat == std::get<0>(sa.find_path_hierarchical(test.start, test.bad)))
<< "Found invalid path using SPACER!";
}
}
catch (std::exception& ex) {
OERROR << "Exception thrown: " << ex.what() << LEND;
}
catch (z3::exception& ex) {
OERROR << "Exception thrown: " << ex << LEND;
}
}
// End parameterized test cases for path finding
// -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
static int pathanalyzer_test_spacer_main(int argc, char **argv) {
// Handle options
namespace po = boost::program_options;
ProgOptDesc pathod = pathanalyzer_test_options();
ProgOptDesc csod = cert_standard_options();
pathod.add(csod);
ProgOptVarMap ovm = parse_cert_options(argc, argv, pathod);
DescriptorSet ds(ovm);
// Resolve imports, load API data, etc.
ds.resolve_imports();
// Global for just this test program to make gtest happy.
global_ds = &ds;
// This is not the most durable solution, but it works. JSG should move this into the testing
// fixture
//Z3_global_param_set("verbose", "10");
PATestAnalyzer pa(ds, ovm);
pa.analyze();
configure_tests(pa, ovm);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
int main(int argc, char **argv) {
return pharos_main("SPTE", pathanalyzer_test_spacer_main, argc, argv, STDERR_FILENO);
}
/* Local Variables: */
/* mode: c++ */
/* fill-column: 95 */
/* comment-column: 0 */
/* End: */
| 29.25641
| 95
| 0.621969
|
JanWielemaker
|
c79b1259fec0b2d76602c19fa77ad7979dd8509f
| 1,993
|
hpp
|
C++
|
engine/glrenderer/buffers.hpp
|
tapio/weep
|
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
|
[
"MIT"
] | 33
|
2017-01-13T20:47:21.000Z
|
2022-03-21T23:29:17.000Z
|
engine/glrenderer/buffers.hpp
|
tapio/weep
|
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
|
[
"MIT"
] | null | null | null |
engine/glrenderer/buffers.hpp
|
tapio/weep
|
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
|
[
"MIT"
] | 4
|
2016-12-10T16:10:42.000Z
|
2020-06-28T04:44:11.000Z
|
#pragma once
#include "common.hpp"
#include "../../data/shaders/uniforms.glsl"
// Generic Buffer Object
struct BufferObjectBase
{
virtual ~BufferObjectBase() { destroy(); }
NONCOPYABLE(BufferObjectBase);
protected:
BufferObjectBase() {}
void create(uint type, uint binding, uint size, const void* data);
void bindBase(uint type, uint binding);
void upload(uint type, uint size, const void* data);
public:
void destroy();
uint id = 0;
};
// Uniform Buffer Object
template<typename T>
struct UBO : public BufferObjectBase
{
UBO() {}
NONCOPYABLE(UBO);
void create() { BufferObjectBase::create(/*GL_UNIFORM_BUFFER*/ 0x8A11, uniforms.binding, sizeof(uniforms), &uniforms); }
void bindBase() { BufferObjectBase::bindBase(/*GL_UNIFORM_BUFFER*/ 0x8A11, uniforms.binding); }
void upload() { BufferObjectBase::upload(/*GL_UNIFORM_BUFFER*/ 0x8A11, sizeof(uniforms), &uniforms); }
T uniforms = T();
};
// Shader Storage Buffer Object
template<typename T>
struct SSBO : public BufferObjectBase
{
SSBO(uint binding, uint size = 0): binding(binding) { buffer.resize(size); }
NONCOPYABLE(SSBO);
void create(bool preserveData = false) {
BufferObjectBase::create(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, binding, sizeof(T) * buffer.size(), buffer.data());
if (!preserveData)
releaseCPUMem();
}
void create(uint newSize, bool preserveData = false) {
if (buffer.empty() && !preserveData) {
BufferObjectBase::create(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, binding, sizeof(T) * newSize, nullptr);
} else {
buffer.resize(newSize);
create(preserveData);
}
}
void bindBase() { BufferObjectBase::bindBase(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, binding); }
void upload(bool preserveData = false) {
BufferObjectBase::upload(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, sizeof(T) * buffer.size(), buffer.data());
if (!preserveData)
releaseCPUMem();
}
void releaseCPUMem() {
buffer.clear();
buffer.shrink_to_fit();
}
uint binding = 0;
std::vector<T> buffer;
};
| 24.9125
| 121
| 0.712494
|
tapio
|
c79bf17c6647e14d45af6d6a9f7eae7520b24632
| 4,519
|
cpp
|
C++
|
DataConverter/SegmenterDictionaryFeatureGenerator.cpp
|
hiroshi-manabe/CRFSegmenter
|
c8b0544933701f91ff9cfac9301c51b181a4f846
|
[
"BSL-1.0"
] | 16
|
2016-07-01T01:40:56.000Z
|
2020-05-06T03:29:42.000Z
|
DataConverter/SegmenterDictionaryFeatureGenerator.cpp
|
hiroshi-manabe/CRFSegmenter
|
c8b0544933701f91ff9cfac9301c51b181a4f846
|
[
"BSL-1.0"
] | 9
|
2016-07-04T06:44:42.000Z
|
2020-05-14T21:23:46.000Z
|
DataConverter/SegmenterDictionaryFeatureGenerator.cpp
|
hiroshi-manabe/CRFSegmenter
|
c8b0544933701f91ff9cfac9301c51b181a4f846
|
[
"BSL-1.0"
] | 2
|
2016-07-05T14:50:32.000Z
|
2019-10-03T02:35:53.000Z
|
#include "SegmenterDictionaryFeatureGenerator.h"
#include "../Dictionary/DictionaryClass.h"
#include "../Utility/CharWithSpace.h"
#include <algorithm>
#include <cassert>
#include <unordered_set>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace DataConverter {
using std::make_shared;
using std::move;
using std::string;
using std::unordered_set;
using std::vector;
using Dictionary::DictionaryClass;
using HighOrderCRF::FeatureTemplate;
using Utility::CharWithSpace;
SegmenterDictionaryFeatureGenerator::SegmenterDictionaryFeatureGenerator(const unordered_set<string> &dictionaries, size_t maxLabelLength) {
dictionary = make_shared<DictionaryClass>(dictionaries);
this->maxLabelLength = maxLabelLength;
}
vector<vector<FeatureTemplate>> SegmenterDictionaryFeatureGenerator::generateFeatureTemplates(const vector<CharWithSpace> &observationList) const {
vector<vector<FeatureTemplate>> featureTemplateListList(observationList.size());
// Generates all the templates
// Reconstructs the whole sentence, recording the start positions
string sentence;
vector<size_t> startPosList;
for (const auto uchar : observationList) {
startPosList.emplace_back(sentence.length());
sentence += uchar.toString();
}
startPosList.emplace_back(sentence.length());
vector<size_t> utf8PosToCharPosList(sentence.length() + 1);
for (size_t i = 0; i < startPosList.size(); ++i) {
utf8PosToCharPosList[startPosList[i]] = i;
}
utf8PosToCharPosList[sentence.length()] = startPosList.size();
for (size_t i = 0; i < startPosList.size() - 1; ++i) {
size_t startUtf8Pos = startPosList[i];
auto ch = observationList[i];
// skip the space if there is one
if (ch.hasSpace()) {
++startUtf8Pos;
}
// Looks up the words
auto results = dictionary->commonPrefixSearch(
string(sentence.c_str() + startUtf8Pos, sentence.length() - startUtf8Pos));
for (auto &p : results) {
auto charLength = p.first;
auto &featureListList = p.second;
unordered_set<string> featureSet;
for (auto &featureList : featureListList) {
for (auto &feature : featureList) {
featureSet.emplace(move(feature));
}
}
size_t endCharPos = utf8PosToCharPosList[startUtf8Pos + charLength];
if (endCharPos == 0) { // This cannot happen if everything is in well-formed utf-8
continue;
}
int wordLength = endCharPos - i;
assert(wordLength > 0);
size_t labelLength = wordLength + 1;
if (labelLength > maxLabelLength) {
labelLength = maxLabelLength;
}
bool hasLeftSpace = ch.hasSpace();
bool hasRightSpace = (endCharPos < observationList.size() ? observationList[endCharPos].hasSpace() : true);
string spaceStr;
if (hasLeftSpace) {
spaceStr += "LS";
}
if (hasRightSpace) {
spaceStr += "RS";
}
spaceStr += "-";
// Feature template for the left position
auto &leftTemplateList = featureTemplateListList[i];
for (const auto &featureStr : featureSet) {
leftTemplateList.emplace_back(string("Rw-") + featureStr, 1);
if (hasLeftSpace || hasRightSpace) {
leftTemplateList.emplace_back(string("Rw") + spaceStr + featureStr, 1);
}
}
if (endCharPos >= observationList.size()) {
continue;
}
// Feature templates for the right position
auto &rightTemplateList = featureTemplateListList[endCharPos];
for (const auto &featureStr : featureSet) {
rightTemplateList.emplace_back(string("Lw-") + featureStr, 1);
rightTemplateList.emplace_back(string("LW-") + featureStr, labelLength);
if (hasLeftSpace || hasRightSpace) {
rightTemplateList.emplace_back(string("Lw") + spaceStr + featureStr, 1);
rightTemplateList.emplace_back(string("LW") + spaceStr + featureStr, labelLength);
}
}
}
}
return featureTemplateListList;
}
} // namespace DataConverter
| 36.739837
| 147
| 0.612525
|
hiroshi-manabe
|
c7a2aafa94bf6965635216afb9ef0f2e0be9aa35
| 154
|
hpp
|
C++
|
pythran/pythonic/__builtin__/pythran/kwonly.hpp
|
AlifeLines/pythran
|
b793344637173cac8e5f4a79b0ab788951d53899
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/__builtin__/pythran/kwonly.hpp
|
AlifeLines/pythran
|
b793344637173cac8e5f4a79b0ab788951d53899
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/__builtin__/pythran/kwonly.hpp
|
AlifeLines/pythran
|
b793344637173cac8e5f4a79b0ab788951d53899
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_BUILTIN_PYTHRAN_KWONLY_HPP
#define PYTHONIC_BUILTIN_PYTHRAN_KWONLY_HPP
#include "pythonic/include/__builtin__/pythran/kwonly.hpp"
#endif
| 30.8
| 58
| 0.883117
|
AlifeLines
|
c7a3126de11c19d81ebc972cbf196e7dd7637b43
| 14,537
|
cpp
|
C++
|
flite/src/cg/mlsa.cpp
|
Barath-Kannan/flite
|
236f91a9a1e60fd25f1deed6d48022567cd7100f
|
[
"Apache-2.0"
] | 7
|
2017-12-10T23:02:22.000Z
|
2021-08-05T21:12:11.000Z
|
flite/src/cg/mlsa.cpp
|
Barath-Kannan/flite
|
236f91a9a1e60fd25f1deed6d48022567cd7100f
|
[
"Apache-2.0"
] | null | null | null |
flite/src/cg/mlsa.cpp
|
Barath-Kannan/flite
|
236f91a9a1e60fd25f1deed6d48022567cd7100f
|
[
"Apache-2.0"
] | 3
|
2018-10-28T03:47:09.000Z
|
2020-06-04T08:54:23.000Z
|
#include "flite/audio/audio.hpp"
#include "flite/synthcommon/track.hpp"
#include "flite/synthcommon/wave.hpp"
#include "flite/utils/alloc.hpp"
#include "flite/utils/math.hpp"
#include "flite/utils/string.hpp"
#ifdef ANDROID
#define SPEED_HACK
#endif
#ifdef UNDER_CE
#define SPEED_HACK
/* This is one of those other things you shouldn't do, but it makes
CG voices in flowm fast enough on my phone */
#define double float
#endif
#include "./mlsa.hpp"
static cst_wave* synthesis_body(const cst_track* params, const cst_track* str, double fs, double framem, cst_cg_db* cg_db, cst_audio_streaming_info* asi, int mlsa_speed_param);
cst_wave* mlsa_resynthesis(const cst_track* params, const cst_track* str, cst_cg_db* cg_db, cst_audio_streaming_info* asi, int mlsa_speed_param)
{
/* Resynthesizes a wave from given track */
cst_wave* wave = 0;
int sr = cg_db->sample_rate;
double shift;
if (params->num_frames > 1)
shift = 1000.0 * (params->times[1] - params->times[0]);
else
shift = 5.0;
wave = synthesis_body(params, str, sr, shift, cg_db, asi, mlsa_speed_param);
return wave;
}
static cst_wave* synthesis_body(const cst_track* params, /* f0 + mcep */
const cst_track* str,
double fs, /* sampling frequency (Hz) */
double framem, /* frame size */
cst_cg_db* cg_db,
cst_audio_streaming_info* asi,
int mlsa_speed_param)
{
long t, pos;
int framel, i;
double f0;
VocoderSetup vs;
cst_wave* wave = 0;
double* mcep;
int stream_mark;
int rc = CST_AUDIO_STREAM_CONT;
int num_mcep;
double ffs = fs;
num_mcep = params->num_channels - 1;
if ((num_mcep > mlsa_speed_param) &&
((num_mcep - mlsa_speed_param) > 4))
/* Basically ignore some of the higher coeffs */
/* It'll sound worse, but it will be faster */
num_mcep -= mlsa_speed_param;
framel = (int)(0.5 + (framem * ffs / 1000.0)); /* 80 for 16KHz */
init_vocoder(ffs, framel, num_mcep, &vs, cg_db);
if (str != NULL)
vs.gauss = MFALSE;
/* synthesize waveforms by MLSA filter */
wave = new_wave();
cst_wave_resize(wave, params->num_frames * framel, 1);
wave->sample_rate = fs;
mcep = cst_alloc(double, num_mcep + 1);
for (t = 0, stream_mark = pos = 0;
(rc == CST_AUDIO_STREAM_CONT) && (t < params->num_frames);
t++) {
f0 = (double)params->frames[t][0];
for (i = 1; i < num_mcep + 1; i++)
mcep[i - 1] = params->frames[t][i];
mcep[i - 1] = 0;
if (str)
vocoder(f0, mcep, str->frames[t], num_mcep, cg_db, &vs, wave, &pos);
else
vocoder(f0, mcep, NULL, num_mcep, cg_db, &vs, wave, &pos);
if (asi && (pos - stream_mark > asi->min_buffsize)) {
rc = (*asi->asc)(wave, stream_mark, pos - stream_mark, 0, asi);
stream_mark = pos;
}
}
wave->num_samples = pos;
if (asi && (rc == CST_AUDIO_STREAM_CONT)) { /* drain the last part of the waveform */
(*asi->asc)(wave, stream_mark, pos - stream_mark, 1, asi);
}
/* memory free */
cst_free(mcep);
free_vocoder(&vs);
if (rc == CST_AUDIO_STREAM_STOP) {
delete_wave(wave);
return NULL;
}
else
return wave;
}
static void init_vocoder(double fs, int framel, int m, VocoderSetup* vs, cst_cg_db* cg_db)
{
/* initialize global parameter */
vs->fprd = framel;
vs->iprd = 1;
vs->seed = 1;
#ifdef SPEED_HACK
/* This makes it about 25% faster and sounds basically the same */
vs->pd = 4;
#else
vs->pd = 5;
#endif
vs->next = 1;
vs->gauss = MTRUE;
/* Pade' approximants */
vs->pade[0] = 1.0;
vs->pade[1] = 1.0;
vs->pade[2] = 0.0;
vs->pade[3] = 1.0;
vs->pade[4] = 0.0;
vs->pade[5] = 0.0;
vs->pade[6] = 1.0;
vs->pade[7] = 0.0;
vs->pade[8] = 0.0;
vs->pade[9] = 0.0;
vs->pade[10] = 1.0;
vs->pade[11] = 0.4999273;
vs->pade[12] = 0.1067005;
vs->pade[13] = 0.01170221;
vs->pade[14] = 0.0005656279;
vs->pade[15] = 1.0;
vs->pade[16] = 0.4999391;
vs->pade[17] = 0.1107098;
vs->pade[18] = 0.01369984;
vs->pade[19] = 0.0009564853;
vs->pade[20] = 0.00003041721;
vs->rate = fs;
vs->c = cst_alloc(double, 3 * (m + 1) + 3 * (vs->pd + 1) + vs->pd * (m + 2));
vs->p1 = -1;
vs->sw = 0;
vs->x = 0x55555555;
/* for postfiltering */
vs->mc = NULL;
vs->o = 0;
vs->d = NULL;
vs->irleng = 64;
/* for MIXED EXCITATION */
vs->ME_order = cg_db->ME_order;
vs->ME_num = cg_db->ME_num;
vs->hpulse = cst_alloc(double, vs->ME_order);
vs->hnoise = cst_alloc(double, vs->ME_order);
vs->xpulsesig = cst_alloc(double, vs->ME_order);
vs->xnoisesig = cst_alloc(double, vs->ME_order);
vs->h = cg_db->me_h;
return;
}
static double plus_or_minus_one()
{
/* Randomly return 1 or -1 */
/* not sure rand() is portable */
if (rand() > RAND_MAX / 2.0)
return 1.0;
else
return -1.0;
}
static void vocoder(double p, double* mc, const float* str, int m, cst_cg_db* cg_db, VocoderSetup* vs, cst_wave* wav, long* pos)
{
double inc, x, e1, e2;
int i, j, k;
double xpulse, xnoise;
double fxpulse, fxnoise;
float gain = 1.0;
if (cg_db->gain != 0.0)
gain = cg_db->gain;
if (str != NULL) /* MIXED-EXCITATION */
{
/* Copy in str's and build hpulse and hnoise for this frame */
for (i = 0; i < vs->ME_order; i++) {
vs->hpulse[i] = vs->hnoise[i] = 0.0;
for (j = 0; j < vs->ME_num; j++) {
vs->hpulse[i] += str[j] * vs->h[j][i];
vs->hnoise[i] += (1 - str[j]) * vs->h[j][i];
}
}
}
if (p != 0.0)
p = vs->rate / p; /* f0 -> pitch */
if (vs->p1 < 0) {
if (vs->gauss & (vs->seed != 1))
vs->next = srnd((unsigned)vs->seed);
vs->p1 = p;
vs->pc = vs->p1;
vs->cc = vs->c + m + 1;
vs->cinc = vs->cc + m + 1;
vs->d1 = vs->cinc + m + 1;
mc2b(mc, vs->c, m, cg_db->mlsa_alpha);
if (cg_db->mlsa_beta > 0.0 && m > 1) {
e1 = b2en(vs->c, m, cg_db->mlsa_alpha, vs);
vs->c[1] -= cg_db->mlsa_beta * cg_db->mlsa_alpha * mc[2];
for (k = 2; k <= m; k++)
vs->c[k] *= (1.0 + cg_db->mlsa_beta);
e2 = b2en(vs->c, m, cg_db->mlsa_alpha, vs);
vs->c[0] += log(e1 / e2) / 2;
}
return;
}
mc2b(mc, vs->cc, m, cg_db->mlsa_alpha);
if (cg_db->mlsa_beta > 0.0 && m > 1) {
e1 = b2en(vs->cc, m, cg_db->mlsa_alpha, vs);
vs->cc[1] -= cg_db->mlsa_beta * cg_db->mlsa_alpha * mc[2];
for (k = 2; k <= m; k++)
vs->cc[k] *= (1.0 + cg_db->mlsa_beta);
e2 = b2en(vs->cc, m, cg_db->mlsa_alpha, vs);
vs->cc[0] += log(e1 / e2) / 2.0;
}
for (k = 0; k <= m; k++)
vs->cinc[k] = (vs->cc[k] - vs->c[k]) *
(double)vs->iprd / (double)vs->fprd;
if (vs->p1 != 0.0 && p != 0.0) {
inc = (p - vs->p1) * (double)vs->iprd / (double)vs->fprd;
}
else {
inc = 0.0;
vs->pc = p;
vs->p1 = 0.0;
}
for (j = vs->fprd, i = (vs->iprd + 1) / 2; j--;) {
if (vs->p1 == 0.0) {
if (vs->gauss)
x = (double)nrandom(vs);
else
x = plus_or_minus_one();
if (str != NULL) /* MIXED EXCITATION */
{
xnoise = x;
xpulse = 0.0;
}
}
else {
if ((vs->pc += 1.0) >= vs->p1) {
x = sqrt(vs->p1);
vs->pc = vs->pc - vs->p1;
}
else
x = 0.0;
if (str != NULL) /* MIXED EXCITATION */
{
xpulse = x;
xnoise = plus_or_minus_one();
}
}
/* MIXED EXCITATION */
/* The real work -- apply shaping filters to pulse and noise */
if (str != NULL) {
fxpulse = fxnoise = 0.0;
for (k = vs->ME_order - 1; k > 0; k--) {
fxpulse += vs->hpulse[k] * vs->xpulsesig[k];
fxnoise += vs->hnoise[k] * vs->xnoisesig[k];
vs->xpulsesig[k] = vs->xpulsesig[k - 1];
vs->xnoisesig[k] = vs->xnoisesig[k - 1];
}
fxpulse += vs->hpulse[0] * xpulse;
fxnoise += vs->hnoise[0] * xnoise;
vs->xpulsesig[0] = xpulse;
vs->xnoisesig[0] = xnoise;
x = fxpulse + fxnoise; /* excitation is pulse plus noise */
}
if (cg_db->sample_rate == 8000)
/* 8KHz voices are too quiet: this is probably not general */
x *= exp(vs->c[0]) * 2.0;
else
x *= exp(vs->c[0]) * gain;
x = mlsadf(x, vs->c, m, cg_db->mlsa_alpha, vs->pd, vs->d1, vs);
wav->samples[*pos] = (short)x;
*pos += 1;
if (!--i) {
vs->p1 += inc;
for (k = 0; k <= m; k++) vs->c[k] += vs->cinc[k];
i = vs->iprd;
}
}
vs->p1 = p;
memmove(vs->c, vs->cc, sizeof(double) * (m + 1));
return;
}
static double mlsadf(double x, double* b, int m, double a, int pd, double* d, VocoderSetup* vs)
{
vs->ppade = &(vs->pade[pd * (pd + 1) / 2]);
x = mlsadf1(x, b, m, a, pd, d, vs);
x = mlsadf2(x, b, m, a, pd, &d[2 * (pd + 1)], vs);
return (x);
}
static double mlsadf1(double x, double* b, int m, double a, int pd, double* d, VocoderSetup* vs)
{
double v, out = 0.0, *pt, aa;
register int i;
aa = 1 - a * a;
pt = &d[pd + 1];
for (i = pd; i >= 1; i--) {
d[i] = aa * pt[i - 1] + a * d[i];
pt[i] = d[i] * b[1];
v = pt[i] * vs->ppade[i];
x += (1 & i) ? v : -v;
out += v;
}
pt[0] = x;
out += x;
return (out);
}
static double mlsadf2(double x, double* b, int m, double a, int pd, double* d, VocoderSetup* vs)
{
double v, out = 0.0, *pt;
register int i;
pt = &d[pd * (m + 2)];
for (i = pd; i >= 1; i--) {
pt[i] = mlsafir(pt[i - 1], b, m, a, &d[(i - 1) * (m + 2)]);
v = pt[i] * vs->ppade[i];
x += (1 & i) ? v : -v;
out += v;
}
pt[0] = x;
out += x;
return (out);
}
static double mlsafir(double x, double* b, int m, double a, double* d)
{
double y = 0.0;
double aa;
register int i;
aa = 1 - a * a;
d[0] = x;
d[1] = aa * d[0] + a * d[1];
for (i = 2; i <= m; i++) {
d[i] = d[i] + a * (d[i + 1] - d[i - 1]);
y += d[i] * b[i];
}
for (i = m + 1; i > 1; i--)
d[i] = d[i - 1];
return (y);
}
static double nrandom(VocoderSetup* vs)
{
if (vs->sw == 0) {
vs->sw = 1;
do {
vs->r1 = 2.0 * rnd(&vs->next) - 1.0;
vs->r2 = 2.0 * rnd(&vs->next) - 1.0;
vs->s = vs->r1 * vs->r1 + vs->r2 * vs->r2;
} while (vs->s > 1 || vs->s == 0);
vs->s = sqrt(-2 * log(vs->s) / vs->s);
return (vs->r1 * vs->s);
}
else {
vs->sw = 0;
return (vs->r2 * vs->s);
}
}
static double rnd(unsigned long* next)
{
double r;
*next = *next * 1103515245L + 12345;
r = (*next / 65536L) % 32768L;
return (r / RANDMAX);
}
static unsigned long srnd(unsigned long seed)
{
return (seed);
}
/* mc2b : transform mel-cepstrum to MLSA digital fillter coefficients */
static void mc2b(double* mc, double* b, int m, double a)
{
b[m] = mc[m];
for (m--; m >= 0; m--)
b[m] = mc[m] - a * b[m + 1];
return;
}
static double b2en(double* b, int m, double a, VocoderSetup* vs)
{
double en;
int k;
if (vs->o < m) {
if (vs->mc != NULL)
cst_free(vs->mc);
vs->mc = cst_alloc(double, (m + 1) + 2 * vs->irleng);
vs->cep = vs->mc + m + 1;
vs->ir = vs->cep + vs->irleng;
}
b2mc(b, vs->mc, m, a);
freqt(vs->mc, m, vs->cep, vs->irleng - 1, -a, vs);
c2ir(vs->cep, vs->irleng, vs->ir, vs->irleng);
en = 0.0;
for (k = 0; k < vs->irleng; k++)
en += vs->ir[k] * vs->ir[k];
return (en);
}
/* b2bc : transform MLSA digital filter coefficients to mel-cepstrum */
static void b2mc(double* b, double* mc, int m, double a)
{
double d, o;
d = mc[m] = b[m];
for (m--; m >= 0; m--) {
o = b[m] + a * d;
d = b[m];
mc[m] = o;
}
return;
}
/* freqt : frequency transformation */
static void freqt(double* c1, int m1, double* c2, int m2, double a, VocoderSetup* vs)
{
register int i, j;
double b;
if (vs->d == NULL) {
vs->size = m2;
vs->d = cst_alloc(double, vs->size + vs->size + 2);
vs->g = vs->d + vs->size + 1;
}
if (m2 > vs->size) {
cst_free(vs->d);
vs->size = m2;
vs->d = cst_alloc(double, vs->size + vs->size + 2);
vs->g = vs->d + vs->size + 1;
}
b = 1 - a * a;
for (i = 0; i < m2 + 1; i++)
vs->g[i] = 0.0;
for (i = -m1; i <= 0; i++) {
if (0 <= m2)
vs->g[0] = c1[-i] + a * (vs->d[0] = vs->g[0]);
if (1 <= m2)
vs->g[1] = b * vs->d[0] + a * (vs->d[1] = vs->g[1]);
for (j = 2; j <= m2; j++)
vs->g[j] = vs->d[j - 1] + a * ((vs->d[j] = vs->g[j]) - vs->g[j - 1]);
}
memmove(c2, vs->g, sizeof(double) * (m2 + 1));
return;
}
/* c2ir : The minimum phase impulse response is evaluated from the minimum phase cepstrum */
static void c2ir(double* c, int nc, double* h, int leng)
{
register int n, k, upl;
double d;
h[0] = exp(c[0]);
for (n = 1; n < leng; n++) {
d = 0;
upl = (n >= nc) ? nc - 1 : n;
for (k = 1; k <= upl; k++)
d += k * c[k] * h[n - k];
h[n] = d / n;
}
return;
}
static void free_vocoder(VocoderSetup* vs)
{
cst_free(vs->c);
cst_free(vs->mc);
cst_free(vs->d);
vs->c = NULL;
vs->mc = NULL;
vs->d = NULL;
vs->ppade = NULL;
vs->cc = NULL;
vs->cinc = NULL;
vs->d1 = NULL;
vs->g = NULL;
vs->cep = NULL;
vs->ir = NULL;
cst_free(vs->hpulse);
cst_free(vs->hnoise);
cst_free(vs->xpulsesig);
cst_free(vs->xnoisesig);
return;
}
| 25.369983
| 176
| 0.475683
|
Barath-Kannan
|
c7a34f2c452678da6f1895bbabb32ab890ed62bc
| 4,118
|
cpp
|
C++
|
src/test/cpp/filter/levelmatchfiltertest.cpp
|
Blaxar/log4cxxNG
|
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
|
[
"Apache-2.0"
] | null | null | null |
src/test/cpp/filter/levelmatchfiltertest.cpp
|
Blaxar/log4cxxNG
|
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
|
[
"Apache-2.0"
] | null | null | null |
src/test/cpp/filter/levelmatchfiltertest.cpp
|
Blaxar/log4cxxNG
|
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxxNG/filter/levelmatchfilter.h>
#include <log4cxxNG/logger.h>
#include <log4cxxNG/spi/filter.h>
#include <log4cxxNG/spi/loggingevent.h>
#include "../logunit.h"
using namespace log4cxxng;
using namespace log4cxxng::filter;
using namespace log4cxxng::spi;
using namespace log4cxxng::helpers;
/**
* Unit tests for LevelMatchFilter.
*/
LOGUNIT_CLASS(LevelMatchFilterTest)
{
LOGUNIT_TEST_SUITE(LevelMatchFilterTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Check that LevelMatchFilter.decide() returns Filter.ACCEPT when level matches.
*/
void test1()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("info"));
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.DENY
* when level matches and acceptOnMatch = false.
*/
void test2()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("info"));
filter->setAcceptOnMatch(false);
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
* when levelToMatch is unspecified.
*/
void test3()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
* when event level is higher than level to match.
*/
void test4()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("debug"));
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
* when event level is lower than level to match.
*/
void test5()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("warn"));
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(LevelMatchFilterTest);
| 30.279412
| 82
| 0.741136
|
Blaxar
|
c7a54ff53495b66fda4b12f683546f16f01ac85f
| 1,586
|
hpp
|
C++
|
integration/traits.hpp
|
FMeirinhos/gsl-modules
|
a638e90bbcfd2573232cb5d398d04a20f4058adb
|
[
"Unlicense"
] | null | null | null |
integration/traits.hpp
|
FMeirinhos/gsl-modules
|
a638e90bbcfd2573232cb5d398d04a20f4058adb
|
[
"Unlicense"
] | null | null | null |
integration/traits.hpp
|
FMeirinhos/gsl-modules
|
a638e90bbcfd2573232cb5d398d04a20f4058adb
|
[
"Unlicense"
] | null | null | null |
//
// traits.hpp
// gsl-modules
//
// Created by Francisco Meirinhos on 13/01/17.
//
#ifndef traits_hpp
#define traits_hpp
#include <chrono>
#include <tuple>
/*
Stolen from
http://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda
Traits of lambda functions
*/
namespace util {
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
template <typename ReturnType, typename... Args>
struct function_traits<ReturnType (*)(Args...)> {
enum { arity = sizeof...(Args) };
// arity is the number of arguments.
typedef ReturnType result_type;
template <size_t i> struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
// the i-th argument is equivalent to the i-th tuple element of a tuple
// composed of those arguments.
};
};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType (ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
enum { arity = sizeof...(Args) };
// arity is the number of arguments.
typedef ReturnType result_type;
template <size_t i> struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
// the i-th argument is equivalent to the i-th tuple element of a tuple
// composed of those arguments.
};
// See: https://stackoverflow.com/questions/36612596/tuple-to-parameter-pack
using argument_t = std::tuple<Args...>;
};
} // namespace util
#endif /* traits_hpp */
| 26
| 118
| 0.704918
|
FMeirinhos
|
c7a63b24eac32b5cbf21d026b3709e15a3e1021d
| 521
|
cpp
|
C++
|
src/main.cpp
|
Andrewkf5011/s4.3
|
32ba306f7f8e8fd48def706977b950a355a183b0
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Andrewkf5011/s4.3
|
32ba306f7f8e8fd48def706977b950a355a183b0
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Andrewkf5011/s4.3
|
32ba306f7f8e8fd48def706977b950a355a183b0
|
[
"MIT"
] | null | null | null |
#include <mbed.h>
#include <C12832.h>
// Using Arduino pin notation
C12832 lcd(D11, D13, D12, D7, D10);
int main()
{
int j=0;
lcd.cls();
lcd.locate(0,0);
lcd.printf("mbed application shield!");
lcd.locate(0,10);
lcd.printf("char %dx%d : %dx%d pixels",
lcd.columns(), lcd.rows(),
lcd.width(), lcd.height() );
lcd.circle(100, 20, 10, 1);
while(true) {
lcd.locate(0,20);
lcd.printf("Counting : %4d",j);
j++;
wait(1.0);
}
}
| 20.038462
| 43
| 0.512476
|
Andrewkf5011
|
c7a74d9bffc8887b12139ed175f9458077243a0e
| 8,650
|
hpp
|
C++
|
boost/monotonic/storage.hpp
|
cschladetsch/Monotonic
|
ec37c3743862475719fdc8d2c3820fc0ab43c55a
|
[
"BSL-1.0"
] | 12
|
2016-05-22T21:14:27.000Z
|
2021-08-05T21:28:17.000Z
|
boost/monotonic/storage.hpp
|
cschladetsch/Monotonic
|
ec37c3743862475719fdc8d2c3820fc0ab43c55a
|
[
"BSL-1.0"
] | 5
|
2017-02-09T14:24:37.000Z
|
2020-10-31T14:38:45.000Z
|
boost/monotonic/storage.hpp
|
cschladetsch/Monotonic
|
ec37c3743862475719fdc8d2c3820fc0ab43c55a
|
[
"BSL-1.0"
] | 1
|
2022-02-02T20:21:12.000Z
|
2022-02-02T20:21:12.000Z
|
// Copyright (C) 2009-2020 Christian@Schladetsch.com
//
// 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 BOOST_MONOTONIC_STORAGE_HPP
#define BOOST_MONOTONIC_STORAGE_HPP
#include <algorithm>
#include <array>
#include <boost/monotonic/detail/prefix.hpp>
#include <boost/monotonic/fixed_storage.hpp>
#include <boost/monotonic/detail/pool.hpp>
#include <boost/monotonic/detail/link.hpp>
namespace boost
{
namespace monotonic
{
/// storage that spans the stack/heap boundary.
///
/// allocation requests first use inline fixed_storage of InlineSize bytes.
/// once that is exhausted, later requests are serviced from the heap.
///
/// all allocations remain valid at all times.
template <size_t InlineSize, size_t MinHeapIncrement, class Alloc>
struct storage : storage_base
{
static constexpr size_t NumPools = 8;
static constexpr size_t ChunkShift = 4;
static constexpr size_t ChunkSize = 1 << ChunkShift;
typedef storage<InlineSize, MinHeapIncrement, Alloc> This;
typedef Alloc Allocator;
typedef typename Allocator::template rebind<char>::other CharAllocator;
typedef detail::Link<CharAllocator> Link;
typedef typename Allocator::template rebind<Link>::other LinkAllocator;
typedef detail::Pool Pool;
// allocations are always made from the stack, or from a pool the first link in the chain
// typedef std::vector<Link, Alloc> Chain;
typedef std::vector<Link, LinkAllocator> Chain;
typedef std::array<Pool, NumPools> Pools;
typedef fixed_storage<InlineSize> FixedStorage; // the inline fixed-sized storage which may be on the stack
private:
FixedStorage fixed; // the inline fixed-sized storage which may be on the stack
Chain chain; // heap-based storage
Allocator alloc; // allocator for heap-based storage
Pools pools; // pools of same-sized chunks
void create_pools()
{
for (size_t n = 0; n < NumPools; ++n)
{
pools[n] = Pool(n*ChunkSize);
}
}
protected:
template <size_t,size_t,class> friend struct stack;
public:
storage()
{
create_pools();
}
storage(Allocator const &A)
: alloc(A)
{
create_pools();
}
~storage()
{
release();
}
void reset()
{
fixed.reset();
for (Pool &pool : pools)
{
pool.reset();
}
for (Link &link : chain)
{
link.reset();
}
}
void release()
{
reset();
for (Link &link : chain)
{
link.release();
}
chain.clear();
}
public:
void *allocate(size_t num_bytes, size_t alignment = 1)
{
size_t pool = (ChunkSize + num_bytes) >> ChunkShift;
if (pool < NumPools)
{
if (void *ptr = from_pool(pool, num_bytes, alignment))
return ptr;
}
if (void *ptr = from_fixed(num_bytes, alignment))
return ptr;
return from_heap(num_bytes, alignment);
}
private:
friend struct detail::Pool;
void *from_pool(size_t bucket, size_t num_bytes, size_t alignment)
{
return pools[bucket].allocate(*this);
}
void *from_fixed(size_t num_bytes, size_t alignment)
{
return fixed.allocate(num_bytes, alignment);
}
void *from_heap(size_t num_bytes, size_t alignment)
{
if (MinHeapIncrement == 0)
return 0;
if (!chain.empty())
{
if (void *ptr = chain.front().allocate(num_bytes, alignment))
{
return ptr;
}
std::make_heap(chain.begin(), chain.end());
if (void *ptr = chain.front().allocate(num_bytes, alignment))
{
return ptr;
}
}
AddLink((std::max)(MinHeapIncrement, num_bytes*2));
void *ptr = chain.front().allocate(num_bytes, alignment);
if (ptr == 0)
throw std::bad_alloc();
return ptr;
}
public:
void deallocate(void *ptr)
{
// do nothing
}
size_t max_size() const
{
return (std::numeric_limits<size_t>::max)();
}
size_t fixed_remaining() const
{
return fixed.remaining();
}
size_t remaining() const
{
return max_size();
}
size_t fixed_used() const
{
return fixed.used();
}
size_t heap_used() const
{
size_t count = 0;
for (Link const &link : chain)
count += link.used();
return count;
}
size_t used() const
{
return fixed_used() + heap_used();
}
size_t num_links() const
{
return chain.size();
}
// ------------------------------------------------------------------------
template <class Ty>
Ty *uninitialised_create()
{
return reinterpret_cast<Ty *>(allocate_bytes<sizeof(Ty)>());
}
template <class Ty>
void construct(Ty *ptr, const std::true_type& /*is_pod*/)
{
// do nothing
}
template <class Ty>
void construct(Ty *ptr, const std::false_type&)
{
new (ptr) Ty();
}
template <class Ty>
Ty &create()
{
Ty *ptr = uninitialised_create<Ty>();
construct(ptr, std::is_pod<Ty>());
return *ptr;
}
template <class Ty, class A0>
Ty &create(A0 a0)
{
Ty *ptr = uninitialised_create<Ty>();
new (ptr) Ty(a0);
return *ptr;
}
template <class Ty, class A0, class A1>
Ty &create(A0 a0, A1 a1)
{
Ty *ptr = uninitialised_create<Ty>();
new (ptr) Ty(a0, a1);
return *ptr;
}
template <class Ty>
void destroy(Ty &object)
{
object.~Ty();
}
template <class Ty>
void destroy(Ty const &object)
{
destroy(const_cast<Ty &>(object));
}
template <size_t N>
char *allocate_bytes()
{
return allocate_bytes(N, boost::aligned_storage<N>::alignment);
}
char *allocate_bytes(size_t num_bytes, size_t alignment = 1)
{
return reinterpret_cast<char *>(allocate(num_bytes, alignment));
}
size_t get_cursor() const
{
return fixed.get_cursor();
}
void set_cursor(size_t n)
{
fixed.set_cursor(n);
}
private:
void AddLink(size_t size)
{
chain.push_back(Link(alloc, size));
std::make_heap(chain.begin(), chain.end());
}
};
} // namespace monotonic
} // namespace boost
#include <boost/monotonic/detail/postfix.hpp>
#endif // BOOST_MONOTONIC_STORAGE_HPP
//EOF
| 30.244755
| 122
| 0.452023
|
cschladetsch
|
c7a7c12ca1d1623c023f8e49b205ce4514378bfe
| 18,660
|
hpp
|
C++
|
libs/boost_1_72_0/boost/spirit/home/support/detail/endian/endian.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/spirit/home/support/detail/endian/endian.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/spirit/home/support/detail/endian/endian.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
// Boost endian.hpp header file
// -------------------------------------------------------//
// (C) Copyright Darin Adler 2000
// (C) Copyright Beman Dawes 2006, 2009
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See library home page at http://www.boost.org/libs/endian
//--------------------------------------------------------------------------------------//
// Original design developed by Darin Adler based on classes developed by Mark
// Borgerding. Four original class templates were combined into a single endian
// class template by Beman Dawes, who also added the unrolled_byte_loops sign
// partial specialization to correctly extend the sign when cover integer size
// differs from endian representation size.
// TODO: When a compiler supporting constexpr becomes available, try possible
// uses.
#ifndef BOOST_SPIRIT_ENDIAN_HPP
#define BOOST_SPIRIT_ENDIAN_HPP
#if defined(_MSC_VER)
#pragma once
#endif
#ifdef BOOST_ENDIAN_LOG
#include <iostream>
#endif
#if defined(__BORLANDC__) || defined(__CODEGEARC__)
#pragma pack(push, 1)
#endif
#include <boost/config.hpp>
#include <boost/predef/other/endian.h>
#ifndef BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#define BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#endif
#ifndef BOOST_NO_IO_COVER_OPERATORS
#define BOOST_NO_IO_COVER_OPERATORS
#endif
#include <boost/spirit/home/support/detail/endian/cover_operators.hpp>
#undef BOOST_NO_IO_COVER_OPERATORS
#undef BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#include <boost/cstdint.hpp>
#include <boost/spirit/home/support/detail/scoped_enum_emulation.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_signed.hpp>
#include <boost/type_traits/make_unsigned.hpp>
#include <climits>
#include <iosfwd>
#if CHAR_BIT != 8
#error Platforms with CHAR_BIT != 8 are not supported
#endif
#define BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT \
{} // C++03
#if defined(BOOST_ENDIAN_NO_CTORS) || defined(BOOST_ENDIAN_FORCE_PODNESS)
#define BOOST_SPIRIT_ENDIAN_NO_CTORS
#endif
namespace boost {
namespace spirit {
namespace detail {
// Unrolled loops for loading and storing streams of bytes.
template <typename T, std::size_t n_bytes,
bool sign = boost::is_signed<T>::value>
struct unrolled_byte_loops {
typedef unrolled_byte_loops<T, n_bytes - 1, sign> next;
static typename boost::make_unsigned<T>::type
load_big(const unsigned char *bytes) {
return *(bytes - 1) | (next::load_big(bytes - 1) << 8);
}
static typename boost::make_unsigned<T>::type
load_little(const unsigned char *bytes) {
return *bytes | (next::load_little(bytes + 1) << 8);
}
static void store_big(char *bytes, T value) {
*(bytes - 1) = static_cast<char>(value);
next::store_big(bytes - 1, value >> 8);
}
static void store_little(char *bytes, T value) {
*bytes = static_cast<char>(value);
next::store_little(bytes + 1, value >> 8);
}
};
template <typename T> struct unrolled_byte_loops<T, 1, false> {
static T load_big(const unsigned char *bytes) { return *(bytes - 1); }
static T load_little(const unsigned char *bytes) { return *bytes; }
static void store_big(char *bytes, T value) {
*(bytes - 1) = static_cast<char>(value);
}
static void store_little(char *bytes, T value) {
*bytes = static_cast<char>(value);
}
};
template <typename T> struct unrolled_byte_loops<T, 1, true> {
static typename boost::make_unsigned<T>::type
load_big(const unsigned char *bytes) {
return *(bytes - 1);
}
static typename boost::make_unsigned<T>::type
load_little(const unsigned char *bytes) {
return *bytes;
}
static void store_big(char *bytes, T value) {
*(bytes - 1) = static_cast<char>(value);
}
static void store_little(char *bytes, T value) {
*bytes = static_cast<char>(value);
}
};
template <typename T, std::size_t n_bytes>
inline T load_big_endian(const void *bytes) {
return static_cast<T>(unrolled_byte_loops<T, n_bytes>::load_big(
static_cast<const unsigned char *>(bytes) + n_bytes));
}
template <> inline float load_big_endian<float, 4>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
b += 3;
float value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*v++ = *b--;
}
return value;
}
template <> inline double load_big_endian<double, 8>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
b += 7;
double value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*v++ = *b--;
}
return value;
}
template <typename T, std::size_t n_bytes>
inline T load_little_endian(const void *bytes) {
return static_cast<T>(unrolled_byte_loops<T, n_bytes>::load_little(
static_cast<const unsigned char *>(bytes)));
}
template <> inline float load_little_endian<float, 4>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
float value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*v++ = *b++;
}
return value;
}
template <> inline double load_little_endian<double, 8>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
double value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*v++ = *b++;
}
return value;
}
template <typename T, std::size_t n_bytes>
inline void store_big_endian(void *bytes, T value) {
unrolled_byte_loops<T, n_bytes>::store_big(
static_cast<char *>(bytes) + n_bytes, value);
}
template <> inline void store_big_endian<float, 4>(void *bytes, float value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
b += 3;
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*b-- = *v++;
}
}
template <> inline void store_big_endian<double, 8>(void *bytes, double value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
b += 7;
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*b-- = *v++;
}
}
template <typename T, std::size_t n_bytes>
inline void store_little_endian(void *bytes, T value) {
unrolled_byte_loops<T, n_bytes>::store_little(static_cast<char *>(bytes),
value);
}
template <>
inline void store_little_endian<float, 4>(void *bytes, float value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*b++ = *v++;
}
}
template <>
inline void store_little_endian<double, 8>(void *bytes, double value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*b++ = *v++;
}
}
} // namespace detail
namespace endian {
#ifdef BOOST_ENDIAN_LOG
bool endian_log(true);
#endif
// endian class template and specializations
// ---------------------------------------//
BOOST_SCOPED_ENUM_START(endianness){big, little, native};
BOOST_SCOPED_ENUM_END
BOOST_SCOPED_ENUM_START(alignment){unaligned, aligned};
BOOST_SCOPED_ENUM_END
template <BOOST_SCOPED_ENUM(endianness) E, typename T, std::size_t n_bits,
BOOST_SCOPED_ENUM(alignment) A = alignment::unaligned>
class endian;
// Specializations that represent unaligned bytes.
// Taking an integer type as a parameter provides a nice way to pass both
// the size and signedness of the desired integer and get the appropriate
// corresponding integer type for the interface.
// unaligned big endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::big, T, n_bits, alignment::unaligned>
: cover_operators<endian<endianness::big, T, n_bits>, T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT explicit endian(T val) {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "big, unaligned, " << n_bits << "-bits, construct(" << val
<< ")\n";
#endif
detail::store_big_endian<T, n_bits / 8>(m_value, val);
}
#endif
endian &operator=(T val) {
detail::store_big_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "big, unaligned, " << n_bits << "-bits, convert("
<< detail::load_big_endian<T, n_bits / 8>(m_value) << ")\n";
#endif
return detail::load_big_endian<T, n_bits / 8>(m_value);
}
private:
char m_value[n_bits / 8];
};
// unaligned little endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::little, T, n_bits, alignment::unaligned>
: cover_operators<endian<endianness::little, T, n_bits>, T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT explicit endian(T val) {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "little, unaligned, " << n_bits << "-bits, construct(" << val
<< ")\n";
#endif
detail::store_little_endian<T, n_bits / 8>(m_value, val);
}
#endif
endian &operator=(T val) {
detail::store_little_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "little, unaligned, " << n_bits << "-bits, convert("
<< detail::load_little_endian<T, n_bits / 8>(m_value) << ")\n";
#endif
return detail::load_little_endian<T, n_bits / 8>(m_value);
}
private:
char m_value[n_bits / 8];
};
// unaligned native endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::native, T, n_bits, alignment::unaligned>
: cover_operators<endian<endianness::native, T, n_bits>, T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#if BOOST_ENDIAN_BIG_BYTE
explicit endian(T val) {
detail::store_big_endian<T, n_bits / 8>(m_value, val);
}
#else
explicit endian(T val) {
detail::store_little_endian<T, n_bits / 8>(m_value, val);
}
#endif
#endif
#if BOOST_ENDIAN_BIG_BYTE
endian &operator=(T val) {
detail::store_big_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const { return detail::load_big_endian<T, n_bits / 8>(m_value); }
#else
endian &operator=(T val) {
detail::store_little_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const {
return detail::load_little_endian<T, n_bits / 8>(m_value);
}
#endif
private:
char m_value[n_bits / 8];
};
// Specializations that mimic built-in integer types.
// These typically have the same alignment as the underlying types.
// aligned big endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::big, T, n_bits, alignment::aligned>
: cover_operators<endian<endianness::big, T, n_bits, alignment::aligned>,
T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
BOOST_STATIC_ASSERT(sizeof(T) == n_bits / 8);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#if BOOST_ENDIAN_BIG_BYTE
endian(T val)
: m_value(val) {
}
#else
explicit endian(T val) {
detail::store_big_endian<T, sizeof(T)>(&m_value, val);
}
#endif
#endif
#if BOOST_ENDIAN_BIG_BYTE
endian &operator=(T val) {
m_value = val;
return *this;
}
operator T() const { return m_value; }
#else
endian &operator=(T val) {
detail::store_big_endian<T, sizeof(T)>(&m_value, val);
return *this;
}
operator T() const { return detail::load_big_endian<T, sizeof(T)>(&m_value); }
#endif
private:
T m_value;
};
// aligned little endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::little, T, n_bits, alignment::aligned>
: cover_operators<endian<endianness::little, T, n_bits, alignment::aligned>,
T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
BOOST_STATIC_ASSERT(sizeof(T) == n_bits / 8);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#if BOOST_ENDIAN_LITTLE_BYTE
endian(T val)
: m_value(val) {
}
#else
explicit endian(T val) {
detail::store_little_endian<T, sizeof(T)>(&m_value, val);
}
#endif
#endif
#if BOOST_ENDIAN_LITTLE_BYTE
endian &operator=(T val) {
m_value = val;
return *this;
}
operator T() const { return m_value; }
#else
endian &operator=(T val) {
detail::store_little_endian<T, sizeof(T)>(&m_value, val);
return *this;
}
operator T() const {
return detail::load_little_endian<T, sizeof(T)>(&m_value);
}
#endif
private:
T m_value;
};
// naming convention typedefs
// ------------------------------------------------------//
// unaligned big endian signed integer types
typedef endian<endianness::big, int_least8_t, 8> big8_t;
typedef endian<endianness::big, int_least16_t, 16> big16_t;
typedef endian<endianness::big, int_least32_t, 24> big24_t;
typedef endian<endianness::big, int_least32_t, 32> big32_t;
typedef endian<endianness::big, int_least64_t, 40> big40_t;
typedef endian<endianness::big, int_least64_t, 48> big48_t;
typedef endian<endianness::big, int_least64_t, 56> big56_t;
typedef endian<endianness::big, int_least64_t, 64> big64_t;
// unaligned big endian unsigned integer types
typedef endian<endianness::big, uint_least8_t, 8> ubig8_t;
typedef endian<endianness::big, uint_least16_t, 16> ubig16_t;
typedef endian<endianness::big, uint_least32_t, 24> ubig24_t;
typedef endian<endianness::big, uint_least32_t, 32> ubig32_t;
typedef endian<endianness::big, uint_least64_t, 40> ubig40_t;
typedef endian<endianness::big, uint_least64_t, 48> ubig48_t;
typedef endian<endianness::big, uint_least64_t, 56> ubig56_t;
typedef endian<endianness::big, uint_least64_t, 64> ubig64_t;
// unaligned little endian signed integer types
typedef endian<endianness::little, int_least8_t, 8> little8_t;
typedef endian<endianness::little, int_least16_t, 16> little16_t;
typedef endian<endianness::little, int_least32_t, 24> little24_t;
typedef endian<endianness::little, int_least32_t, 32> little32_t;
typedef endian<endianness::little, int_least64_t, 40> little40_t;
typedef endian<endianness::little, int_least64_t, 48> little48_t;
typedef endian<endianness::little, int_least64_t, 56> little56_t;
typedef endian<endianness::little, int_least64_t, 64> little64_t;
// unaligned little endian unsigned integer types
typedef endian<endianness::little, uint_least8_t, 8> ulittle8_t;
typedef endian<endianness::little, uint_least16_t, 16> ulittle16_t;
typedef endian<endianness::little, uint_least32_t, 24> ulittle24_t;
typedef endian<endianness::little, uint_least32_t, 32> ulittle32_t;
typedef endian<endianness::little, uint_least64_t, 40> ulittle40_t;
typedef endian<endianness::little, uint_least64_t, 48> ulittle48_t;
typedef endian<endianness::little, uint_least64_t, 56> ulittle56_t;
typedef endian<endianness::little, uint_least64_t, 64> ulittle64_t;
// unaligned native endian signed integer types
typedef endian<endianness::native, int_least8_t, 8> native8_t;
typedef endian<endianness::native, int_least16_t, 16> native16_t;
typedef endian<endianness::native, int_least32_t, 24> native24_t;
typedef endian<endianness::native, int_least32_t, 32> native32_t;
typedef endian<endianness::native, int_least64_t, 40> native40_t;
typedef endian<endianness::native, int_least64_t, 48> native48_t;
typedef endian<endianness::native, int_least64_t, 56> native56_t;
typedef endian<endianness::native, int_least64_t, 64> native64_t;
// unaligned native endian unsigned integer types
typedef endian<endianness::native, uint_least8_t, 8> unative8_t;
typedef endian<endianness::native, uint_least16_t, 16> unative16_t;
typedef endian<endianness::native, uint_least32_t, 24> unative24_t;
typedef endian<endianness::native, uint_least32_t, 32> unative32_t;
typedef endian<endianness::native, uint_least64_t, 40> unative40_t;
typedef endian<endianness::native, uint_least64_t, 48> unative48_t;
typedef endian<endianness::native, uint_least64_t, 56> unative56_t;
typedef endian<endianness::native, uint_least64_t, 64> unative64_t;
// These types only present if platform has exact size integers:
// aligned big endian signed integer types
// aligned big endian unsigned integer types
// aligned little endian signed integer types
// aligned little endian unsigned integer types
// aligned native endian typedefs are not provided because
// <cstdint> types are superior for this use case
#ifdef INT16_MAX
typedef endian<endianness::big, int16_t, 16, alignment::aligned>
aligned_big16_t;
typedef endian<endianness::big, uint16_t, 16, alignment::aligned>
aligned_ubig16_t;
typedef endian<endianness::little, int16_t, 16, alignment::aligned>
aligned_little16_t;
typedef endian<endianness::little, uint16_t, 16, alignment::aligned>
aligned_ulittle16_t;
#endif
#ifdef INT32_MAX
typedef endian<endianness::big, int32_t, 32, alignment::aligned>
aligned_big32_t;
typedef endian<endianness::big, uint32_t, 32, alignment::aligned>
aligned_ubig32_t;
typedef endian<endianness::little, int32_t, 32, alignment::aligned>
aligned_little32_t;
typedef endian<endianness::little, uint32_t, 32, alignment::aligned>
aligned_ulittle32_t;
#endif
#ifdef INT64_MAX
typedef endian<endianness::big, int64_t, 64, alignment::aligned>
aligned_big64_t;
typedef endian<endianness::big, uint64_t, 64, alignment::aligned>
aligned_ubig64_t;
typedef endian<endianness::little, int64_t, 64, alignment::aligned>
aligned_little64_t;
typedef endian<endianness::little, uint64_t, 64, alignment::aligned>
aligned_ulittle64_t;
#endif
} // namespace endian
} // namespace spirit
} // namespace boost
#undef BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#undef BOOST_SPIRIT_ENDIAN_NO_CTORS
#if defined(__BORLANDC__) || defined(__CODEGEARC__)
#pragma pack(pop)
#endif
#endif // BOOST_SPIRIT_ENDIAN_HPP
| 32.11704
| 90
| 0.710021
|
henrywarhurst
|
c7aa1aad149753749241a39cced2f20c736c6a8d
| 1,839
|
cpp
|
C++
|
TESTS/mbed_drivers/timeout/main.cpp
|
nachocarballeda/mbed-os
|
fc1836545dcc2fc86f03b01292b62bf2089f67c3
|
[
"Apache-2.0"
] | 3
|
2018-03-13T13:42:12.000Z
|
2019-05-17T11:48:04.000Z
|
TESTS/mbed_drivers/timeout/main.cpp
|
nachocarballeda/mbed-os
|
fc1836545dcc2fc86f03b01292b62bf2089f67c3
|
[
"Apache-2.0"
] | 1
|
2017-02-20T10:48:02.000Z
|
2017-02-21T11:34:16.000Z
|
TESTS/mbed_drivers/timeout/main.cpp
|
nachocarballeda/mbed-os
|
fc1836545dcc2fc86f03b01292b62bf2089f67c3
|
[
"Apache-2.0"
] | 8
|
2018-01-28T02:23:18.000Z
|
2021-02-26T01:15:55.000Z
|
/*
* Copyright (c) 2013-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "utest/utest.h"
using namespace utest::v1;
Timeout timeout;
DigitalOut led(LED1);
volatile int ticker_count = 0;
volatile bool print_tick = false;
static const int total_ticks = 10;
const int ONE_SECOND_US = 1000000;
void send_kv_tick() {
if (ticker_count <= total_ticks) {
timeout.attach_us(send_kv_tick, ONE_SECOND_US);
print_tick = true;
}
}
void wait_and_print() {
while(ticker_count <= total_ticks) {
if (print_tick) {
print_tick = false;
greentea_send_kv("tick", ticker_count++);
led = !led;
}
}
}
void test_case_ticker() {
timeout.attach_us(send_kv_tick, ONE_SECOND_US);
wait_and_print();
}
// Test cases
Case cases[] = {
Case("Timers: toggle on/off", test_case_ticker),
};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases) {
GREENTEA_SETUP(total_ticks + 5, "timing_drift_auto");
return greentea_test_setup_handler(number_of_cases);
}
Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);
int main() {
Harness::run(specification);
}
| 27.044118
| 88
| 0.710169
|
nachocarballeda
|
c7ab178e0ff3dfece38b430bb52c93b657ef8e5c
| 9,378
|
cc
|
C++
|
ithwrapper/ith/cli/pipe.cc
|
wareya/chiitrans
|
7a392a304e6315cb4ecf836804512bb972090e8b
|
[
"Apache-2.0"
] | 71
|
2015-01-06T03:06:25.000Z
|
2022-03-02T17:47:28.000Z
|
ithwrapper/ith/cli/pipe.cc
|
holemcross/chiitrans
|
c5e9aba5f555b1f81792d1dd4864b7efeb12f823
|
[
"Apache-2.0"
] | 7
|
2015-01-14T15:08:41.000Z
|
2018-11-20T18:18:15.000Z
|
ithwrapper/ith/cli/pipe.cc
|
holemcross/chiitrans
|
c5e9aba5f555b1f81792d1dd4864b7efeb12f823
|
[
"Apache-2.0"
] | 35
|
2015-05-24T02:16:17.000Z
|
2022-03-23T18:52:56.000Z
|
// pipe.cc
// 8/24/2013 jichi
// Branch: ITH_DLL/pipe.cpp, rev 66
// 8/24/2013 TODO: Clean up this file
#ifdef _MSC_VER
# pragma warning (disable:4100) // C4100: unreference formal parameter
#endif // _MSC_VER
#include "cli_p.h"
#include "ith/common/defs.h"
//#include "ith/common/growl.h"
#include "ith/sys/sys.h"
#include "cc/ccmacro.h"
//#include <ITH\AVL.h>
//#include <ITH\ntdll.h>
WCHAR mutex[] = ITH_GRANTPIPE_MUTEX;
WCHAR exist[] = ITH_PIPEEXISTS_EVENT;
WCHAR detach_mutex[0x20];
//WCHAR write_event[0x20];
//WCHAR engine_event[0x20];
//WCHAR recv_pipe[] = L"\\??\\pipe\\ITH_PIPE";
//WCHAR command[] = L"\\??\\pipe\\ITH_COMMAND";
wchar_t recv_pipe[] = ITH_TEXT_PIPE;
wchar_t command[] = ITH_COMMAND_PIPE;
LARGE_INTEGER wait_time={-100*10000,-1};
LARGE_INTEGER sleep_time={-20*10000,-1};
DWORD engine_type;
DWORD engine_base;
DWORD module_base;
HANDLE hPipe,
hCommand,
hDetach; //,hLose;
IdentifyEngineFun IdentifyEngine;
InsertHookFun InsertHook;
InsertDynamicHookFun InsertDynamicHook;
bool hook_inserted=0;
// jichi 9/28/2013: protect pipe on wine
// Put the definition in this file so that it might be inlined
void CliUnlockPipe()
{
if (IthIsWine())
IthReleaseMutex(::hmMutex);
}
void CliLockPipe()
{
if (IthIsWine()) {
const LONGLONG timeout = -50000000; // in nanoseconds = 5 seconds
NtWaitForSingleObject(hmMutex, 0, (PLARGE_INTEGER)&timeout);
}
}
HANDLE IthOpenPipe(LPWSTR name, ACCESS_MASK direction)
{
UNICODE_STRING us;
RtlInitUnicodeString(&us,name);
SECURITY_DESCRIPTOR sd = {1};
OBJECT_ATTRIBUTES oa = {sizeof(oa), 0, &us, OBJ_CASE_INSENSITIVE, &sd, 0};
HANDLE hFile;
IO_STATUS_BLOCK isb;
if (NT_SUCCESS(NtCreateFile(&hFile, direction, &oa, &isb, 0, 0, FILE_SHARE_READ, FILE_OPEN, 0, 0, 0)))
return hFile;
else
return INVALID_HANDLE_VALUE;
}
DWORD WINAPI WaitForPipe(LPVOID lpThreadParameter) // Dynamically detect ITH main module status.
{
CC_UNUSED(lpThreadParameter);
int i;
TextHook *man;
struct {
DWORD pid;
TextHook *man;
DWORD module;
DWORD engine;
} u;
HANDLE hMutex,
hPipeExist;
//swprintf(engine_event,L"ITH_ENGINE_%d",current_process_id);
swprintf(detach_mutex, ITH_DETACH_MUTEX_ L"%d",current_process_id);
//swprintf(lose_event,L"ITH_LOSEPIPE_%d",current_process_id);
//hEngine=IthCreateEvent(engine_event);
//NtWaitForSingleObject(hEngine,0,0);
//NtClose(hEngine);
while (engine_base == 0)
NtDelayExecution(0, &wait_time);
//LoadEngine(L"ITH_Engine.dll");
u.module = module_base;
u.pid = current_process_id;
u.man = hookman;
u.engine = engine_base;
hPipeExist = IthOpenEvent(exist);
IO_STATUS_BLOCK ios;
//hLose=IthCreateEvent(lose_event,0,0);
if (hPipeExist != INVALID_HANDLE_VALUE)
while (running) {
hPipe = INVALID_HANDLE_VALUE;
hCommand = INVALID_HANDLE_VALUE;
while (NtWaitForSingleObject(hPipeExist,0,&wait_time) == WAIT_TIMEOUT)
if (!running)
goto _release;
hMutex = IthCreateMutex(mutex,0);
NtWaitForSingleObject(hMutex,0,0);
while (hPipe == INVALID_HANDLE_VALUE||
hCommand == INVALID_HANDLE_VALUE) {
NtDelayExecution(0, &sleep_time);
if (hPipe == INVALID_HANDLE_VALUE)
hPipe = IthOpenPipe(recv_pipe, GENERIC_WRITE);
if (hCommand == INVALID_HANDLE_VALUE)
hCommand = IthOpenPipe(command, GENERIC_READ);
}
//NtClearEvent(hLose);
CliLockPipe();
NtWriteFile(hPipe, 0, 0, 0, &ios, &u, 16, 0, 0);
CliUnlockPipe();
live = true;
for (man = hookman, i = 0; i < current_hook; man++)
if (man->RecoverHook()) // jichi 9/27/2013: This is the place where built-in hooks like TextOutA are inserted
i++;
//OutputConsole(dll_name);
//OutputConsole(L"Pipe connected.");
//OutputDWORD(tree->Count());
NtReleaseMutant(hMutex,0);
NtClose(hMutex);
if (!hook_inserted && engine_base) {
hook_inserted = true;
IdentifyEngine();
}
hDetach = IthCreateMutex(detach_mutex,1);
while (running && NtWaitForSingleObject(hPipeExist,0,&sleep_time)==WAIT_OBJECT_0)
NtDelayExecution(0,&sleep_time);
live=false;
for (man = hookman, i = 0; i < current_hook; man++)
if (man->RemoveHook())
i++;
if (!running) {
IthCoolDown(); // jichi 9/28/2013: Use cooldown instead of lock pipe to revent from hanging on exit
//CliLockPipe();
NtWriteFile(hPipe,0,0,0,&ios, man,4,0,0);
//CliUnlockPipe();
IthReleaseMutex(hDetach);
}
NtClose(hDetach);
NtClose(hPipe);
}
_release:
//NtClose(hLose);
NtClose(hPipeExist);
return 0;
}
DWORD WINAPI CommandPipe(LPVOID lpThreadParameter)
{
CC_UNUSED(lpThreadParameter);
DWORD command;
BYTE buff[0x400] = {};
HANDLE hPipeExist;
hPipeExist = IthOpenEvent(exist);
IO_STATUS_BLOCK ios={};
if (hPipeExist!=INVALID_HANDLE_VALUE)
while (running) {
while (!live) {
if (!running)
goto _detach;
NtDelayExecution(0, &sleep_time);
}
// jichi 9/27/2013: Why 0x200 not 0x400? wchar_t?
switch (NtReadFile(hCommand, 0, 0, 0, &ios, buff, 0x200, 0, 0)) {
case STATUS_PIPE_BROKEN:
case STATUS_PIPE_DISCONNECTED:
NtClearEvent(hPipeExist);
continue;
case STATUS_PENDING:
NtWaitForSingleObject(hCommand, 0, 0);
switch (ios.Status) {
case STATUS_PIPE_BROKEN:
case STATUS_PIPE_DISCONNECTED:
NtClearEvent(hPipeExist);
continue;
case 0: break;
default:
if (NtWaitForSingleObject(hDetach, 0, &wait_time) == WAIT_OBJECT_0)
goto _detach;
}
}
if (ios.uInformation && live) {
command = *(DWORD *)buff;
switch(command) {
case IHF_COMMAND_NEW_HOOK:
//IthBreak();
buff[ios.uInformation] = 0;
buff[ios.uInformation + 1] = 0;
NewHook(*(HookParam *)(buff + 4), (LPWSTR)(buff + 4 + sizeof(HookParam)), 0);
break;
case IHF_COMMAND_REMOVE_HOOK:
{
DWORD rm_addr = *(DWORD *)(buff+4);
HANDLE hRemoved = IthOpenEvent(ITH_REMOVEHOOK_EVENT);
TextHook *in = hookman;
for (int i = 0; i < current_hook; in++) {
if (in->Address()) i++;
if (in->Address() == rm_addr) break;
}
if (in->Address())
in->ClearHook();
IthSetEvent(hRemoved);
NtClose(hRemoved);
} break;
case IHF_COMMAND_MODIFY_HOOK:
{
DWORD rm_addr = *(DWORD *)(buff + 4);
HANDLE hModify = IthOpenEvent(ITH_MODIFYHOOK_EVENT);
TextHook *in = hookman;
for (int i = 0; i < current_hook; in++) {
if (in->Address()) i++;
if (in->Address() == rm_addr) break;
}
if (in->Address())
in->ModifyHook(*(HookParam *)(buff + 4));
IthSetEvent(hModify);
NtClose(hModify);
} break;
case IHF_COMMAND_DETACH:
running = false;
live = false;
goto _detach;
default: ;
}
}
}
_detach:
NtClose(hPipeExist);
NtClose(hCommand);
return 0;
}
extern "C" {
DWORD IHFAPI OutputConsole(LPWSTR)
{
// jichi 9/28/2013: I do not need this ><
//if (live)
//if (str) {
// int t, len, sum;
// BYTE buffer[0x80];
// BYTE *buff;
// len = wcslen(str) << 1;
// t = swprintf((LPWSTR)(buffer + 8),L"%d: ",current_process_id) << 1;
// sum = len + t + 8;
// if (sum > 0x80) {
// buff = new BYTE[sum];
// memset(buff, 0, sum); // jichi 9/25/2013: zero memory
// memcpy(buff + 8, buffer + 8, t);
// }
// else
// buff = buffer;
// *(DWORD *)buff = IHF_NOTIFICATION; //cmd
// *(DWORD *)(buff + 4) = IHF_NOTIFICATION_TEXT; //console
// memcpy(buff + t + 8, str, len);
// IO_STATUS_BLOCK ios;
// NtWriteFile(hPipe,0,0,0,&ios,buff,sum,0,0);
// if (buff != buffer)
// delete[] buff;
// return len;
//}
return 0;
}
//DWORD IHFAPI OutputDWORD(DWORD d)
//{
// WCHAR str[0x10];
// swprintf(str,L"%.8X",d);
// OutputConsole(str);
// return 0;
//}
//DWORD IHFAPI OutputRegister(DWORD *base)
//{
// WCHAR str[0x40];
// swprintf(str,L"EAX:%.8X",base[0]);
// OutputConsole(str);
// swprintf(str,L"ECX:%.8X",base[-1]);
// OutputConsole(str);
// swprintf(str,L"EDX:%.8X",base[-2]);
// OutputConsole(str);
// swprintf(str,L"EBX:%.8X",base[-3]);
// OutputConsole(str);
// swprintf(str,L"ESP:%.8X",base[-4]);
// OutputConsole(str);
// swprintf(str,L"EBP:%.8X",base[-5]);
// OutputConsole(str);
// swprintf(str,L"ESI:%.8X",base[-6]);
// OutputConsole(str);
// swprintf(str,L"EDI:%.8X",base[-7]);
// OutputConsole(str);
// return 0;
//}
DWORD IHFAPI RegisterEngineModule(DWORD base, DWORD idEngine, DWORD dnHook)
{
IdentifyEngine = (IdentifyEngineFun)idEngine;
InsertDynamicHook = (InsertDynamicHookFun)dnHook;
engine_base = base;
return 0;
}
DWORD IHFAPI NotifyHookInsert(DWORD addr)
{
if (live) {
BYTE buffer[0x10];
*(DWORD*)buffer=IHF_NOTIFICATION;
*(DWORD*)(buffer+4)=IHF_NOTIFICATION_NEWHOOK;
*(DWORD*)(buffer+8)=addr;
*(DWORD*)(buffer+0xc)=0;
IO_STATUS_BLOCK ios;
CliLockPipe();
NtWriteFile(hPipe,0,0,0,&ios,buffer,0x10,0,0);
CliUnlockPipe();
}
return 0;
}
}
// EOF
| 28.591463
| 115
| 0.621881
|
wareya
|
c7ac381b26bd3c4eff54f9011e245c0429a1629e
| 3,797
|
cpp
|
C++
|
android-31/android/renderscript/Matrix4f.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/android/renderscript/Matrix4f.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/android/renderscript/Matrix4f.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../JFloatArray.hpp"
#include "./Matrix4f.hpp"
namespace android::renderscript
{
// Fields
// QJniObject forward
Matrix4f::Matrix4f(QJniObject obj) : JObject(obj) {}
// Constructors
Matrix4f::Matrix4f()
: JObject(
"android.renderscript.Matrix4f",
"()V"
) {}
Matrix4f::Matrix4f(JFloatArray arg0)
: JObject(
"android.renderscript.Matrix4f",
"([F)V",
arg0.object<jfloatArray>()
) {}
// Methods
jfloat Matrix4f::get(jint arg0, jint arg1) const
{
return callMethod<jfloat>(
"get",
"(II)F",
arg0,
arg1
);
}
JFloatArray Matrix4f::getArray() const
{
return callObjectMethod(
"getArray",
"()[F"
);
}
jboolean Matrix4f::inverse() const
{
return callMethod<jboolean>(
"inverse",
"()Z"
);
}
jboolean Matrix4f::inverseTranspose() const
{
return callMethod<jboolean>(
"inverseTranspose",
"()Z"
);
}
void Matrix4f::load(android::renderscript::Matrix4f arg0) const
{
callMethod<void>(
"load",
"(Landroid/renderscript/Matrix4f;)V",
arg0.object()
);
}
void Matrix4f::loadFrustum(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3, jfloat arg4, jfloat arg5) const
{
callMethod<void>(
"loadFrustum",
"(FFFFFF)V",
arg0,
arg1,
arg2,
arg3,
arg4,
arg5
);
}
void Matrix4f::loadIdentity() const
{
callMethod<void>(
"loadIdentity",
"()V"
);
}
void Matrix4f::loadMultiply(android::renderscript::Matrix4f arg0, android::renderscript::Matrix4f arg1) const
{
callMethod<void>(
"loadMultiply",
"(Landroid/renderscript/Matrix4f;Landroid/renderscript/Matrix4f;)V",
arg0.object(),
arg1.object()
);
}
void Matrix4f::loadOrtho(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3, jfloat arg4, jfloat arg5) const
{
callMethod<void>(
"loadOrtho",
"(FFFFFF)V",
arg0,
arg1,
arg2,
arg3,
arg4,
arg5
);
}
void Matrix4f::loadOrthoWindow(jint arg0, jint arg1) const
{
callMethod<void>(
"loadOrthoWindow",
"(II)V",
arg0,
arg1
);
}
void Matrix4f::loadPerspective(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const
{
callMethod<void>(
"loadPerspective",
"(FFFF)V",
arg0,
arg1,
arg2,
arg3
);
}
void Matrix4f::loadProjectionNormalized(jint arg0, jint arg1) const
{
callMethod<void>(
"loadProjectionNormalized",
"(II)V",
arg0,
arg1
);
}
void Matrix4f::loadRotate(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const
{
callMethod<void>(
"loadRotate",
"(FFFF)V",
arg0,
arg1,
arg2,
arg3
);
}
void Matrix4f::loadScale(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"loadScale",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::loadTranslate(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"loadTranslate",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::multiply(android::renderscript::Matrix4f arg0) const
{
callMethod<void>(
"multiply",
"(Landroid/renderscript/Matrix4f;)V",
arg0.object()
);
}
void Matrix4f::rotate(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const
{
callMethod<void>(
"rotate",
"(FFFF)V",
arg0,
arg1,
arg2,
arg3
);
}
void Matrix4f::scale(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"scale",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::set(jint arg0, jint arg1, jfloat arg2) const
{
callMethod<void>(
"set",
"(IIF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::translate(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"translate",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::transpose() const
{
callMethod<void>(
"transpose",
"()V"
);
}
} // namespace android::renderscript
| 17.026906
| 111
| 0.629708
|
YJBeetle
|
c7acf1ea6fe29506547e60ad88931fc236be01e8
| 542
|
cc
|
C++
|
Code/0003-longest-substring-without-repeating-characters.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | 2
|
2019-12-06T14:08:57.000Z
|
2020-01-15T15:25:32.000Z
|
Code/0003-longest-substring-without-repeating-characters.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | 1
|
2020-01-15T16:29:16.000Z
|
2020-01-26T12:40:13.000Z
|
Code/0003-longest-substring-without-repeating-characters.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
if (n < 2) {
return n;
}
int result = 1;
int begin = 0;
unordered_map<char, int> m;
for (int i = 0; i < n; i++) {
if (m.find(s[i]) != m.end() && m[s[i]] >= begin) {
result = max(result, i - begin);
begin = m[s[i]] + 1;
}
m[s[i]] = i;
}
result = max(result, n - begin);
return result;
}
};
| 25.809524
| 62
| 0.394834
|
SMartQi
|
c7adf89a0c49e30a3ce0006128a101253326e2ec
| 6,061
|
hpp
|
C++
|
include/GlobalNamespace/BeatmapDataLoader_SpecialEventsFilter.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/BeatmapDataLoader_SpecialEventsFilter.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/BeatmapDataLoader_SpecialEventsFilter.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"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: BeatmapDataLoader
#include "GlobalNamespace/BeatmapDataLoader.hpp"
// Including type: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType
#include "BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData.hpp"
// Including type: BeatmapSaveDataVersion3.BeatmapSaveData
#include "BeatmapSaveDataVersion3/BeatmapSaveData.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"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: HashSet`1<T>
template<typename T>
class HashSet_1;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: EnvironmentKeywords
class EnvironmentKeywords;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter*, "", "BeatmapDataLoader/SpecialEventsFilter");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: BeatmapDataLoader/SpecialEventsFilter
// [TokenAttribute] Offset: FFFFFFFF
class BeatmapDataLoader::SpecialEventsFilter : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private readonly System.Collections.Generic.HashSet`1<BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType> _eventTypesToFilter
// Size: 0x8
// Offset: 0x10
::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>* eventTypesToFilter;
// Field size check
static_assert(sizeof(::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*) == 0x8);
public:
// Creating conversion operator: operator ::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*
constexpr operator ::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*() const noexcept {
return eventTypesToFilter;
}
// Get instance field reference: private readonly System.Collections.Generic.HashSet`1<BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType> _eventTypesToFilter
::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*& dyn__eventTypesToFilter();
// public System.Void .ctor(BeatmapSaveDataVersion3.BeatmapSaveData/BeatmapSaveDataVersion3.BasicEventTypesWithKeywords basicEventTypesWithKeywords, EnvironmentKeywords environmentKeywords)
// Offset: 0x1369D1C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BeatmapDataLoader::SpecialEventsFilter* New_ctor(::BeatmapSaveDataVersion3::BeatmapSaveData::BasicEventTypesWithKeywords* basicEventTypesWithKeywords, ::GlobalNamespace::EnvironmentKeywords* environmentKeywords) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BeatmapDataLoader::SpecialEventsFilter*, creationType>(basicEventTypesWithKeywords, environmentKeywords)));
}
// public System.Boolean IsEventValid(BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType basicBeatmapEventType)
// Offset: 0x136ACE4
bool IsEventValid(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType basicBeatmapEventType);
}; // BeatmapDataLoader/SpecialEventsFilter
#pragma pack(pop)
static check_size<sizeof(BeatmapDataLoader::SpecialEventsFilter), 16 + sizeof(::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*)> __GlobalNamespace_BeatmapDataLoader_SpecialEventsFilterSizeCheck;
static_assert(sizeof(BeatmapDataLoader::SpecialEventsFilter) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::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: GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::IsEventValid
// Il2CppName: IsEventValid
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::*)(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType)>(&GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::IsEventValid)> {
static const MethodInfo* get() {
static auto* basicBeatmapEventType = &::il2cpp_utils::GetClassFromName("BeatmapSaveDataVersion2_6_0AndEarlier", "BeatmapSaveData/BeatmapEventType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter*), "IsEventValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{basicBeatmapEventType});
}
};
| 64.478723
| 286
| 0.804983
|
RedBrumbler
|
c7af199c5ce7c8ebff0e74ee021e01781b89afca
| 811
|
cc
|
C++
|
1663/5028028_AC_125MS_452K.cc
|
twilightgod/twilight-poj-solution
|
3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82
|
[
"Apache-2.0"
] | 21
|
2015-05-26T10:18:12.000Z
|
2021-06-01T09:39:47.000Z
|
1663/5028028_AC_125MS_452K.cc
|
twilightgod/twilight-poj-solution
|
3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82
|
[
"Apache-2.0"
] | null | null | null |
1663/5028028_AC_125MS_452K.cc
|
twilightgod/twilight-poj-solution
|
3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82
|
[
"Apache-2.0"
] | 8
|
2015-09-30T08:41:15.000Z
|
2020-03-11T03:49:42.000Z
|
/**********************************************************************
* Online Judge : POJ
* Problem Title : Number Steps
* ID : 1663
* Date : 4/22/2009
* Time : 20:34:57
* Computer Name : EVERLASTING-PC
***********************************************************************/
#include<iostream>
using namespace std;
int x,y,t;
int SNumber()
{
if(x==y)
{
if(x%2)
{
return 2*x-1;
}
else
{
return 2*x;
}
}
else if(x==y+2)
{
if(x%2)
{
return 2*y+1;
}
else
{
return 2*x-2;
}
}
return -1;
}
int main()
{
//freopen("in_1663.txt","r",stdin);
cin>>t;
while(t--)
{
cin>>x>>y;
int ans=SNumber();
if(ans==-1)
{
cout<<"No Number\n";
}
else
{
cout<<ans<<endl;
}
}
return 0;
}
| 13.516667
| 72
| 0.378545
|
twilightgod
|
c7b54349030ea973cfff59d9bbd447db32a4f6f1
| 31,681
|
cpp
|
C++
|
main.cpp
|
RizniMohamed/Best-Auto-Part-
|
2319664109d2fe425e427c1b7c338cdb08b18853
|
[
"Apache-2.0"
] | null | null | null |
main.cpp
|
RizniMohamed/Best-Auto-Part-
|
2319664109d2fe425e427c1b7c338cdb08b18853
|
[
"Apache-2.0"
] | null | null | null |
main.cpp
|
RizniMohamed/Best-Auto-Part-
|
2319664109d2fe425e427c1b7c338cdb08b18853
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <limits>
#include <iomanip>
#include <fstream>
using namespace std;
//Function Prototyping
void Header(string,int);
void Menue();
void guestMenue();
void guestSelection(int);
void userMenue();
void userSelection(int);
void adminMenue();
void adminSelection(int);
void Manage_user_accounts();
void display_user_accounts();
void deleteUserML();
void availableService();
void Available_Service_Menue();
void List_Services(string);
void Search_services();
void buyService();
bool Available_Service_Selection(int);
void availableProduct();
void Available_Product_Menue();
void List_Product(string);
void Search_Product();
void buyProduct();
bool Available_Product_Selection(int);
void login();
void signup();
void logout();
void Manage_login();
void admin_login_Menue();
bool admin_login_Selection(int);
void user_login_Menue();
bool user_login_Selection(int);
void changePassword();
bool deleteAccount();
void Manage_Services_Proucts();
void Manage_Services_Proucts_Menue();
bool Manage_Services_Proucts_Selection(int);
void Add_Services();
void Delete_Services();
void Update_Services();
void Add_Products();
void Delete_Products();
void Update_Products();
void cart();
float find_price_delete_cart(string,int);
void bill();
void money_total(int , bool, bool);
void resetCartSystem();
//Gloabal Variable
bool loginStatus = 0;
bool loginAdminStatus = 0;
string password = "";
string username = "";
string UP[2];
float total = 0;
//Constants
int main() {
resetCartSystem();
Menue();
return 0;
}
void resetCartSystem(){
ofstream sCartFile("Cart\\cart_S.txt");
ofstream pCartFile("Cart\\cart_P.txt");
sCartFile.close();
pCartFile.close();
total = 0;
}
string path = "Main Menue";
void Header(string ipath="", int status =-1){
system("CLS");
cout << "\t\t\t==============\n"
<< "\t\t\tBest Auto Part\n"
<< "\t\t\t==============\n\n" ;
if(ipath != "" && status == 1){
path += " -> " + ipath;
}else if (status ==0){
ipath = " -> " + ipath;
path.replace(path.find(ipath), ipath.length(), "");
}
cout << path << "\n-----------------------------------------------------------------------\n";
money_total(0,1,1);
}
void money_total(int price = 0 , bool add = 1, bool show = 0){
if(add){
total += price;
}else{
total -= price;
}
if(show)
cout << "\t\t\t\t\t\t\t\t" << fixed << setprecision(2) << total << " LKR";
}
void Menue(){
while(true){
Header();
if(loginStatus)
(loginAdminStatus)?adminMenue():userMenue();
else
guestMenue();
int option = 0;
cout << "\nEnter the option : ";
cin >> option;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "invalid option\n";
system("PAUSE");
}else{
if(loginStatus)
(loginAdminStatus)?adminSelection(option):userSelection(option);
else
guestSelection(option);
}
}
}
void guestMenue(){
cout << "\n\tGuest\n\n";
cout << "1. Available Services\n"
<< "2. Available Proucts\n"
;
cout << "\n3. Login\n"
<< "4. Signup\n"
<< "0. Exit\n";
}
void guestSelection(int option){
switch(option){
case 1:
availableService();
break;
case 2:
availableProduct();
break;
case 3:
login();
break;
case 4:
signup();
break;
case 0:
system("CLS");
exit(0);
break;
default:
cout << "invalid option\n";
}
}
void availableService(){
bool stop = 0;
while(!stop){
Header("Available Service",1);
cout << "\n\tAvailable Service\n";
Available_Service_Menue();
int option = 0;
cout << "\nEnter the option : ";
cin >> option;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid option\n";
system("PAUSE");
}else{
stop = Available_Service_Selection(option);
}
Header("Available Service",0);
}
}
void Available_Service_Menue(){
cout << "\n1. List Services\n"
<< "2. Search Services\n"
;
if(loginStatus || loginAdminStatus){
cout << "3. Buy\n";
}
cout << "\n0. Back\n";
}
bool Available_Service_Selection(int option){
switch(option){
case 1:
Header("List Services",1);
List_Services("Services\\service.txt");
system("PAUSE");
Header("List Services",0);
break;
case 2:
Search_services();
break;
case 0:
return 1;
break;
default:
if(loginStatus || loginAdminStatus){
buyService();
}else{
cout << "invalid option\n";
system("PAUSE");
}
}
return 0;
}
void buyProduct(){
while(1){
Header("Buy Product",1);
cout << "\n\t\tBuy Product\n\n";
int pNum = 0, i = 0 , j= 0 , quantity = 0;;
string line[20], catchLine, Product;
float pprice;
cout << "Enter Product number : ";
cin >> pNum;
ifstream infile("Product\\Product.txt");
while(getline(infile,line[i])){
if( (pNum-1) == i){
catchLine = line[i];
break;
}
i++;
}
infile.close();
if(catchLine != ""){
long long int pos = 0;
string delimiter = ",";
while ((pos = catchLine.find(delimiter)) != string::npos) {
Product = catchLine.substr(0, pos);
catchLine.erase(0, pos + delimiter.length());
pprice = stoi( catchLine.substr(0, catchLine.size()-4) );
}
cout << "Enter the quantity : ";
cin >> quantity;
cout << "\nProduct : " << Product
<< "\nUnit price : " << pprice
<< "\nQuantity : " << quantity
<< "\nPrice : " << pprice*quantity;
{
ofstream outfile("cart\\cart_P.txt",ios::app);
outfile << Product << "," << pprice*quantity << endl;
outfile.close();
}
cout << "\n\n Successfully added to cart\n";
money_total(pprice*quantity,1,0);
}else{
cout << "Invalid Product number\n";
}
char yn;
cout << "\nDo you want to buy more Products? (y/n) : ";
cin >> yn;
bool askReturn = true;
while (askReturn){
if(yn == 'n'){
askReturn = false;
break;
}else if(yn == 'y'){
break;
}else{
cout << "Invalid option\n";
}
}
if (!askReturn){
system("PAUSE");
Header("Buy Product",0);
break;
}
system("PAUSE");
Header("Buy Product",0);
}
}
void buyService(){
while(1){
Header("Buy Service",1);
cout << "\n\t\tBuy Service\n\n";
int sNum = 0, i = 0 , j= 0 , quantity = 0;;
string line[20], catchLine, service;
float sprice;
cout << "Enter service number : ";
cin >> sNum;
ifstream infile("Services\\service.txt");
while(getline(infile,line[i])){
if( (sNum-1) == i){
catchLine = line[i];
break;
}
i++;
}
infile.close();
if(catchLine != ""){
long long int pos = 0;
string delimiter = ",";
while ((pos = catchLine.find(delimiter)) != string::npos) {
service = catchLine.substr(0, pos);
catchLine.erase(0, pos + delimiter.length());
sprice = stoi( catchLine.substr(0, catchLine.size()-4) );
}
cout << "Enter the quantity : ";
cin >> quantity;
cout << "\nService : " << service
<< "\nUnit price : " << sprice
<< "\nQuantity : " << quantity
<< "\nPrice : " << sprice*quantity;
{
ofstream outfile("cart\\cart_S.txt",ios::app);
outfile << service << "," << sprice*quantity << endl;
outfile.close();
}
cout << "\n\n Successfully added to cart\n";
money_total(sprice*quantity,1,0);
}else{
cout << "Invalid service number\n";
}
char yn;
cout << "\nDo you want to buy more services? (y/n) : ";
cin >> yn;
bool askReturn = true;
while (askReturn){
if(yn == 'n'){
askReturn = false;
break;
}else if(yn == 'y'){
break;
}else{
cout << "Invalid option\n";
}
}
if (!askReturn){
system("PAUSE");
Header("Buy Service",0);
break;
}
system("PAUSE");
Header("Buy Service",0);
}
}
void List_Services(string path){
cout << "\n\t\t List Services\n\n";
string line[100], SANDP[200];
int n = 0;
ifstream infile(path);
while(getline(infile,line[n])){
n++;
}
infile.close();
int i = 0;
for(int j = 0 ; j < n ; j++){
long long int pos = 0;
string delimiter = ",";
while ((pos = line[j].find(delimiter)) != string::npos) {
SANDP[i] = line[j].substr(0, pos);
line[j].erase(0, pos + delimiter.length());
SANDP[i+1] = line[j].substr(0, pos+10);
i+=2;
}
}
int z = 0;
cout << "\tName \t\t\t\tPrice" << "\n\n";
for(int i = 0 ; i < (n*2) ; i+=2){
cout << left <<setw(2) << ++z << " " << setw(32) << left << SANDP[i] << "\t" <<setw(32) <<SANDP[i+1] << "\n";
}
cout << endl;
}
void Search_services(){
Header("Search Services",1);
cout << "\n\t\t Search Services\n\n";
string line[10],SSP[20], Pname;
bool isHas = false;
int n = 0;
cout << "Enter service name : ";
cin >> Pname;
ifstream infile("Services\\service.txt");
for(int i = 0 ; i < 10 ; i++){
while(!infile.fail()){
getline(infile,line[i]);
if ( (line[i].find(Pname)) != (string::npos)){
isHas = true;
n++;
break;
}
}
}
infile.close();
if(isHas){
int pos = 0 , i = 0;
string UP[2],delimiter = ",";
for(int j = 0 ; j < n ; j++){
while ((pos = line[j].find(delimiter)) != string::npos) {
SSP[i] = line[j].substr(0, pos);
line[j].erase(0, pos + delimiter.length());
SSP[i+1] = line[j].substr(0, pos+10);
i+=2;
}
}
int z = 0;
cout << endl << setw(20) << "Name" << setw(28) << "Price" << "\n\n";
for(int i = 0 ; i < (n*2) ; i+=2){
cout << left <<setw(2) << ++z << " " << setw(32) << left << SSP[i] << "\t" <<setw(32) <<SSP[i+1] << "\n";
}
}else{
cout << "\nService not found, make sure search word is correct by checking in service list\n";
}
cout << endl;
system("PAUSE");
Header("Search Services",0);
}
void availableProduct(){
bool stop = 0;
while(!stop){
Header("Available Product",1);
cout << "\n\tAvailable Product\n";
Available_Product_Menue();
int option = 0;
cout << "\nEnter the option : ";
cin >> option;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid option\n";
system("PAUSE");
}else{
stop = Available_Product_Selection(option);
}
Header("Available Product",0);
}
}
void Available_Product_Menue(){
cout << "\n1. List Product\n"
<< "2. Search Product\n"
;
if(loginStatus || loginAdminStatus){
cout << "3. Buy\n";
}
cout << "\n0. Back\n";
}
bool Available_Product_Selection(int option){
switch(option){
case 1:
Header("List Product",1);
List_Product("Product\\Product.txt");
system("PAUSE");
Header("List Product",0);
break;
case 2:
Search_Product();
break;
case 0:
return 1;
break;
default:
if(loginStatus || loginAdminStatus){
buyProduct();
}else{
cout << "invalid option\n";
system("PAUSE");
}
}
return 0;
}
void List_Product(string path){
cout << "\n\t\t List Product\n\n";
string line[100], SANDP[200];
int n = 0;
ifstream infile(path);
while(getline(infile,line[n])){
n++;
}
infile.close();
int i = 0;
for(int j = 0 ; j < n ; j++){
long long int pos = 0;
string delimiter = ",";
while ((pos = line[j].find(delimiter)) != string::npos) {
SANDP[i] = line[j].substr(0, pos);
line[j].erase(0, pos + delimiter.length());
SANDP[i+1] = line[j].substr(0, pos+10);
i+=2;
}
}
int z = 0;
cout << "\tName \t\t\t\tPrice" << "\n\n";
for(int i = 0 ; i < (n*2) ; i+=2){
cout << left <<setw(2) << ++z << " " << setw(32) << left << SANDP[i] << "\t" <<setw(32) <<SANDP[i+1] << "\n";
}
cout << endl;
}
void Search_Product(){
Header("Search Product",1);
cout << "\n\t\t Search Product\n\n";
string line[10],SSP[20], Pname;
bool isHas = false;
int n = 0;
cout << "Enter Product name : ";
cin >> Pname;
ifstream infile("Product\\Product.txt");
for(int i = 0 ; i < 10 ; i++){
while(!infile.fail()){
getline(infile,line[i]);
if ( (line[i].find(Pname)) != (string::npos)){
isHas = true;
n++;
break;
}
}
}
infile.close();
if(isHas){
int pos = 0 , i = 0;
string UP[2],delimiter = ",";
for(int j = 0 ; j < n ; j++){
while ((pos = line[j].find(delimiter)) != string::npos) {
SSP[i] = line[j].substr(0, pos);
line[j].erase(0, pos + delimiter.length());
SSP[i+1] = line[j].substr(0, pos+10);
i+=2;
}
}
int z = 0;
cout << endl << " " << setw(20) << "Name" << setw(28) << "Price" << "\n\n";
for(int i = 0 ; i < (n*2) ; i+=2){
cout << left <<setw(2) << ++z << " " << setw(32) << left << SSP[i] << "\t" <<setw(32) <<SSP[i+1] << "\n";
}
}else{
cout << "\nProduct not found, make sure search word is correct by checking in service list\n";
}
cout << endl;
system("PAUSE");
Header("Search Product",0);
}
void adminMenue(){
if (loginAdminStatus){
cout << "\n\tWelcome admin "<< username << "\n\n";
}else{
cout << "\n\tWelcome "<< username << "\n\n";
}
cout << "1. Available Services\n"
<< "2. Available Proucts\n"
<< "3. Manage Services & Proucts\n"
<< "4. Manage login\n"
<< "5. Cart\n"
;
cout << "\n6. Logout\n"
<< "0. Exit\n";
}
void adminSelection(int option){
switch(option){
case 1:
availableService();
break;
case 2:
availableProduct();
break;
case 3:
Manage_Services_Proucts();
break;
case 4:
Manage_login();
break;
case 5:
cart();
break;
case 6:
logout();
break;
case 0:
system("CLS");
exit(0);
break;
default:
cout << "invalid option\n";
}
}
void Manage_Services_Proucts(){
bool stop = 0;
while(!stop){
Header("Manage Services Proucts",1);
cout << "\n\tManage Services Proucts\n";
Manage_Services_Proucts_Menue();
int option = 0;
cout << "\nEnter the option : ";
cin >> option;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid option\n";
system("PAUSE");
}else{
stop = Manage_Services_Proucts_Selection(option);
}
Header("Manage Services Proucts",0);
}
}
void Manage_Services_Proucts_Menue(){
cout << "\nServices:\n"
<< " 1. Add Services\n"
<< " 2. Delete Services\n"
<< " 3. Update Services\n"
;
cout << "\nProucts:\n"
<< " 4. Add Proucts\n"
<< " 5. Delete Proucts\n"
<< " 6. Update Proucts\n"
;
cout << "\n0. Back\n";
}
bool Manage_Services_Proucts_Selection(int option){
switch(option){
case 1:
Add_Services();
break;
case 2:
Delete_Services();
break;
case 3:
Update_Services();
break;
case 4:
Add_Products();
break;
case 5:
Delete_Products();
break;
case 6:
Update_Products();
break;
case 0:
return 1;
break;
default:
cout << "invalid option\n";
}
return 0;
}
void Add_Products(){
string Product, price;
Header("Add Products",1);
cout << "\nAdd Products\n\n";
ifstream infile("Product\\Product.txt");
if(infile){
ofstream outfile("Product\\Product.txt", ios::app);
cout << "Enter Product name : ";
cin >> Product;
cout << "Enter Product Price : ";
cin >> price;
outfile << Product << "," << price << " LKR" << endl;
outfile.close();
cout << "Product added successfully\n";
}else{
cout << "Unable to access data file\n";
}
system("PAUSE");
Header("Add Products",0);
}
void Add_Services(){
string service, price;
Header("Add Services",1);
cout << "\nAdd Services\n\n";
ifstream infile("Services\\service.txt");
if(infile){
ofstream outfile("Services\\service.txt", ios::app);
cout << "Enter service name : ";
cin >> service;
cout << "Enter service Price : ";
cin >> price;
outfile << service << "," << price << " LKR" << endl;
outfile.close();
cout << "Service added successfully\n";
}else{
cout << "Unable to access data file\n";
}
system("PAUSE");
Header("Add Services",0);
}
void delete_S_P(string path, int sNum){
string line[50];
int i = 0 , j= 0;
ifstream infile(path);
while(getline(infile,line[i])){
if( (sNum) == i){
line[i] = "";
}
i++;
}
infile.close();
ofstream outfile(path);;
while(i>j){
if(line[j] !=""){
outfile << line[j] << endl;
}
j++;
}
outfile.close();
}
void Delete_Products(){
Header("Delete Products",1);
cout << "\n\tDelete Products\n\n";
int sNum = 0;
cout << "Enter Products number : ";
cin >> sNum;
string line[50], catchLine;
int i = 0 , j= 0;
ifstream infile("Product\\Product.txt");
while(getline(infile,line[i])){
if( (sNum-1) == i){
catchLine = line[i];
}
i++;
}
infile.close();
cout << "Confirm : \n"
<< " Once you deleted, \'" << catchLine << "\' no longer available to be a user of this\n"
<< " Do you want to delete (y/n) : "
;
char yn;
cin >> yn;
if (yn == 'y'){
{
delete_S_P("Product\\Product.txt", (sNum-1) );
}
cout << "Deletion process successed\n";
}else if(yn == 'n'){
cout << "Deletion process cancelled\n";
}else{
cout << "invalid option\n";
}
system("PAUSE");
Header("Delete Products",0);
}
void Delete_Services(){
Header("Delete Services",1);
cout << "\n\tUpdate Services\n\n";
int sNum = 0;
cout << "Enter service number : ";
cin >> sNum;
string line[20], catchLine;
int i = 0 , j= 0;
ifstream infile("Services\\service.txt");
while(getline(infile,line[i])){
if( (sNum-1) == i){
catchLine = line[i];
}
i++;
}
infile.close();
cout << "Confirm : \n"
<< " Once you deleted, \'" << catchLine << "\' no longer available to be a user of this\n"
<< " Do you want to delete (y/n) : "
;
char yn;
cin >> yn;
if (yn == 'y'){
{
delete_S_P("Services\\service.txt", (sNum-1) );
}
cout << "Deletion process successed\n";
}else if(yn == 'n'){
cout << "Deletion process cancelled\n";
}else{
cout << "invalid option\n";
}
system("PAUSE");
Header("Delete Services",0);
}
void Update_Products(){
Header("Update Products",1);
cout << "\n\tUpdate Products\n\n";
int sNum = 0;
cout << "Enter Product number : ";
cin >> sNum;
string line[50], catchLine;
int i = 0 , j= 0;
ifstream infile("Product\\Product.txt");
while(getline(infile,line[i])){
if( (sNum-1) == i){
catchLine = line[i];
line[i] = "";
}
i++;
}
infile.close();
cout << "Confirm : \n"
<< " Are you going to update \' " << catchLine << " \' (y/n) : "
;
char yn;
cin >> yn;
if (yn == 'y'){
{
delete_S_P("Product\\Product.txt", (sNum-1) );
string Product, price;
ofstream outfile("Product\\Product.txt", ios::app);;
cout << "Enter Product name : ";
cin >> Product;
cout << "Enter Product Price : ";
cin >> price;
outfile << Product << "," << price << " LKR" << endl;
outfile.close();
cout << "Product updated successfully\n";
}
}else if(yn == 'n'){
cout << "Deletion process cancelled\n";
}else{
cout << "invalid option\n";
}
system("PAUSE");
Header("Update Products",0);
}
void Update_Services(){
Header("Update Services",1);
cout << "\n\tUpdate Services\n\n";
int sNum = 0;
cout << "Enter service number : ";
cin >> sNum;
string line[20], catchLine;
int i = 0 , j= 0;
ifstream infile("Services\\service.txt");
while(getline(infile,line[i])){
if( (sNum-1) == i){
catchLine = line[i];
}
i++;
}
infile.close();
cout << "Confirm : \n"
<< " Are you going to update \' " << catchLine << " \' (y/n) : "
;
char yn;
cin >> yn;
if (yn == 'y'){
{
delete_S_P("Services\\service.txt", (sNum-1) );
string service, price;
ofstream outfile("Services\\service.txt", ios::app);;
cout << "Enter service name : ";
cin >> service;
cout << "Enter service Price : ";
cin >> price;
outfile << service << "," << price << " LKR" << endl;
outfile.close();
cout << "Service updated successfully\n";
}
}else if(yn == 'n'){
cout << "Deletion process cancelled\n";
}else{
cout << "invalid option\n";
}
system("PAUSE");
Header("Update Services",0);
}
void userMenue(){
if (loginAdminStatus){
cout << "\n\tWelcome admin "<< username << "\n\n";
}else{
cout << "\n\tWelcome "<< username << "\n\n";
}
cout << "1. Available Services\n"
<< "2. Available Proucts\n"
<< "3. Manage login\n"
<< "4. Cart\n"
;
cout << "\n5. Logout\n"
<< "0. Exit\n";
}
void userSelection(int option){
switch(option){
case 1:
availableService();
break;
case 2:
availableProduct();
break;
case 3:
Manage_login();
break;
case 4:
cart();
break;
case 5:
logout();
break;
case 0:
system("CLS");
exit(0);
break;
default:
cout << "invalid option\n";
}
}
void logout(){
loginStatus = false;
loginAdminStatus = false;
resetCartSystem();
Menue();
}
void signup(){
Header("Signup",1);
cout << "\nCreate Account\n\n";
cout << "Enter username : ";
cin >> username;
ifstream infile("Login\\" + username + ".txt");
if(!infile){
cout << "Enter password : ";
cin >> password;
UP[1] = password;
cout << "Confirm password : ";
cin >> password;
if(UP[1] == password){
ofstream outfile("Login\\" + username + ".txt");
outfile << username << "," << password;
outfile.close();
ofstream masterFile("Login\\LMaster.txt",ios::app);
masterFile << username << "," << password << endl;
masterFile.close();
cout << "Account created successfully\n";
}else{
cout << "Password mismatched\n";
}
}else{
cout << "Username already taken\n";
}
system("PAUSE");
Header("Signup",0);
}
void login(){
string line;
bool valid = false, isHas = false;
Header("Login",1);
cout << "\n\tLogin\n\n";
cout << "Enter username : ";
cin >> username;
cout << "Enter password : ";
cin >> password;
ifstream infile("Login\\" + username + ".txt");
while(!infile.fail()){
getline(infile,line);
if ( (line.find(username)) != (string::npos)){
isHas = true;
break;
}
}
infile.close();
if(isHas){
int pos = 0;
string UP[2],delimiter = ",";
while ((pos = line.find(delimiter)) != string::npos) {
UP[0] = line.substr(0, pos);
line.erase(0, pos + delimiter.length());
UP[1] = line.substr(0, pos);
}
for(int i =0 ; i < 2 ; i++){
if(username==UP[i] && password==UP[i+1]){
valid = true;
break;
}
}
if(valid){
cout << "\nAccess Granted...\n";
loginStatus = true;
if(username.find("#") != string::npos){
loginAdminStatus = 1;
}else{
loginAdminStatus = 0;
}
}else{
cout << "\nAccess Denied...Invalid Password.\n\n";
loginStatus = false;
}
}else{
cout << "\nAccess Denied...Account not found\n\n";
loginStatus = false;
}
system("PAUSE");
Header("Login",0);
}
void Manage_login(){
bool stop = 0;
while(!stop){
Header("Manage login",1);
cout << "\n\tLogin\n";
if(loginAdminStatus)
admin_login_Menue();
else
user_login_Menue();
int option = 0;
cout << "\nEnter the option : ";
cin >> option;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid option\n";
system("PAUSE");
}else{
if(loginAdminStatus){
stop = admin_login_Selection(option);
}else
stop = user_login_Selection(option);
}
Header("Manage login",0);
}
}
void admin_login_Menue(){
cout << "\nManage login Menue\n\n";
cout << "1. Change Password\n"
<< "2. Manage user accounts\n"
<< "3. Delete Account\n"
;
cout << "\n0. Back\n";
}
bool admin_login_Selection(int option){
switch(option){
case 1:
changePassword();
break;
case 2:
Manage_user_accounts();
break;
case 3:
return deleteAccount();
break;
case 0:
return 1;
break;
default:
cout << "invalid option\n";
}
return 0;
}
void user_login_Menue(){
cout << "\nManage login Menue\n\n";
cout << "1. Change Password\n"
<< "2. Delete Account\n"
;
cout << "\n0. Back\n";
}
bool user_login_Selection(int option){
switch(option){
case 1:
changePassword();
break;
case 2:
return deleteAccount();
break;
case 0:
return 1;
break;
default:
cout << "invalid option\n";
}
return 0;
}
void changePassword(){
Header("Change Password",1);
cout << "\nChange Password\n\n";
UP[1] = password;
cout << "Enter old password : ";
cin >> password;
if(UP[1] == password){
cout << "Enter new password : ";
cin >> UP[1];
{
deleteUserML();
ofstream outfile("Login\\LMaster.txt", ios::app);
outfile << username << "," << UP[1] << endl;
outfile.close();
}
ofstream outfile("Login\\" + username + ".txt");
outfile << username << "," << UP[1];
outfile.close();
cout << "Password changed successfully\n";
}else{
cout << "Invalid Password\n";
}
system("PAUSE");
Header("Change Password",0);
}
bool deleteAccount(){
Header("Delete Account",1);
cout << "\n\tDelete Account\n\n";
cout << "Confirm : \n"
<< " Once you deleted you are no longer authorized to be a user of this\n"
<< " Do you want to delete (y/n) : "
;
char yn;
cin >> yn;
if (yn == 'y'){
const string fileName = "Login\\" + username + ".txt";
remove(fileName.c_str());
deleteUserML();
cout << "Account deleted successfully\n";
loginStatus = 0;
system("PAUSE");
Header("Delete Account",0);
return 1;
}else if(yn == 'n'){
cout << "Deletion process cancelled\n";
}else{
cout << "invalid option\n";
}
system("PAUSE");
Header("Delete Account",0);
return 0;
}
void deleteUserML(){
string line[100];
int i = 0 , j= 0;
ifstream infile("Login\\LMaster.txt");
string lineCheck = username + "," + password;
while(getline(infile,line[i])){
if(lineCheck == line[i]){
line[i] = "";
}
i++;
}
infile.close();
ofstream outfile("Login\\LMaster.txt");
while(i>j){
if(line[j] !=""){
outfile << line[j] << endl;
}
j++;
}
outfile.close();
}
void Manage_user_accounts(){
bool stop = 0;
while(!stop){
Header("Manage user accounts",1);
cout << "\n\tManage user accounts\n\n";
display_user_accounts();
cout << "\nEnter user username : ";
cin >> username;
ifstream infilet("Login\\" + username + ".txt");
if(infilet){
cout << "Enter user password : ";
cin >> password;
user_login_Menue();
int option = 0;
cout << "\nEnter the option : ";
cin >> option;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid option\n";
system("PAUSE");
}else{
stop = user_login_Selection(option);
}
}else{
cout << "Account not found\n";
}
//system("PAUSE");
Header("Manage user accounts",0);
}
}
void display_user_accounts(){
string line[100], DUA[200];
int n = 0;
ifstream infile("Login\\LMaster.txt");
while(getline(infile,line[n])){
n++;
}
infile.close();
int i = 0;
for(int j = 0 ; j < n ; j++){
int pos = 0;
string delimiter = ",";
while ((pos = line[j].find(delimiter)) != string::npos) {
DUA[i] = line[j].substr(0, pos);
line[j].erase(0, pos + delimiter.length());
DUA[i+1] = line[j].substr(0, pos);
i+=2;
}
}
int z = 0;
cout << " Username\tPassword \n";
for(int i = 0 ; i < n*2 ; i+=2){
cout << setw(3) << ++z << " " << DUA[i] << "\t\t" << DUA[i+1] << "\n";
}
}
void cart(){
int sNum;
char yn;
string sline = "", pline = "";
ifstream sinfile("Cart\\cart_S.txt");
getline(sinfile,sline);
sinfile.close();
ifstream pinfile("Cart\\cart_P.txt");
getline(pinfile,pline);
pinfile.close();
if( (sline != "") || (pline != "") ){
Header("Cart",1);
if(sline != ""){
do{
Header("Cart",0);
Header("Cart",1);
cout << "\n\t\t\t Cart\n";
List_Services("Cart\\cart_S.txt");
cout << "Do you want to remove any service from the cart? (y/n) : ";
cin >> yn;
if(yn == 'y'){
cout << "\nEnter the service number : ";
cin >> sNum;
money_total(find_price_delete_cart("Cart\\cart_S.txt",sNum),0,0);
delete_S_P("Cart\\cart_S.txt", (sNum-1) );
}
}while(yn == 'y');
}
if(pline != ""){
do{
Header("Cart",0);
Header("Cart",1);
cout << "\n\t\t\t Cart\n";
List_Services("Cart\\cart_S.txt");
List_Product("Cart\\cart_P.txt");
cout << "Do you want to remove any product from the cart? (y/n) : ";
cin >> yn;
if(yn == 'y'){
cout << "\nEnter the product number : ";
cin >> sNum;
money_total(find_price_delete_cart("Cart\\cart_P.txt",sNum),0,0);
delete_S_P("Cart\\cart_P.txt", (sNum-1) );
}
}while(yn == 'y');
}
bill();
Header("Cart",0);
}else{
cout << "\t\t Cart is empty \n";
system("PAUSE");
}
}
void bill(){
Header("Bill",1);
cout << "\n\t\t\t Bill\n";
List_Services("Cart\\cart_S.txt");
List_Product("Cart\\cart_P.txt");
cout << setw(16) <<"Customer name : " << username << "\n";
cout << setw(16) << "Total Price :" << total << "\n";
cout << "\n\t\tThank you!\n\n";
resetCartSystem();
system("Pause");
Header("Bill",0);
}
float find_price_delete_cart(string path, int num){
string line[50], SANDP[100];
int n = 0;
ifstream infile(path);
while(getline(infile,line[n])){
n++;
}
infile.close();
int i = 0;
for(int j = 0 ; j < n ; j++){
long long int pos = 0;
string delimiter = ",";
while ((pos = line[j].find(delimiter)) != string::npos) {
SANDP[i] = line[j].substr(0, pos);
line[j].erase(0, pos + delimiter.length());
SANDP[i+1] = line[j].substr(0, pos+10);
i+=2;
}
}
if(num>n)
return 0.00;
else
return stof(SANDP[(2*num)-1]);
}
| 19.937697
| 114
| 0.52975
|
RizniMohamed
|
c7b6bd3aaa34c24a4e855e4edb30602aa8c15715
| 174
|
hpp
|
C++
|
src/helper.hpp
|
Pyknic/matrix-solver
|
1521bb87f0b0cee60fde435367bb586ae3e24d7b
|
[
"MIT"
] | null | null | null |
src/helper.hpp
|
Pyknic/matrix-solver
|
1521bb87f0b0cee60fde435367bb586ae3e24d7b
|
[
"MIT"
] | null | null | null |
src/helper.hpp
|
Pyknic/matrix-solver
|
1521bb87f0b0cee60fde435367bb586ae3e24d7b
|
[
"MIT"
] | null | null | null |
#pragma once
//
// Copyright (c) 2020 Emil Forslund. All rights reserved.
//
#include "symbol.hpp"
#include <string>
Symbol* _(float v);
Symbol* _(const std::string& s);
| 13.384615
| 57
| 0.672414
|
Pyknic
|
c7b91e3142328590d0a305e58709326aa002a521
| 38,426
|
cc
|
C++
|
src/paths/AssemblyCleanupTools.cc
|
bayolau/discovar
|
9e472aca13670e40ab2234b89c8afd64875c58bf
|
[
"MIT"
] | null | null | null |
src/paths/AssemblyCleanupTools.cc
|
bayolau/discovar
|
9e472aca13670e40ab2234b89c8afd64875c58bf
|
[
"MIT"
] | null | null | null |
src/paths/AssemblyCleanupTools.cc
|
bayolau/discovar
|
9e472aca13670e40ab2234b89c8afd64875c58bf
|
[
"MIT"
] | 1
|
2021-11-28T21:35:27.000Z
|
2021-11-28T21:35:27.000Z
|
///////////////////////////////////////////////////////////////////////////////
// SOFTWARE COPYRIGHT NOTICE AGREEMENT //
// This software and its documentation are copyright (2011) by the //
// Broad Institute. All rights are reserved. This software is supplied //
// without any warranty or guaranteed support whatsoever. The Broad //
// Institute is not responsible for its use, misuse, or functionality. //
///////////////////////////////////////////////////////////////////////////////
// MakeDepend: library OMP
// MakeDepend: cflags OMP_FLAGS
#include "CoreTools.h"
#include "VecUtilities.h"
#include "ParallelVecUtilities.h"
#include "lookup/LookAlign.h"
#include "efasta/EfastaTools.h"
#include "paths/AssemblyCleanupTools.h"
#include "pairwise_aligners/SmithWatBandedA.h"
struct scompare : public std::binary_function<superb,superb,bool>
{
bool operator()( const superb& s1, const superb& s2 ) const
{ return s1.FullLength() > s2.FullLength(); }
};
Assembly::Assembly( const String in_superb_file, const String in_contigs_file, const String in_scaff_graph_file ){
// Loading scaffolds
cout << Date( ) << ": loading superb file" << endl;
ReadSuperbs( in_superb_file, scaffolds_ );
// reading contig information
if ( in_contigs_file.Contains(".efasta") ) {
LoadEfastaIntoStrings(in_contigs_file, efastas_);
fastgs_.resize( efastas_.size() );
for ( size_t i = 0; i < efastas_.size(); i++ )
fastgs_[i] = recfastg( ToString(i), basefastg( efastas_[i] ) );
}else if ( in_contigs_file.Contains(".fastg") ) {
LoadFastg(in_contigs_file, fastgs_);
efastas_.resize( fastgs_.size() );
efasta tmp;
for ( size_t i = 0; i < fastgs_.size(); i++ )
{
tmp.clear();
fastgs_[i].AsEfasta( tmp , fastg_meta::MODE_2);
efastas_[i] = tmp;
}
}
tigMap_.resize( efastas_.size() );
for ( size_t tid = 0; tid != efastas_.size(); tid++ )
tigMap_[tid] = ToString(tid);
scaffMap_.resize( scaffolds_.size() );
for ( int sid = 0; sid < scaffolds_.isize(); sid++ )
scaffMap_[sid] = ToString(sid);
if ( in_scaff_graph_file.nonempty() )
BinaryReader::readFile( in_scaff_graph_file, &SG_ );
else{
SG_.Initialize( scaffolds_.isize() );
}
}
Assembly::Assembly( const vec<superb>& scaffoldsIn, const VecEFasta& efastasIn, const vec<String>* scaffMap, const vec<String>* tigMap, const digraphE<sepdev>* SGin ){
scaffolds_ = scaffoldsIn;
efastas_ = efastasIn;
fastgs_.resize( efastas_.size() );
for ( size_t i = 0; i < efastas_.size(); i++ )
fastgs_[i] = recfastg( ToString(i), basefastg( efastas_[i] ) );
if ( tigMap == 0 ){
tigMap_.resize( efastas_.size() );
for ( size_t tid = 0; tid != efastas_.size(); tid++ )
tigMap_[tid] = ToString(tid);
}else tigMap_ = *tigMap;
if ( scaffMap == 0 ){
scaffMap_.resize( scaffolds_.size() );
for ( int sid = 0; sid < scaffolds_.isize(); sid++ )
scaffMap_[sid] = ToString(sid);
}else scaffMap_ = *scaffMap;
if ( SGin != 0 ){
SG_ = *SGin;
}else{
SG_.Initialize( scaffolds_.isize() );
}
}
Assembly::Assembly( const vec<superb>& scaffoldsIn, const vec<recfastg>& fastgsIn, const vec<String>* scaffMap, const vec<String>* tigMap, const digraphE<sepdev>* SGin ){
scaffolds_ = scaffoldsIn;
fastgs_ = fastgsIn;
efastas_.resize( fastgs_.size() );
efasta tmp;
for ( size_t i = 0; i < fastgs_.size(); i++ )
{
tmp.clear();
fastgs_[i].AsEfasta( tmp , fastg_meta::MODE_2);
efastas_[i] = tmp;
}
if ( tigMap == 0 ){
tigMap_.resize( efastas_.size() );
for ( size_t tid = 0; tid != efastas_.size(); tid++ )
tigMap_[tid] = ToString(tid);
}else tigMap_ = *tigMap;
if ( scaffMap == 0 ){
scaffMap_.resize( scaffolds_.size() );
for ( int sid = 0; sid < scaffolds_.isize(); sid++ )
scaffMap_[sid] = ToString(sid);
}else scaffMap_ = *scaffMap;
if ( SGin != 0 ){
SG_ = *SGin;
}else{
SG_.Initialize( scaffolds_.isize() );
}
}
size_t Assembly::scaffoldsTotLen() const{
size_t len = 0;
for ( size_t is = 0; is < scaffolds_.size(); is++ )
len += scaffolds_[is].FullLength();
return len;
}
size_t Assembly::scaffoldsRedLen() const{
size_t len = 0;
for ( size_t is = 0; is < scaffolds_.size(); is++ )
len += scaffolds_[is].ReducedLength();
return len;
}
size_t Assembly::scaffoldsNtigs() const{
size_t ntigs = 0;
for ( size_t is = 0; is < scaffolds_.size(); is++ )
ntigs += scaffolds_[is].Ntigs();
return ntigs;
}
// check integrity of scafolds and contigs data: contig size in superb == contig size in efasta,
// each contig used once and only once
void Assembly::check_integrity() const{
cout << Date() << ": checking integrity" << endl;
ForceAssertEq( efastas_.size(), fastgs_.size() );
vec<int> tigs_used( efastas_.size(), 0);
for ( size_t i = 0; i < efastas_.size( ); i++ ){
vec<String> s(1);
s[0] = efastas_[i];
ValidateEfastaRecord(s);
ForceAssert( fastgs_[i].IsGapless() );
ForceAssertEq( fastgs_[i].Length1(), efastas_[i].Length1() );
ForceAssertEq( fastgs_[i].MinLength(fastg_meta::MODE_2), efastas_[i].MinLength() );
ForceAssertEq( fastgs_[i].MaxLength(fastg_meta::MODE_2), efastas_[i].MaxLength() );
efasta fe;
fastgs_[i].AsEfasta( fe ,fastg_meta::MODE_2);
basevector b1, b2;
fe.FlattenTo( b1 );
efastas_[i].FlattenTo( b2 );
ForceAssertEq( b1, b2 );
ForceAssertEq( fe.Length1(), efastas_[i].Length1() );
ForceAssertEq( fe.MinLength(), efastas_[i].MinLength() );
ForceAssertEq( fe.MaxLength(), efastas_[i].MaxLength() );
}
for ( size_t si = 0; si < scaffolds_.size(); si++ ){
const superb & s = scaffolds_[si];
ForceAssertGt( s.Ntigs(), 0 );
for ( int tpos = 0; tpos < s.Ntigs(); tpos++ ){
size_t tid = s.Tig(tpos);
ForceAssertLt( tid, efastas_.size() );
if ( efastas_[tid].Length1() != s.Len(tpos) ){
DPRINT5( si, tpos, tid, s.Len(tpos), efastas_[tid].Length1() );
ForceAssertEq( efastas_[tid].Length1(), s.Len(tpos) );
}
tigs_used[tid]++;
}
}
vec<size_t> unused_tigs, overused_tigs;
for ( size_t tid = 0; tid < tigs_used.size(); tid++ ){
if ( tigs_used[tid] == 0 )
unused_tigs.push_back( tid );
else if ( tigs_used[tid] > 1 )
overused_tigs.push_back(tid);
}
if ( unused_tigs.size() > 0 || overused_tigs.size() > 0 ){
if ( unused_tigs.size() > 0 ){
int max_un_size = efastas_.at( unused_tigs[0] ).Length1();
for ( size_t i = 0; i < unused_tigs.size(); i++ )
if ( efastas_.at( unused_tigs[i] ).Length1() > max_un_size )
max_un_size = efastas_.at( unused_tigs[i] ).Length1();
cout << Date() << ": maximum size of unused contig is : " << max_un_size << endl;
}
DPRINT2( unused_tigs.size(), overused_tigs.size() );
ForceAssert( unused_tigs.size() == 0 && overused_tigs.size() == 0 );
}
ForceAssertEq( scaffolds_.isize(), SG_.N() );
return;
}
void Assembly::remove_small_scaffolds(const int min_scaffold_size) {
cout << Date() << ": removing small scaffolds: " << endl;
vec<int> verts_to_remove;
for ( int si = 0; si < scaffolds_.isize(); si++ )
if ( scaffolds_.at(si).ReducedLength() < min_scaffold_size )
verts_to_remove.push_back(si);
remove_scaffolds(verts_to_remove);
}
void Assembly::remove_scaffolds( const vec<Bool>& to_remove ) {
cout << Date() << ": initial number of scaffolds = " << scaffolds_.size() << endl;
ForceAssertEq( scaffolds_.size(), to_remove.size() );
ForceAssertEq( efastas_.size(), fastgs_.size() );
vec<int> verts_to_remove;
for ( size_t i = 0; i < to_remove.size(); i++ )
if ( to_remove[i] ) {
verts_to_remove.push_back(i);
SG_.DeleteEdgesAtVertex( i );
}
EraseIf( scaffolds_, to_remove );
EraseIf( scaffMap_, to_remove );
SG_.RemoveEdgelessVertices( verts_to_remove );
ForceAssertEq( scaffolds_.isize(), SG_.N() );
ForceAssertEq( efastas_.size(), fastgs_.size() );
cout << Date() << ": final number of scaffolds = " << scaffolds_.size() << endl;
}
void Assembly::remove_scaffolds( const vec<int>& s_to_remove ) {
if ( s_to_remove.size() == 0 ) return;
ForceAssertGe( Min(s_to_remove), 0 );
ForceAssertLt( Max(s_to_remove), scaffolds_.isize() );
vec<Bool> to_remove( scaffolds_.size(), False );
for ( size_t i = 0; i < s_to_remove.size(); i++ )
to_remove[ s_to_remove[i] ] = True;
remove_scaffolds( to_remove );
}
void Assembly::remove_contigs( const vec<Bool>& to_remove )
{
ForceAssertEq( efastas_.size(), fastgs_.size() );
vec<int> offsets( efastas_.size(), 0 );
int offset = 0;
for ( size_t tid = 0; tid < efastas_.size(); tid++ ){
if ( to_remove[tid] ){
offsets[tid] = -1;
offset++;
}
else{ offsets[tid] = offset; }
}
ForceAssertEq( offsets.size(), efastas_.size() );
for ( int tid = 0; tid < offsets.isize(); tid++ ){
if ( offsets[tid] > 0 ){
efastas_[ tid - offsets[tid] ] = efastas_[tid];
fastgs_[ tid - offsets[tid] ] = fastgs_[tid];
tigMap_[tid - offsets[tid] ] = tigMap_[tid];
}
}
efastas_.resize( efastas_.size() - offset );
fastgs_.resize( fastgs_.size() - offset );
tigMap_.resize( tigMap_.size() - offset );
ForceAssertEq( efastas_.size(), tigMap_.size() );
for ( size_t si = 0; si < scaffolds_.size(); si++ ){
for ( int tpos = 0; tpos < scaffolds_[si].Ntigs(); tpos++ ){
int tid = scaffolds_[si].Tig(tpos);
if ( offsets[tid] >= 0 ){
int newtid = tid - offsets[tid];
ForceAssertGe( newtid, 0 );
scaffolds_[si].SetTig( tpos, newtid );
}
else{
scaffolds_[si].RemoveTigByPos( tpos );
tpos--;
}
}
}
ForceAssertEq( efastas_.size(), fastgs_.size() );
}
void Assembly::remove_small_contigs( const int min_size_solo, const int min_size_in ){
cout << Date() << ": removing small contigs and renumbering" << endl;
vec<int> offsets( efastas_.size(), 0 );
vec<Bool> tigsToRemove( efastas_.size(), False);
for ( size_t si = 0; si < scaffolds_.size(); si++ ){
if ( scaffolds_[si].Ntigs() == 1 ){
if ( scaffolds_[si].Len(0) < min_size_solo )
tigsToRemove[ scaffolds_[si].Tig(0) ] = True;
}
else{
for ( int tpos = 0; tpos < scaffolds_[si].Ntigs(); tpos++ ){
if ( scaffolds_[si].Len(tpos) < min_size_in )
tigsToRemove[ scaffolds_[si].Tig(tpos) ] = True;
}
}
}
remove_contigs(tigsToRemove);
}
void Assembly::remove_unused_contigs(){
cout << Date() << ": removing unused contigs and renumbering" << endl;
ForceAssertEq( efastas_.size(), fastgs_.size() );
//ForceAssertEq( scaffolds_.isize(), SG_.N() );
vec<int> tigs_used( efastas_.size(), 0);
for ( size_t si = 0; si < scaffolds_.size(); si++ ){
const superb & s = scaffolds_[si];
ForceAssertGt( s.Ntigs(), 0 );
for ( int tpos = 0; tpos < s.Ntigs(); tpos++ ){
size_t tid = s.Tig(tpos);
ForceAssertLt( tid, efastas_.size() );
if ( efastas_[tid].Length1() != s.Len(tpos) ){
DPRINT5( si, tpos, tid, s.Len(tpos), efastas_[tid].Length1() );
ForceAssertEq( efastas_[tid].Length1(), s.Len(tpos) );
}
tigs_used[tid]++;
}
}
size_t unusedCt = 0;
vec<int> offsets( efastas_.size(), 0 );
int offset = 0;
for ( size_t tid = 0; tid < efastas_.size(); tid++ ){
if ( ! tigs_used[tid] ){
offsets[tid] = -1;
offset++;
unusedCt++;
}
else{ offsets[tid] = offset; }
}
cout << Date( ) << ": found " << unusedCt << " unused contigs, removing" << endl;
ForceAssertEq( offsets.size(), efastas_.size() );
for ( int tid = 0; tid < offsets.isize(); tid++ ){
if ( offsets[tid] > 0 ){
efastas_[ tid - offsets[tid] ] = efastas_[tid];
fastgs_[ tid - offsets[tid] ] = fastgs_[tid];
tigMap_[tid - offsets[tid] ] = tigMap_[tid];
}
}
efastas_.resize( efastas_.size() - offset );
fastgs_.resize( fastgs_.size() - offset );
tigMap_.resize( tigMap_.size() - offset );
ForceAssertEq( efastas_.size(), tigMap_.size() );
ForceAssertEq( efastas_.size(), fastgs_.size() );
cout << Date() << ": updating scaffolds tig ids" << endl;
for ( size_t si = 0; si < scaffolds_.size(); si++ ){
for ( int tpos = 0; tpos < scaffolds_[si].Ntigs(); tpos++ ){
int tid = scaffolds_[si].Tig(tpos);
if ( offsets[tid] >= 0 ){
int newtid = tid - offsets[tid];
ForceAssertGe( newtid, 0 );
scaffolds_[si].SetTig( tpos, newtid );
}
else{
scaffolds_[si].RemoveTigByPos( tpos );
tpos--;
}
}
}
cout << Date() << ": done with removing unused contigs" << endl;
}
void Assembly::reorder(){
// Sorting scaffolds according to size and renumbering contigs according
// to sequential appearance in scaffolds
cout << Date() << ": sorting scaffolds" << endl;
vec<int> neworder( scaffolds_.size(), vec<int>::IDENTITY );
SortSync( scaffolds_, neworder, scompare() );
PermuteVec( scaffMap_, neworder );
SG_.ReorderVertices( neworder );
renumber();
}
// renumber all the contigs sequentially according to the scaffold
void Assembly::renumber(){
cout << Date() << ": renumbering contigs for ordered scaffolds" << endl;
vec<String> otigMap;
vec<superb> oscaffolds = scaffolds_;
VecEFasta oefastas;
vec<recfastg> ofastgs;
int cTid = -1;
for ( size_t is = 0; is < scaffolds_.size(); is++ ){
for ( int tpos = 0; tpos < scaffolds_[is].Ntigs(); tpos++ ){
cTid++;
int oTid = scaffolds_[is].Tig(tpos);
oscaffolds.at(is).SetTig( tpos, cTid );
oefastas.push_back( efastas_.at(oTid) );
ofastgs.push_back( fastgs_.at(oTid) );
otigMap.push_back( tigMap_.at(oTid) );
}
}
efastas_.resize(0);
fastgs_.resize(0);
tigMap_.resize(0);
size_t newScaffoldsTotLen = 0, newScaffoldsRedLen = 0;
for ( size_t is = 0; is < scaffolds_.size(); is++ ){
newScaffoldsTotLen += scaffolds_[is].FullLength();
newScaffoldsRedLen += scaffolds_[is].ReducedLength();
}
scaffolds_ = oscaffolds;
oscaffolds.resize(0);
efastas_ = oefastas;
fastgs_ = ofastgs;
oefastas.resize(0);
ofastgs.resize(0);
tigMap_ = otigMap;
}
struct sData{
sData() : AmbEventCount_(0), MaxAmbCount_(0), RedLen_(0), MinRedLen_(0), MaxRedLen_(0),
FullLen_(0), MinFullLen_(0), MaxFullLen_(0) {};
int AmbEventCount_, MaxAmbCount_;
int RedLen_, MinRedLen_, MaxRedLen_;
int FullLen_, MinFullLen_, MaxFullLen_;
basevector seq_, minseq_, maxseq_;
basevector seq_rc_, minseq_rc_, maxseq_rc_;
};
void Assembly::dedup( const Bool Exact ) {
// Remove duplicate scaffolds.
cout << Date() << ": removing duplicate scaffolds: " << endl;
cout << Date() << ": initial number of scaffolds = " << scaffolds_.size() << endl;
// cononicalize efastas
VecEFasta cefastas( efastas_.size() );
VecEFasta cefastas_rc( efastas_.size() );
for ( size_t ci = 0; ci < efastas_.size(); ci++ ){
efastas_[ci].Canonicalize( cefastas[ci] );
ValidateEfastaRecord( cefastas[ci] );
efasta eseq_rc = efastas_[ci];
eseq_rc.ReverseComplement();
eseq_rc.Canonicalize( cefastas_rc[ci] );
ValidateEfastaRecord( cefastas_rc[ci] );
}
// compute scaffold data
vec< vec< vec<basevector> > > s2altTigs( scaffolds_.size() );
vec<sData> s2data( scaffolds_.size() );
for ( int si = 0; si < scaffolds_.isize(); si++ ){
s2altTigs[si].resize( scaffolds_[si].Ntigs() );
for ( int i = 0; i < scaffolds_[si].Ntigs(); i++ ){
int ti = scaffolds_[si].Tig(i);
efasta& tigi = cefastas[ ti ];
s2data[si].AmbEventCount_ += tigi.AmbEventCount();
s2data[si].MaxAmbCount_ += tigi.AmbCount();
s2data[si].MinRedLen_ += tigi.MinLength();
s2data[si].MaxRedLen_ += tigi.MaxLength();
s2data[si].MinFullLen_ += tigi.MinLength();
s2data[si].MaxFullLen_ += tigi.MaxLength();
s2data[si].RedLen_ += tigi.Length1();
s2data[si].FullLen_ += tigi.Length1();
if ( i < scaffolds_[si].Ntigs() -1 ){
s2data[si].MinFullLen_ += scaffolds_[si].Gap(i) - scaffolds_[si].Dev(i);
s2data[si].MaxFullLen_ += scaffolds_[si].Gap(i) + scaffolds_[si].Dev(i);
s2data[si].FullLen_ += scaffolds_[si].Gap(i);
}
fastavector fseq;
tigi.FlattenMinTo( fseq );
s2altTigs[si][i].push_back( fseq.ToBasevector() );
if ( tigi.Ambiguities() > 0 ){
tigi.FlattenTo( fseq );
s2altTigs[si][i].push_back( fseq.ToBasevector() );
tigi.FlattenMaxTo( fseq );
s2altTigs[si][i].push_back( fseq.ToBasevector() );
}else{
s2altTigs[si][i].push_back( fseq.ToBasevector() );
s2altTigs[si][i].push_back( fseq.ToBasevector() );
}
}
DPRINT3( si, s2data[si].AmbEventCount_, s2data[si].MaxAmbCount_ );
}
for ( int si = 0; si < scaffolds_.isize(); si++ ) {
int Ni = scaffolds_[si].Ntigs();
basevector seq, minseq, maxseq;
for ( int ci = 0; ci < Ni; ci++ ){
minseq = Cat( minseq, s2altTigs[si][ci][0] );
seq = Cat( seq, s2altTigs[si][ci][1] );
maxseq = Cat( maxseq, s2altTigs[si][ci][2] );
if ( ci < Ni -1 )
for ( int pi = 0; pi < scaffolds_[si].Gap(ci); pi++ ){
seq.push_back(0); minseq.push_back(0); maxseq.push_back(0);
}
}
s2data[si].seq_ = seq; s2data[si].minseq_ = minseq; s2data[si].maxseq_ = maxseq;
basevector seq_rc, minseq_rc, maxseq_rc;
for ( int i = 0; i < Ni; i++ ){
int ci = Ni -1 -i;
basevector ci_minseq_rc = s2altTigs[si][ci][0]; ci_minseq_rc.ReverseComplement();
basevector ci_seq_rc = s2altTigs[si][ci][1]; ci_seq_rc.ReverseComplement();
basevector ci_maxseq_rc = s2altTigs[si][ci][2]; ci_maxseq_rc.ReverseComplement();
minseq_rc = Cat( minseq_rc, ci_minseq_rc );
seq_rc = Cat( seq_rc, ci_seq_rc );
maxseq_rc = Cat( maxseq_rc, ci_maxseq_rc );
if ( ci > 0 )
for ( int pi = 0; pi < scaffolds_[si].Gap(ci-1); pi++ ){
seq_rc.push_back(0); minseq_rc.push_back(0); maxseq_rc.push_back(0);
}
}
ForceAssertEq( minseq.size(), minseq_rc.size() );
ForceAssertEq( seq.size(), seq_rc.size() );
ForceAssertEq( maxseq.size(), maxseq_rc.size() );
s2data[si].seq_rc_ = seq_rc; s2data[si].minseq_rc_ = minseq_rc; s2data[si].maxseq_rc_ = maxseq_rc;
}
int removed_count = 0;
int removed_size = 0;
vec <Bool> to_remove ( scaffolds_.size(), False );
for ( int si = 0; si < scaffolds_.isize(); si++ ) {
if ( to_remove[si] ) continue;
int Ni = scaffolds_[si].Ntigs();
for ( int sj = si + 1; sj < scaffolds_.isize(); sj++ ) {
if ( to_remove[sj] ) continue;
int Nj = scaffolds_[sj].Ntigs();
ForceAssertEq( Nj, s2altTigs[sj].isize() );
// roughly check if scaffolds could be duplicates of each other
if ( Ni != Nj )
continue;
if ( s2data[si].FullLen_ != s2data[sj].FullLen_ &&
( s2data[si].MaxFullLen_ < s2data[sj].MinFullLen_ ||
s2data[sj].MaxFullLen_ < s2data[si].MinFullLen_ ) )
continue;
if ( s2data[si].RedLen_ != s2data[sj].RedLen_ &&
( s2data[si].MaxRedLen_ < s2data[sj].MinRedLen_ ||
s2data[sj].MaxRedLen_ < s2data[si].MinRedLen_ ) )
continue;
cout << "\n\n\n";
cout << Date() << ": --------- comparing scaffolds:" << endl;
DPRINT2( si, sj );
DPRINT2( s2data[si].AmbEventCount_, s2data[sj].AmbEventCount_ );
DPRINT2( s2data[si].MaxAmbCount_, s2data[sj].MaxAmbCount_ );
DPRINT2( s2data[si].seq_.size(), s2data[sj].seq_.size());
// more detailed check
vec<int> areRcs( Ni, 0 );
vec<int> areEqual( Ni, 0 );
for ( int ci = 0; ci < Ni; ci++ ){
if ( ci > 0 && areEqual[ci-1] != 1 && areRcs[ci-1] != 1 ) continue;
int ti = scaffolds_[si].Tig(ci);
vec< vec<String> > iblocks;
cefastas[ti].GetBlocks( iblocks );
if ( ci == 0 || areEqual[ci-1] == 1 ){
// checking duplication
int cje = ci;
int tje = scaffolds_[sj].Tig(cje);
if ( cefastas[ti] == cefastas[tje] ){
areEqual[ci] = 1;
}else if ( cefastas[ti].AmbEventCount() == cefastas[tje].AmbEventCount() ){
vec< vec<String> > eblocks;
cefastas[tje].GetBlocks( eblocks );
Bool pathEqual = True;
for ( int ib = 0; ib < iblocks.isize(); ib++ ){
if ( iblocks[ib].size() == 1 && eblocks[ib].size() == 1 ){
if ( iblocks[ib][0] != eblocks[ib][0] ){
pathEqual =False;
break;
}
}else{
Bool foundEqualRoute = False;
for ( int ir1 = 0; ir1 < iblocks[ib].isize(); ir1++ )
for ( int ir2 = 0; ir2 < eblocks[ib].isize(); ir2++ )
if ( iblocks[ib][ir1] == eblocks[ib][ir2] ){
foundEqualRoute = True;
break;
}
if ( ! foundEqualRoute ){
pathEqual = False;
break;
}
}
}
if ( pathEqual ) areEqual[ci] = 1;
}
}
if ( ci == 0 || areRcs[ci-1] == 1 ){
// checking reverse duplication
int cjr = Nj -ci -1;
int tjr = scaffolds_[sj].Tig(cjr);
efasta eseq_rc = cefastas_rc[tjr];
if ( cefastas[ti] == eseq_rc ){
areRcs[ci] = 1;
}else if ( cefastas[ti].AmbEventCount() == eseq_rc.AmbEventCount() ){
vec< vec<String> > rblocks;
eseq_rc.GetBlocks( rblocks );
Bool pathEqual = True;
for ( int ib = 0; ib < iblocks.isize(); ib++ ){
if ( iblocks[ib].size() == 1 && rblocks[ib].size() == 1 ){
if ( iblocks[ib][0] != rblocks[ib][0] ){
pathEqual =False;
break;
}
}else{
Bool foundEqualRoute = False;
for ( int ir1 = 0; ir1 < iblocks[ib].isize(); ir1++ )
for ( int ir2 = 0; ir2 < rblocks[ib].isize(); ir2++ )
if ( iblocks[ib][ir1] == rblocks[ib][ir2] ){
foundEqualRoute = True;
break;
}
if ( ! foundEqualRoute ){
pathEqual = False;
break;
}
}
}
if ( pathEqual ) areRcs[ci] = 1;
}
}
}
if ( Sum( areRcs ) > 0 || Sum( areEqual ) > 0 )
DPRINT4( areRcs.size(), Sum( areRcs ), areEqual.size(), Sum( areEqual ) );
if ( Sum( areRcs ) == areRcs.isize() || Sum( areEqual ) == areEqual.isize() ){
String type = Sum( areRcs ) == areRcs.isize() ? "reverse complement" : "duplicate";
cout << Date() << ": scaffold " << sj << "(l=" << scaffolds_[si].FullLength() << ") is " << type << " of " << si
<< " (length " << scaffolds_[si].FullLength() << ")" << endl;
to_remove[sj] = True;
removed_count++;
removed_size += scaffolds_[sj].ReducedLength();
}else if ( ! Exact) {
cout << "\n";
cout << Date() << ": ------------- RUNNING BANDED SMITH-WATERMAN -------------------\n\n";
int amb_diff_count = Max( s2data[si].maxseq_.isize() - s2data[si].minseq_.isize(),
s2data[sj].maxseq_.isize() - s2data[sj].minseq_.isize() );
int amb_event_count = Max( s2data[si].AmbEventCount_, s2data[sj].AmbEventCount_ );
int amb_max_count = Max( s2data[si].MaxAmbCount_, s2data[sj].MaxAmbCount_ );
DPRINT3( amb_diff_count, amb_event_count, amb_max_count );
// no exact match, check alignment
for ( int iter = 0; iter < 3; iter++ ){
if ( to_remove[sj] ) continue;
basevector si_seq;
if ( iter == 0 ) si_seq = s2data[si].seq_;
else if ( iter == 1 ) si_seq = s2data[si].minseq_;
else if ( iter == 2 ) si_seq = s2data[si].maxseq_;
basevector sj_seq;
if ( iter == 0 ) sj_seq = s2data[sj].seq_;
else if ( iter == 1 ) sj_seq = s2data[sj].minseq_;
else if ( iter == 2 ) sj_seq = s2data[sj].maxseq_;
// flank sequences with the same ends for the case where efasta amibugity is at the edge
Bool FlankSequences = False;
if ( efastas_[ scaffolds_[si].Tig(0) ].front() == '{' || efastas_[ scaffolds_[sj].Tig(0) ].front() == '{' ||
efastas_[ scaffolds_[si].Tig(0) ].back() == '}' || efastas_[ scaffolds_[sj].Tig(0) ].back() == '}' )
FlankSequences = True;
basevector flank;
flank.SetFromString("AAAAAAAAAA");
if ( FlankSequences ){
cout << Date() << " Flanking" << endl;
si_seq = Cat( flank, si_seq, flank );
sj_seq = Cat( flank, sj_seq, flank );
}
align aF;
int min_overlap = Min( si_seq.size(), sj_seq.size() );
DPRINT( min_overlap );
int errorsF = 0;
int lenDiff = abs( si_seq.isize() - sj_seq.isize() );
int bandwidth = 2 * lenDiff;
int maxErr = amb_max_count + amb_event_count + lenDiff + 1 + round( 0.0001 * (double)si_seq.isize() );
DPRINT( maxErr );
bandwidth = Max( bandwidth, 10 );
DPRINT( bandwidth );
cout << Date() << ": aligning forward" << endl;
float scoreF =
SmithWatBandedA2<unsigned short>(si_seq, sj_seq, 0, bandwidth, aF, errorsF );
look_align laF;
laF.ResetFromAlign( aF, si_seq, sj_seq );
DPRINT5( scoreF, laF.a.extent1(), laF.a.extent2(), errorsF, maxErr );
if ( ( laF.a.extent1() >= min_overlap || laF.a.extent2() >= min_overlap ) &&
errorsF <= maxErr && laF.Fw1() ){
cout << Date() << ": scaffold " << sj << "(l=" << scaffolds_[si].FullLength() << ") is a copy of " << si
<< " (length " << scaffolds_[si].FullLength() << ")" << endl;
to_remove[sj] = True;
removed_count++;
removed_size += scaffolds_[sj].ReducedLength();
}else{
basevector sj_seq_rc;
if ( iter == 0 ) sj_seq_rc = s2data[sj].seq_rc_;
else if ( iter == 1 ) sj_seq_rc = s2data[sj].minseq_rc_;
else if ( iter == 2 ) sj_seq_rc = s2data[sj].maxseq_rc_;
if ( FlankSequences )
sj_seq_rc = Cat( flank, si_seq, flank );
align aR;
int errorsR = 0;
cout << Date() << ": aligning reverse" << endl;
int scoreR =
SmithWatBandedA2<unsigned short>(si_seq, sj_seq_rc, 0, bandwidth, aR, errorsR );
look_align laR;
laR.ResetFromAlign( aR, si_seq, sj_seq_rc );
DPRINT5( scoreR, laR.a.extent1(), laR.a.extent2(), errorsR, maxErr );
if ( ( laR.a.extent1() >= min_overlap || laR.a.extent2() >= min_overlap ) &&
errorsR <= maxErr && laR.Fw1() ){
cout << Date() << ": scaffold " << sj << "(l=" << scaffolds_[si].FullLength() << ") is reverse-complement of " << si
<< " (length " << scaffolds_[si].FullLength() << ")" << endl;
to_remove[sj] = True;
removed_count++;
removed_size += scaffolds_[sj].ReducedLength();
}
}
cout << Date() << ": vvvvvvvvvvvvvv DONE WIHT ALIGNMENT vvvvvvvvvvvvvvv\n\n\n" << endl;
}
}
}
}
EraseIf( scaffolds_, to_remove );
EraseIf( scaffMap_, to_remove );
EraseIf( s2data, to_remove );
EraseIf( s2altTigs, to_remove );
vec<int> verts_to_remove;
for ( int i = 0; i < to_remove.isize(); i++ )
if ( to_remove[i] ){
SG_.DeleteEdgesAtVertex( i );
verts_to_remove.push_back( i );
}
SG_.RemoveEdgelessVertices( verts_to_remove );
cout << Date() << ": removed " << removed_count << " duplicate scaffolds"
<< " (" << removed_size << " bases)" << endl;
cout << Date() << ": final number of scaffolds = " << scaffolds_.size() << endl;
remove_unused_contigs();
}
void Assembly::dedup2() {
// Remove scaffolds that are possibly duplicate
// The criteria are:
// 1. two scaffolds have same number of contigs (n_contig)
// 2. n_contig >= 2
// 3. Each contig and gap much match
// - Gaps are matched whan [ gap_size +/- 3 * std ] overlap
// - Contigs are matched when
// - perfect efasta match for contig size < 50,000
// - 1/100 mismatch kmer rate for contig size >= 50,000 (!!!!! this is only meant to be temporary fix to the problem)
// 4. Both rc and fw duplicates are checked
int VERBOSITY = 0;
const int EfastaMatchSize = 50 * 1000;
const int MaxDev = 3;
const double MaxMismatchRate = 0.01;
cout << Date() << ": " << "Remove possible duplicate scaffolds" << endl;
cout << Date() << ": " << "initial number of scaffolds = " << scaffolds_.size() << endl;
int removed_count = 0;
int removed_size = 0;
vec <Bool> to_remove ( scaffolds_.size(), False );
for ( int si = 0; si < scaffolds_.isize(); si++ ) {
if ( to_remove[si] ) continue;
int Ni = scaffolds_[si].Ntigs();
//if ( Ni < 2 ) continue;
for ( int sj = si + 1; sj < scaffolds_.isize(); sj++ ) {
if ( to_remove[sj] ) continue;
int Nj = scaffolds_[sj].Ntigs();
if ( Nj != Ni ) continue;
//VERBOSITY = ( si == 1 && sj == 6 ? 1: 0 );
// check scaffolds duplicate in two passes: fw in pass=0, rc in pass=1
for( int pass = 0; pass < 2; pass++ ) {
if ( VERBOSITY >= 1 )
cout << Date() << ": " << "pass= " << pass << endl;
if ( VERBOSITY >= 1 )
cout << Date() << ": " << "check gap " << endl ;
// compare the gap of two scaffolds
bool gap_match = true;
for ( int igap = 0; igap < Ni-1; ++igap ) {
int gap1 = scaffolds_[si].Gap(igap);
int dev1 = scaffolds_[si].Dev(igap);
int gap2 = scaffolds_[sj].Gap( pass == 0 ? igap : Ni -2 - igap);
int dev2 = scaffolds_[sj].Dev( pass == 0 ? igap : Ni -2 - igap);
if ( IntervalOverlap( gap1 - MaxDev * dev1, gap1 + MaxDev * dev1 + 1,
gap2 - MaxDev * dev2, gap2 + MaxDev * dev2 + 1) == 0 ) {
gap_match = false;
break;
}
}
if ( !gap_match) continue;
if ( VERBOSITY >= 1 )
cout << Date() << ": " << "check contigs " << endl ;
// check if the contigs matchs
bool tig_match = true;
if ( VERBOSITY >= 1 )
cout<< Date() << " ncontigs= " << Ni << endl;
for ( int itig = 0; itig < Ni; ++itig) {
if ( VERBOSITY >= 1 )
cout << Date() << ": check contig " << itig << ": "
<< " vs " << scaffolds_[sj].Tig( pass == 0 ? itig : Nj -1 -itig ) << endl;
efasta &tigi = efastas_[ scaffolds_[si].Tig(itig) ];
efasta &tigj = efastas_[ scaffolds_[sj].Tig( pass == 0 ? itig : Nj -1 -itig ) ] ;
if ( VERBOSITY >= 1 )
cout << Date() << ": tigi.size()= " << tigi.size() << endl;
if ( VERBOSITY >= 1 )
cout << Date() << ": tigj.size()= " << tigj.size() << endl;
// check if contig sizes match
int tig_size = ( tigi.size() + tigj.size() ) /2;
int MaxMismatch = tig_size * MaxMismatchRate ;
if ( abs( (int)tigi.size() - (int)tigj.size() ) > MaxMismatch ) { tig_match = false; break; }
// require perfect efasta match if contig size less than EfastaMatchSize
if ( tig_size < EfastaMatchSize ) {
if ( VERBOSITY >= 1 )
cout << Date() << ": check efasta " << endl;
vec<basevector> v_ibases, v_jbases;
tigi.ExpandTo(v_ibases);
tigj.ExpandTo(v_jbases);
if ( pass == 1 )
for ( size_t k = 0; k < v_jbases.size(); ++k ) { v_jbases[k].ReverseComplement(); }
bool foundEqual = False;
for ( size_t vi = 0; vi < v_ibases.size() && ! foundEqual; vi++ ){
for ( size_t vj = 0; vj < v_jbases.size(); vj++ ){
if ( v_jbases[vj].size() != v_ibases[vi].size() )
continue;
basevector jbases = v_jbases[vj];
if ( jbases == v_ibases[vi] ){
foundEqual = True;
break;
}
}
}
if ( ! foundEqual ) {
tig_match = false;
break;
}
}
// larger contig size. do kmer matching
else {
if ( VERBOSITY >= 1 )
cout << Date() << ": check kmers " << endl;
basevector base1, base2;
tigi.FlattenTo( base1 );
tigj.FlattenTo( base2 );
if ( pass == 1 ) base2.ReverseComplement();
const int K = 24;
ForceAssertGt( base1.isize( ), K );
vec< basevector > kmers1( base1.isize( ) - K + 1);
#pragma omp parallel for
for ( int jz = 0; jz <= base1.isize( ) - K; jz += 1000 )
for ( int j = jz; j <= Min( base1.isize( ) - K, jz + 1000 ); j++ )
kmers1[j].SetToSubOf( base1, j, K );
ParallelUniqueSort(kmers1);
ForceAssertGt( base2.isize( ), K );
vec< basevector > kmers2( base2.isize( ) - K + 1);
#pragma omp parallel for
for ( int jz = 0; jz <= base2.isize( ) - K; jz += 1000 )
for ( int j = jz; j <= Min( base2.isize( ) - K, jz + 1000 ); j++ )
kmers2[j].SetToSubOf( base2, j, K );
ParallelUniqueSort(kmers2);
// compare how many kmers are identical for the two sorted list
int nkmer1 = kmers1.size(), nkmer2 = kmers2.size();
int nkmer = (nkmer1 + nkmer2)/2;
int count = 0;
for( size_t i = 0, j = 0; i < kmers1.size() && j < kmers2.size(); ) {
if ( kmers1[i] > kmers2[j] ) j++;
else if ( kmers1[i] < kmers2[j] ) i++;
else count++, i++, j++;
}
if ( VERBOSITY >= 1 ) {
cout << Date() << ": nkmer= " << nkmer << endl;
cout << Date() << ": duplicate= " << count << endl;
}
if ( abs(nkmer - count) > int( nkmer * MaxMismatchRate) ) {
tig_match = false;
break;
}
}
} // for itig
if ( !tig_match ) continue;
// ---------------------------------------------------------------------------
// Now we concluded that the two scaffolds are duplicate. Remove the later one
// --------------------------------------------------------------------------
{
String type = pass == 0 ? "fw duplicate" : "rc duplicate";
cout << Date() << ": scaffold " << sj << " is " << type << " of " << si
<< " (length " << scaffolds_[si].FullLength() << ")" << endl;
to_remove[sj] = True;
removed_count++;
removed_size += scaffolds_[sj].ReducedLength();
break; // do not go second pass
}
} // end pass 2
} // end for sj
} // end for si
// now remove the duplicate scaffolds
{
EraseIf( scaffolds_, to_remove );
EraseIf( scaffMap_, to_remove );
vec<int> verts_to_remove;
for ( int i = 0; i < to_remove.isize(); i++ )
if ( to_remove[i] ){
SG_.DeleteEdgesAtVertex( to_remove[i] );
verts_to_remove.push_back( i );
}
SG_.RemoveEdgelessVertices( verts_to_remove );
}
cout << Date() << ": removed " << removed_count << " duplicate scaffolds"
<< " (" << removed_size << " bases)" << endl;
cout << Date() << ": final number of scaffolds = " << scaffolds_.size() << endl;
remove_unused_contigs();
}
void Assembly::dedup_exact() {
// Remove duplicate scaffolds...currently only handles case of singleton contigs
// which are duplicates fw or rc. --bruce 8 Jun 2011
cout << Date() << ": removing duplicate scaffolds: " << endl;
cout << Date() << ": initial number of scaffolds = " << scaffolds_.size() << endl;
int removed_count = 0;
int removed_size = 0;
vec<int> remaining( scaffolds_.size(), vec<int>::IDENTITY );
vec<int> verts_to_remove;
for ( int si = 0; si < scaffolds_.isize(); si++ ) {
if (scaffolds_[si].Ntigs() != 1) continue;
for ( int sj = si + 1; sj < scaffolds_.isize(); sj++ ) {
if (scaffolds_[sj].Ntigs() != 1) continue;
efasta &tigi = efastas_[scaffolds_[si].Tig(0)];
efasta &tigj = efastas_[scaffolds_[sj].Tig(0)];
if (tigi.size() != tigj.size()) continue;
basevector ibases, jbases;
tigi.FlattenTo(ibases);
tigj.FlattenTo(jbases);
bool rc = False;
if (ibases != jbases) {
jbases.ReverseComplement();
rc = True;
if (ibases != jbases) continue;
}
/*
cout << "scaffold " << sj << " duplicate of " << si
<< " (length " << scaffolds_[si].FullLength()
<< (rc ? " rc" : "") << ")" << endl;
*/
scaffolds_.erase( scaffolds_.begin() + sj );
scaffMap_.erase( scaffMap_.begin() + sj );
verts_to_remove.push_back( remaining[sj] );
SG_.DeleteEdgesAtVertex( remaining[sj] );
remaining.erase( remaining.begin() + sj );
sj--;
removed_count++;
removed_size += ibases.size();
}
}
SG_.RemoveEdgelessVertices( verts_to_remove );
cout << Date() << ": removed " << removed_count << " duplicate scaffolds"
<< " (" << removed_size << " bases)" << endl;
cout << Date() << ": final number of scaffolds = " << scaffolds_.size() << endl;
remove_unused_contigs();
}
void Assembly::set_min_gaps( const int min_gap ){
cout << Date() << ": resetting gaps < " << min_gap << endl;
for ( size_t is = 0; is < scaffolds_.size(); is++ )
for ( int tpos = 0; tpos < scaffolds_[is].Ntigs() -1; tpos++ )
if ( scaffolds_[is].Gap(tpos) < min_gap ) {
scaffolds_[is].SetGap( tpos, min_gap );
scaffolds_[is].SetDev( tpos, 0 );
}
}
void Assembly::WriteFastg( const String head_out ) const {
// fastg_meta FGM;
Ofstream(out_g, head_out + ".assembly.fastg");
// out_g << FGM.GetFileHeader( head_out ) << "\n";
out_g << fastg_meta::GetFileHeader( head_out ) << "\n";
for (size_t is = 0; is < scaffolds_.size(); is++) {
const superb& S = scaffolds_[is];
headfastg hfg( ToString(is), SG_.From(is) );
basefastg bfg;
for ( int it = 0; it < S.Ntigs(); it++) {
int tigId = S.Tig( it );
bfg += basefastg( efastas_[tigId] );
if ( it < S.Ntigs() -1 )
bfg += basefastg( S.Gap(it), S.Dev(it) );
}
recfastg rfg( hfg, bfg );
rfg.Print( out_g );
}
// out_g << FGM.GetFileFooter() << "\n";
out_g << fastg_meta::GetFileFooter() << "\n";
}
void Assembly::Write( const String head_out ) const {
// writing output
cout << Date() << ": writing output files" << endl;
WriteSuperbs( head_out + ".superb", scaffolds_ );
WriteSummary( head_out + ".summary", scaffolds_ );
Ofstream( efout, head_out + ".contigs.efasta" );
for ( size_t id = 0; id < efastas_.size(); id++ )
efastas_[id].Print(efout, "contig_" + ToString(id) );
}
void Assembly::WriteExtra( const String head_out ) const{
vec<fastavector> fastas(efastas_.size());
for ( size_t id = 0; id < efastas_.size(); id++ )
efastas_[id].FlattenTo( fastas[id] );
Ofstream( fout, head_out + ".contigs.fasta" );
for ( size_t id = 0; id < fastas.size(); id++ )
fastas[id].Print(fout, "contig_" + ToString(id) );
{
vecfastavector vec_tigs;
for ( size_t i = 0; i < fastas.size( ); i++ )
vec_tigs.push_back_reserve( fastas[i] );
vec_tigs.WriteAll( head_out + ".contigs.vecfasta" );
}
vecbasevector bases( efastas_.size() );
for ( size_t id = 0; id < efastas_.size(); id++ )
efastas_[id].FlattenTo( bases[id] );
bases.WriteAll( head_out + ".contigs.fastb" );
Ofstream( cmout, head_out + ".contigs.mapping" );
for ( size_t id = 0; id < tigMap_.size(); id++ )
cmout << ToString(id) + " from " + ToString( tigMap_[id] ) << "\n";
Ofstream( smout, head_out + ".superb.mapping" );
for ( size_t is = 0; is < scaffMap_.size(); is++ )
smout << ToString(is) + " from " + ToString( scaffMap_[is] ) << "\n";
WriteScaffoldedEFasta( head_out + ".assembly.efasta", efastas_, scaffolds_ );
WriteScaffoldedFasta( head_out + ".assembly.fasta", fastas, scaffolds_ );
BinaryWriter::writeFile( head_out + ".scaffold_graph.", SG_ );
}
| 35.253211
| 170
| 0.592463
|
bayolau
|
c7bbb0a147bc75aa65e0234f9b46e003970d8cda
| 9,058
|
cpp
|
C++
|
src/GenModel.cpp
|
StebQC/GenModel
|
6590293cd541ebb3bba1e73b04c6d014dfc633f2
|
[
"MIT"
] | null | null | null |
src/GenModel.cpp
|
StebQC/GenModel
|
6590293cd541ebb3bba1e73b04c6d014dfc633f2
|
[
"MIT"
] | null | null | null |
src/GenModel.cpp
|
StebQC/GenModel
|
6590293cd541ebb3bba1e73b04c6d014dfc633f2
|
[
"MIT"
] | null | null | null |
#include "GenModel.h"
//#include "SqlCaller.h"
#include <math.h>
#include <time.h>
GenModel::GenModel()
{
version = "genmodellean-0.0.15 build 0001";
hassolution = false;
bcreated = false;
binit = false;
nc = 0;
nr = 0;
solverdata = NULL;
}
double GenModel::FindConstraintMaxLhs(long row)
{
double total = 0.0;
for(int i = 0; i < int(consts[row].cols.size()); i++)
total += (consts[row].coefs[i] >= 0 ? vars.ub[consts[row].cols[i]] : vars.lb[consts[row].cols[i]])*consts[row].coefs[i];
return total;
}
double GenModel::FindConstraintMinLhs(long row)
{
double total = 0.0;
for(int i = 0; i < int(consts[row].cols.size()); i++)
total += (consts[row].coefs[i] >= 0 ? vars.lb[consts[row].cols[i]] : vars.ub[consts[row].cols[i]])*consts[row].coefs[i];
return total;
}
long GenModel::MakeConstraintFeasible(long row)
{
if(consts[row].sense == 'L')
{
double min = FindConstraintMinLhs(row);
if(min > consts[row].lrhs)
consts[row].lrhs = min;
}
else if(consts[row].sense == 'G')
{
double max = FindConstraintMaxLhs(row);
if(max < consts[row].lrhs)
consts[row].lrhs = max;
}
else if(consts[row].sense == 'R')
{
double min = FindConstraintMinLhs(row);
double max = FindConstraintMaxLhs(row);
if(max < consts[row].lrhs)
consts[row].lrhs = max;
else if(min > consts[row].urhs)
consts[row].urhs = min;
}
return 0;
}
long GenModel::SetLongParam(string param, long val)
{
longParam[param] = val;
return 0;
}
long GenModel::SetDblParam(string param, double val)
{
dblParam[param] = val;
return 0;
}
long GenModel::SetBoolParam(string param, bool val)
{
boolParam[param] = val;
return 0;
}
long GenModel::SetStrParam(string param, string val)
{
strParam[param] = val;
return 0;
}
long GenModel::ThrowError(string error)
{
printf("%s\n", error.c_str());
throw error;
}
long GenModel::PrintObjVal()
{
printf("obj : %f\n", objval);
return 0;
}
long GenModel::PrintSol()
{
//printf("obj : %f\n", objval);
for(long i = 0; i < long(vars.n); i++)
{
printf("%s : %f\n", vars.name[i].c_str(), vars.sol[i]);
}
return 0;
}
long GenModel::PrintModel()
{
return 0;
}
long GenModel::PrintSol(string v)
{
//printf("obj : %f\n", objval);
if(vars.offset.count(v) == 0)
return 0;
map<string, long>::iterator it = vars.offset.find(v);
long deb = it->second;
long fin = vars.n;
for(it = vars.offset.begin(); it != vars.offset.end(); it++)
{
if(it->second > deb && it->second < fin)
fin = it->second;
}
for(long i = deb; i < fin; i++)
{
printf("%s : %f\n", vars.name[i].c_str(), vars.sol[i]);
}
return 0;
}
long GenModel::PrintSolNz()
{
//printf("obj : %f\n", objval);
for(long i = 0; i < long(vars.n); i++)
{
if(fabs(vars.sol[i]) > 0.000001)
printf("%s : %f\n", vars.name[i].c_str(), vars.sol[i]);
}
return 0;
}
long GenModel::PrintSolNz(string v)
{
//printf("obj : %f\n", objval);
if(vars.offset.count(v) == 0)
return 0;
map<string, long>::iterator it = vars.offset.find(v);
long deb = it->second;
long fin = vars.n;
for(it = vars.offset.begin(); it != vars.offset.end(); it++)
{
if(it->second > deb && it->second < fin)
fin = it->second;
}
for(long i = deb; i < fin; i++)
{
if(fabs(vars.sol[i]) > 0.000001)
printf("%s : %f\n", vars.name[i].c_str(), vars.sol[i]);
}
return 0;
}
long ModConsts::AddNz(long c, double v)
{
cols.push_back(c);
coefs.push_back(v);
nz++;
return 0;
}
long GenModel::AddConst(string cname)
{
ci[cname] = nc;
consts.push_back(ModConsts());
consts.back().name = cname;
nc++;
return 0;
}
long GenModel::AddConst(string cname, double rhs, char sense)
{
AddConst(cname);
consts.back().lrhs = rhs;
consts.back().sense = sense;
return 0;
}
long GenModel::AddNz(long row, long col, double val)
{
consts[row].AddNz(col, val);
return 0;
}
long GenModel::AddNzToLast(long col, double val)
{
consts.back().AddNz(col, val);
return 0;
}
long GenModel::SetNumbers()
{
nr = consts.size();
nc = vars.n; //vars.obj.size();
nz = 0;
for(long i = 0; i < long(nr); i++)
{
consts[i].nz = consts[i].cols.size();
nz+=consts[i].nz;
}
return 0;
}
long GenModel::AddVar(string nn, double o, double l, double u, char t)
{
vars.AddVar(nn, o, l, u, t);
return 0;
}
long GenModel::AddVars(string nn, long size, double o, double l, double u, char t)
{
vars.AddVars(nn, size, o, l, u, t);
return 0;
}
long GenModel::SetQpCoef(long i, long j, double val)
{
vars.SetQpCoef(i, j, val);
return 0;
}
long GenModel::AddModelColumn(int count, int* ind, double* val, double obj, double lb, double ub, string name, char type)
{
AddVar(name, obj, lb, ub, type);
for(long i = 0; i < count; i++)
AddNz(ind[i], vars.n-1, val[i]);
return 0;
}
long GenModel::AddModelCol(vector<int>& ind, vector<double>& val, double obj, double lb, double ub, string name, char type)
{
AddVar(name, obj, lb, ub, type);
for(long i = 0; i < long(ind.size()); i++)
AddNz(ind[i], vars.n-1, val[i]);
return 0;
}
long GenModel::AddModelRow(vector<int>& ind, vector<double>& val, double rhs, char sense, string name)
{
AddConst(name, rhs, sense);
for(long i = 0; i < long(ind.size()); i++)
AddNzToLast(ind[i], val[i]);
return 0;
}
long GenModel::AddSolverColumn(int count, int* ind, double* val, double obj, double lb, double ub, string name, char type)
{
return 0;
}
long GenModel::ChangeBulkBounds(int count, int * ind, char * type, double * vals)
{
throw string("ChangeBulkBounds() Not implemented");
return 0;
}
long GenModel::ChangeBulkObjectives(int count, int * ind, double * vals)
{
throw string("ChangeBulkObjectives() Not implemented");
return 0;
}
long GenModel::ChangeBulkNz(int count, int* rind, int* cind, double* vals)
{
throw string("ChangeBulkNz() Not implemented");
return 0;
}
long GenModel::SetObjUpperCutoff(double value)
{
return 0;
}
long GenModel::WriteProblemToLpFile(string filename)
{
throw string("WriteProblemToLpFile() Not implemented");
return 0;
}
long GenModel::WriteSolutionToFile(string filename)
{
throw string("WriteSolutionToFile() Not implemented");
return 0;
}
void GenModel::AttachCallback(bool(*callbackFunction) (double obj, double bestBound, bool feasibleSolution))
{
return;
}
double GenModel::GetMIPBestBound()
{
return 0;
}
long GenModel::ChangeBulkRHS(int count, int* ind, double* vals)
{
return 0;
}
long GenModel::DeleteMipStarts()
{
throw string("DeleteMipStarts() Not implemented");
return 0;
}
double GenModel::GetMIPRelativeGap()
{
throw string("GetMIPRelativeGap() Not implemented");
return 0.0;
}
long GenModel::ExportModel(string cname)
{
return 0;
}
long GenModel::ExportConflict(string cname)
{
return 0;
}
long ModVars::AddVar(string nn, double o, double l, double u, char t)
{
//offset[nn] = n;
name.push_back(nn);
obj.push_back(o);
ub.push_back(u);
lb.push_back(l);
type.push_back(t);
n++;
return 0;
}
long ModVars::AddVars(string nn, long size, double o, double l, double u, char t)
{
offset[nn] = n;
char c[4096];
for(long i = 0; i < size; i++)
{
snprintf(c, 4096, "%s_%ld", nn.c_str(), i);
AddVar(string(c), o, l, u, t);
}
return 0;
}
long ModVars::SetQpCoef(long i, long j, double val)
{
qi.push_back(i);
qj.push_back(j);
qobj.push_back(val);
return 0;
}
long ModVars::Print()
{
for(long i = 0; i < long(n); i++)
{
printf("%ld: %s obj=%f [%c]\n", i, name[i].c_str(), obj[i], type[i]);
}
return 0;
}
template <typename T>
void _freeall(T& t)
{
T tmp;
t.swap(tmp);
}
long GenModel::ClearStructure()
{
consts.clear();
_freeall(consts);
ci.clear();
_freeall(ci);
vars.name.clear();
_freeall(vars.name);
vars.obj.clear();
_freeall(vars.obj);
vars.type.clear();
_freeall(vars.type);
vars.offset.clear();
_freeall(vars.offset);
vars.ub.clear();
_freeall(vars.ub);
vars.lb.clear();
_freeall(vars.lb);
vars.sol.clear();
_freeall(vars.sol);
vars.rc.clear();
_freeall(vars.rc);
vars.qobj.clear();
_freeall(vars.qobj);
vars.qi.clear();
_freeall(vars.qi);
vars.qj.clear();
_freeall(vars.qj);
return 0;
}
genmodel_param dbl2param(double val)
{
genmodel_param ret;
ret.dblval = val;
return ret;
}
genmodel_param long2param(long val)
{
genmodel_param ret;
ret.longval = val;
return ret;
}
genmodel_param str2param(string val)
{
genmodel_param ret;
ret.strval = val.c_str();
return ret;
}
| 20.493213
| 128
| 0.596048
|
StebQC
|
c7bed9512bf1669bd704249a678e3caac03f48f8
| 6,308
|
hpp
|
C++
|
stan/math/prim/prob/loglogistic_lpdf.hpp
|
LaudateCorpus1/math
|
990a66b3cccd27a5fd48626360bb91093a48278b
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/prim/prob/loglogistic_lpdf.hpp
|
LaudateCorpus1/math
|
990a66b3cccd27a5fd48626360bb91093a48278b
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/prim/prob/loglogistic_lpdf.hpp
|
LaudateCorpus1/math
|
990a66b3cccd27a5fd48626360bb91093a48278b
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_PRIM_PROB_LOGLOGISTIC_LPDF_HPP
#define STAN_MATH_PRIM_PROB_LOGLOGISTIC_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The log of the loglogistic density for the specified scalar(s)
* given the specified scales(s) and shape(s). y, alpha, or beta
* can each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/scale/shape triple.
*
* @tparam T_y type of scalar.
* @tparam T_scale type of scale parameter.
* @tparam T_shape type of shape parameter.
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) scale parameter(s)
* for the loglogistic distribution.
* @param beta (Sequence of) shape parameter(s) for the
* loglogistic distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if any of the inputs are not positive and finite.
*/
template <bool propto, typename T_y, typename T_scale, typename T_shape,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_scale, T_shape>* = nullptr>
return_type_t<T_y, T_scale, T_shape> loglogistic_lpdf(const T_y& y,
const T_scale& alpha,
const T_shape& beta) {
using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
using T_scale_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
using T_shape_ref = ref_type_if_t<!is_constant<T_shape>::value, T_shape>;
using std::pow;
static const char* function = "loglogistic_lpdf";
check_consistent_sizes(function, "Random variable", y, "Scale parameter",
alpha, "Shape parameter", beta);
T_y_ref y_ref = y;
T_scale_ref alpha_ref = alpha;
T_shape_ref beta_ref = beta;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) alpha_val = to_ref(as_value_column_array_or_scalar(alpha_ref));
decltype(auto) beta_val = to_ref(as_value_column_array_or_scalar(beta_ref));
check_positive_finite(function, "Random variable", y_val);
check_positive_finite(function, "Scale parameter", alpha_val);
check_positive_finite(function, "Shape parameter", beta_val);
if (size_zero(y, alpha, beta)) {
return 0.0;
}
if (!include_summand<propto, T_y, T_scale, T_shape>::value) {
return 0.0;
}
operands_and_partials<T_y_ref, T_scale_ref, T_shape_ref> ops_partials(
y_ref, alpha_ref, beta_ref);
const auto& inv_alpha
= to_ref_if<!is_constant_all<T_y, T_scale>::value>(inv(alpha_val));
const auto& y_div_alpha
= to_ref_if<!is_constant_all<T_shape>::value>(y_val * inv_alpha);
const auto& y_div_alpha_pow_beta
= to_ref_if<!is_constant_all<T_shape>::value>(pow(y_div_alpha, beta_val));
const auto& log1_arg
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
1 + y_div_alpha_pow_beta);
const auto& log_y = to_ref_if<!is_constant_all<T_shape>::value>(log(y_val));
const auto& log_alpha
= to_ref_if<include_summand<propto, T_scale, T_shape>::value>(
log(alpha_val));
const auto& beta_minus_one
= to_ref_if<(include_summand<propto, T_scale, T_shape>::value
|| !is_constant_all<T_y>::value)>(beta_val - 1.0);
size_t N = max_size(y, alpha, beta);
size_t N_alpha_beta = max_size(alpha, beta);
T_partials_return logp = sum(beta_minus_one * log_y - 2.0 * log(log1_arg));
if (include_summand<propto, T_scale, T_shape>::value) {
logp += sum(N * (log(beta_val) - log_alpha - beta_minus_one * log_alpha)
/ N_alpha_beta);
}
if (!is_constant_all<T_y, T_scale, T_shape>::value) {
const auto& two_inv_log1_arg
= to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(2.0 * inv(log1_arg));
if (!is_constant_all<T_y, T_scale>::value) {
const auto& y_pow_beta = to_ref_if<!is_constant_all<T_y, T_scale>::value>(
pow(y_val, beta_val));
const auto& inv_alpha_pow_beta
= to_ref_if < !is_constant_all<T_y>::value
&& !is_constant_all<T_scale>::value > (pow(inv_alpha, beta_val));
if (!is_constant_all<T_y>::value) {
const auto& inv_y = inv(y_val);
const auto& y_deriv = beta_minus_one * inv_y
- two_inv_log1_arg
* (beta_val * inv_alpha_pow_beta)
* y_pow_beta * inv_y;
ops_partials.edge1_.partials_ = y_deriv;
}
if (!is_constant_all<T_scale>::value) {
const auto& alpha_deriv = -beta_val * inv_alpha
- two_inv_log1_arg * y_pow_beta * (-beta_val)
* inv_alpha_pow_beta * inv_alpha;
ops_partials.edge2_.partials_ = alpha_deriv;
}
}
if (!is_constant_all<T_shape>::value) {
const auto& beta_deriv
= (1.0 * inv(beta_val)) + log_y - log_alpha
- two_inv_log1_arg * y_div_alpha_pow_beta * log(y_div_alpha);
ops_partials.edge3_.partials_ = beta_deriv;
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_scale, typename T_shape>
inline return_type_t<T_y, T_scale, T_shape> loglogistic_lpdf(
const T_y& y, const T_scale& alpha, const T_shape& beta) {
return loglogistic_lpdf<false>(y, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
| 41.228758
| 80
| 0.672796
|
LaudateCorpus1
|
c7bff271f455b6173e8f2501c86a7221315fe810
| 13,224
|
cpp
|
C++
|
src/hed/libs/message/SOAPEnvelope.cpp
|
davidgcameron/arc
|
9813ef5f45e5089507953239de8fa2248f5ad32c
|
[
"Apache-2.0"
] | null | null | null |
src/hed/libs/message/SOAPEnvelope.cpp
|
davidgcameron/arc
|
9813ef5f45e5089507953239de8fa2248f5ad32c
|
[
"Apache-2.0"
] | null | null | null |
src/hed/libs/message/SOAPEnvelope.cpp
|
davidgcameron/arc
|
9813ef5f45e5089507953239de8fa2248f5ad32c
|
[
"Apache-2.0"
] | null | null | null |
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstring>
#include "SOAPEnvelope.h"
#define SOAP12_ENV_NAMESPACE "http://www.w3.org/2003/05/soap-envelope"
#define SOAP12_ENC_NAMESPACE "http://www.w3.org/2003/05/soap-encoding"
#define SOAP11_ENV_NAMESPACE "http://schemas.xmlsoap.org/soap/envelope/"
#define SOAP11_ENC_NAMESPACE "http://schemas.xmlsoap.org/soap/encoding/"
namespace Arc {
namespace internal {
class SOAPNS: public NS {
public:
SOAPNS(bool ver12) {
if(ver12) {
(*this)["soap-enc"]=SOAP12_ENC_NAMESPACE;
(*this)["soap-env"]=SOAP12_ENV_NAMESPACE;
} else {
(*this)["soap-enc"]=SOAP11_ENC_NAMESPACE;
(*this)["soap-env"]=SOAP11_ENV_NAMESPACE;
};
}
};
}
SOAPEnvelope::SOAPEnvelope(const std::string& s):XMLNode(s) {
set();
decode();
}
SOAPEnvelope::SOAPEnvelope(const char* s,int l):XMLNode(s,l) {
set();
decode();
}
SOAPEnvelope::SOAPEnvelope(const SOAPEnvelope& soap):XMLNode(),fault(NULL) {
soap.envelope.New(*this);
set();
}
SOAPEnvelope::SOAPEnvelope(const NS& ns,bool f):XMLNode(ns,"Envelope"),fault(NULL) {
XMLNode& it = *this;
if(!it) return;
ver12=false;
for(NS::const_iterator i = ns.begin();i!=ns.end();++i) {
if(i->second == SOAP12_ENV_NAMESPACE) {
ver12=true; break;
};
};
internal::SOAPNS ns_(ver12);
ns_["xsi"]="http://www.w3.org/2001/XMLSchema-instance";
ns_["xsd"]="http://www.w3.org/2001/XMLSchema";
XMLNode::Namespaces(ns_);
XMLNode::Name("soap-env:Envelope"); // Fixing namespace
header=XMLNode::NewChild("soap-env:Header");
body=XMLNode::NewChild("soap-env:Body");
envelope=it; ((SOAPEnvelope*)(&envelope))->is_owner_=true;
XMLNode::is_owner_=false; XMLNode::node_=((SOAPEnvelope*)(&body))->node_;
if(f) {
XMLNode fault_n = body.NewChild("soap-env:Fault");
if(ver12) {
XMLNode code_n = fault_n.NewChild("soap-env:Code");
XMLNode reason_n = fault_n.NewChild("soap-env:Reason");
reason_n.NewChild("soap-env:Text")="unknown";
code_n.NewChild("soap-env:Value")="soap-env:Receiver";
} else {
XMLNode code_n = fault_n.NewChild("soap-env:faultcode");
XMLNode reason_n = fault_n.NewChild("soap-env:faultstring");
reason_n.NewChild("soap-env:Text")="unknown";
code_n.NewChild("soap-env:Value")="soap-env:Server";
};
fault=new SOAPFault(body);
};
}
SOAPEnvelope::SOAPEnvelope(XMLNode root):XMLNode(root),fault(NULL) {
if(!node_) return;
if(node_->type != XML_ELEMENT_NODE) { node_=NULL; return; };
set();
// decode(); ??
}
SOAPEnvelope::~SOAPEnvelope(void) {
if(fault) delete fault;
}
// This function is only called from constructor
void SOAPEnvelope::set(void) {
fault=NULL;
XMLNode& it = *this;
if(!it) return;
ver12=false;
if(!it.NamespacePrefix(SOAP12_ENV_NAMESPACE).empty()) ver12=true;
internal::SOAPNS ns(ver12);
ns["xsi"]="http://www.w3.org/2001/XMLSchema-instance";
ns["xsd"]="http://www.w3.org/2001/XMLSchema";
// Do not apply deeper than Envelope + Header/Body + Fault
it.Namespaces(ns,true,2);
envelope = it;
if((!envelope) || (!MatchXMLName(envelope,"soap-env:Envelope"))) {
// No SOAP Envelope found
if(is_owner_) xmlFreeDoc(node_->doc); node_=NULL;
return;
};
if(MatchXMLName(envelope.Child(0),"soap-env:Header")) {
// SOAP has Header
header=envelope.Child(0);
body=envelope.Child(1);
} else {
// SOAP has no header - create an empty one
body=envelope.Child(0);
header=envelope.NewChild("soap-env:Header",0,true);
};
if(!MatchXMLName(body,"soap-env:Body")) {
// No SOAP Body found
if(is_owner_) xmlFreeDoc(node_->doc); node_=NULL;
return;
};
// Transfer ownership.
((SOAPEnvelope*)(&envelope))->is_owner_=is_owner_; // true
// Make this object represent SOAP Body
is_owner_=false;
this->node_=((SOAPEnvelope*)(&body))->node_;
// Check if this message is fault
fault = new SOAPFault(body);
if(!(*fault)) {
delete fault; fault=NULL;
} else {
// Apply namespaces to Fault element
body.Namespaces(ns);
}
}
XMLNode SOAPEnvelope::findid(XMLNode parent, const std::string& id) {
XMLNode node;
if(!parent) return node;
for(int n = 0; (bool)(node = parent.Child(n)); ++n) {
if(node.Attribute("id") == id) return node;
}
if(parent == body) return node;
return findid(parent.Parent(),id);
}
void SOAPEnvelope::decode(XMLNode node) {
if(!node) return;
// A lot of TODOs
if((node.Size() == 0) && ((std::string)node).empty()) {
XMLNode href = node.Attribute("href");
if((bool)href) {
std::string id = href;
if(id[0] == '#') {
id = id.substr(1);
if(!id.empty()) {
// Looking for corresponding id
XMLNode id_node = findid(node.Parent(),id);
if((bool)id_node) {
href.Destroy();
// Replacing content
node = (std::string)id_node;
XMLNode cnode;
for(int n = 0; (bool)(cnode = id_node.Child(n)); ++n) {
node.NewChild(cnode);
}
}
}
}
}
}
// Repeat for all children nodes
XMLNode cnode;
for(int n = 0; (bool)(cnode = node.Child(n)); ++n) {
decode(cnode);
}
}
void SOAPEnvelope::decode(void) {
// Do links in first elelment
decode(body.Child(0));
// Remove rest
XMLNode cnode;
while((bool)(cnode = body.Child(1))) {
cnode.Destroy();
}
}
SOAPEnvelope* SOAPEnvelope::New(void) {
XMLNode new_envelope;
envelope.New(new_envelope);
SOAPEnvelope* new_soap = new SOAPEnvelope(new_envelope);
if(new_soap) {
((SOAPEnvelope*)(&(new_soap->envelope)))->is_owner_=true;
((SOAPEnvelope*)(&new_envelope))->is_owner_=false;
};
return new_soap;
}
void SOAPEnvelope::Swap(SOAPEnvelope& soap) {
bool ver12_tmp = ver12;
ver12=soap.ver12; soap.ver12=ver12_tmp;
SOAPFault* fault_tmp = fault;
fault=soap.fault; soap.fault=fault_tmp;
envelope.Swap(soap.envelope);
header.Swap(soap.header);
body.Swap(soap.body);
XMLNode::Swap(soap);
}
void SOAPEnvelope::Swap(Arc::XMLNode& soap) {
XMLNode& it = *this;
envelope.Swap(soap);
it.Swap(envelope);
envelope=XMLNode();
body=XMLNode();
header=XMLNode();
ver12=false;
fault=NULL;
set();
}
void SOAPEnvelope::Namespaces(const NS& namespaces) {
envelope.Namespaces(namespaces);
}
NS SOAPEnvelope::Namespaces(void) {
return (envelope.Namespaces());
}
void SOAPEnvelope::GetXML(std::string& out_xml_str,bool user_friendly) const {
if(header.Size() == 0) {
SOAPEnvelope& it = *(SOAPEnvelope*)this;
// Moving header outside tree and then back.
// This fully recovers initial tree and allows this methof to be const
XMLNode tmp_header;
it.header.Move(tmp_header);
envelope.GetXML(out_xml_str,user_friendly);
it.header=it.envelope.NewChild("soap-env:Header",0,true); // It can be any dummy
it.header.Exchange(tmp_header);
return;
};
envelope.GetXML(out_xml_str,user_friendly);
}
// Wrap existing fault
SOAPFault::SOAPFault(XMLNode body) {
ver12 = (body.Namespace() == SOAP12_ENV_NAMESPACE);
if(body.Size() != 1) return;
fault=body.Child(0);
if(!MatchXMLName(fault,body.Prefix()+":Fault")) { fault=XMLNode(); return; };
if(!ver12) {
code=fault["faultcode"];
if(code) {
reason=fault["faultstring"];
node=fault["faultactor"];
role=XMLNode();
detail=fault["detail"];
return;
};
} else {
code=fault["Code"];
if(code) {
reason=fault["Reason"];
node=fault["Node"];
role=fault["Role"];
detail=fault["Detail"];
return;
};
};
fault=XMLNode();
return;
}
// Create new fault in existing body
SOAPFault::SOAPFault(XMLNode body,SOAPFaultCode c,const char* r) {
ver12 = (body.Namespace() == SOAP12_ENV_NAMESPACE);
fault=body.NewChild("Fault");
if(!fault) return;
internal::SOAPNS ns(ver12);
fault.Namespaces(ns);
fault.Name("soap-env:Fault");
Code(c);
Reason(0,r);
}
// Create new fault in existing body
SOAPFault::SOAPFault(XMLNode body,SOAPFaultCode c,const char* r,bool v12) {
ver12=v12;
fault=body.NewChild("soap-env:Fault");
if(!fault) return;
Code(c);
Reason(0,r);
}
std::string SOAPFault::Reason(int num) {
if(ver12) return reason.Child(num);
if(num != 0) return "";
return reason;
}
void SOAPFault::Reason(int num,const char* r) {
if(!r) r = "";
if(ver12) {
if(!reason) reason=fault.NewChild(fault.Prefix()+":Reason");
XMLNode rn = reason.Child(num);
if(!rn) rn=reason.NewChild(fault.Prefix()+":Text");
rn=r;
return;
};
if(!reason) reason=fault.NewChild(fault.Prefix()+":faultstring");
if(*r) {
reason=r;
} else {
// RFC says it SHOULD provide some description.
// And some implementations take it too literally.
reason="unknown";
};
return;
}
std::string SOAPFault::Node(void) {
return node;
}
void SOAPFault::Node(const char* n) {
if(!n) n = "";
if(!node) {
if(ver12) {
node=fault.NewChild(fault.Prefix()+":Node");
} else {
node=fault.NewChild(fault.Prefix()+":faultactor");
};
};
node=n;
}
std::string SOAPFault::Role(void) {
return role;
}
void SOAPFault::Role(const char* r) {
if(!r) r = "";
if(ver12) {
if(!role) role=fault.NewChild(fault.Prefix()+":Role");
role=r;
};
}
static const char* FaultCodeMatch(const char* base,const char* code) {
if(!base) base = "";
if(!code) code = "";
int l = strlen(base);
if(strncasecmp(base,code,l) != 0) return NULL;
if(code[l] == 0) return code+l;
if(code[l] == '.') return code+l+1;
return NULL;
}
SOAPFault::SOAPFaultCode SOAPFault::Code(void) {
if(!code) return undefined;
if(ver12) {
std::string c = code["Value"];
std::string::size_type p = c.find(":");
if(p != std::string::npos) c.erase(0,p+1);
if(strcasecmp("VersionMismatch",c.c_str()) == 0)
return VersionMismatch;
if(strcasecmp("MustUnderstand",c.c_str()) == 0)
return MustUnderstand;
if(strcasecmp("DataEncodingUnknown",c.c_str()) == 0)
return DataEncodingUnknown;
if(strcasecmp("Sender",c.c_str()) == 0)
return Sender;
if(strcasecmp("Receiver",c.c_str()) == 0)
return Receiver;
return unknown;
} else {
std::string c = code;
std::string::size_type p = c.find(":");
if(p != std::string::npos) c.erase(0,p+1);
if(FaultCodeMatch("VersionMismatch",c.c_str()))
return VersionMismatch;
if(FaultCodeMatch("MustUnderstand",c.c_str()))
return MustUnderstand;
if(FaultCodeMatch("Client",c.c_str()))
return Sender;
if(FaultCodeMatch("Server",c.c_str()))
return Receiver;
};
return unknown;
}
void SOAPFault::Code(SOAPFaultCode c) {
if(ver12) {
if(!code) code=fault.NewChild(fault.Prefix()+":Code");
XMLNode value = code["Value"];
if(!value) value=code.NewChild(code.Prefix()+":Value");
switch(c) {
case VersionMismatch: value=value.Prefix()+":VersionMismatch"; break;
case MustUnderstand: value=value.Prefix()+":MustUnderstand"; break;
case DataEncodingUnknown: value=value.Prefix()+":DataEncodingUnknown"; break;
case Sender: value=value.Prefix()+":Sender"; break;
case Receiver: value=value.Prefix()+":Receiver"; break;
default: value=""; break;
};
} else {
if(!code) code=fault.NewChild(fault.Prefix()+":faultcode");
switch(c) {
case VersionMismatch: code=code.Prefix()+":VersionMismatch"; break;
case MustUnderstand: code=code.Prefix()+":MustUnderstand"; break;
case Sender: code=code.Prefix()+":Client"; break;
case Receiver: code=code.Prefix()+":Server"; break;
default: code=""; break;
};
};
}
std::string SOAPFault::Subcode(int level) {
if(!ver12) return "";
if(level < 0) return "";
if(!code) return "";
XMLNode subcode = code;
for(;level;--level) {
subcode=subcode["Subcode"];
if(!subcode) return "";
};
return subcode["Value"];
}
void SOAPFault::Subcode(int level,const char* s) {
if(!ver12) return;
if(level < 0) return;
if(!s) s = "";
if(!code) code=fault.NewChild(fault.Prefix()+":Code");
XMLNode subcode = code;
for(;level;--level) {
XMLNode subcode_ = subcode["Subcode"];
if(!subcode_) subcode_=subcode.NewChild(subcode.Prefix()+":Subcode");
subcode=subcode_;
};
if(!subcode["Value"]) {
subcode.NewChild(subcode.Prefix()+":Value")=s;
} else {
subcode["Value"]=s;
};
}
XMLNode SOAPFault::Detail(bool create) {
if(detail) return detail;
if(!create) return XMLNode();
if(!ver12) {
detail=fault.NewChild(fault.Prefix()+":detail");
} else {
detail=fault.NewChild(fault.Prefix()+":Detail");
};
return detail;
}
SOAPEnvelope& SOAPEnvelope::operator=(const SOAPEnvelope& soap) {
if(fault) delete fault;
fault=NULL;
envelope=XMLNode();
header=XMLNode();
body=XMLNode();
soap.envelope.New(*this);
set();
return *this;
}
SOAPEnvelope* SOAPFault::MakeSOAPFault(SOAPFaultCode code,const std::string& reason) {
SOAPEnvelope* out = new SOAPEnvelope(NS(),true);
if(!out) return NULL;
SOAPFault* fault = out->Fault();
if(!fault) { delete out; return NULL; };
fault->Code(code);
fault->Reason(reason);
return out;
}
} // namespace Arc
| 27.209877
| 86
| 0.63967
|
davidgcameron
|
c7c2e8ab4dc883ec62c6e6ad15603570e9b171b8
| 488
|
cpp
|
C++
|
B-CPP-300-LYN-3-1-CPPD14M/ex00/Fruit.cpp
|
Neotoxic-off/Epitech2024
|
8b3dd04fa9ac2b7019c0b5b1651975a7252d929b
|
[
"Apache-2.0"
] | 2
|
2022-02-07T12:44:51.000Z
|
2022-02-08T12:04:08.000Z
|
B-CPP-300-LYN-3-1-CPPD14M/ex00/Fruit.cpp
|
Neotoxic-off/Epitech2024
|
8b3dd04fa9ac2b7019c0b5b1651975a7252d929b
|
[
"Apache-2.0"
] | null | null | null |
B-CPP-300-LYN-3-1-CPPD14M/ex00/Fruit.cpp
|
Neotoxic-off/Epitech2024
|
8b3dd04fa9ac2b7019c0b5b1651975a7252d929b
|
[
"Apache-2.0"
] | 1
|
2022-01-23T21:26:06.000Z
|
2022-01-23T21:26:06.000Z
|
/*
** EPITECH PROJECT, 2020
** B-CPP-300-LYN-3-1-CPPD14M-
** File description:
** Fruit.cpp
*/
#include "Fruit.hpp"
Fruit::Fruit()
{
this->name = "fruit";
this->_vitamins = 0;
return;
}
Fruit::Fruit(std::string const &_name_, int _vitamins_)
{
this->name = _name_;
this->_vitamins = _vitamins_;
return;
}
Fruit::~Fruit()
{
return;
}
std::string const &Fruit::getName()
{
return(this->name);
}
int Fruit::getVitamins()
{
return(this->_vitamins);
}
| 13.189189
| 55
| 0.610656
|
Neotoxic-off
|
c7c44bed3f2564f4702ed6c4515175a6825623c5
| 7,900
|
cpp
|
C++
|
src/stan/language/ast_def.cpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
src/stan/language/ast_def.cpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
src/stan/language/ast_def.cpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_LANG_AST_DEF_CPP
#define STAN_LANG_AST_DEF_CPP
#include "stan/language/ast.hpp"
#include "stan/language/ast/fun/bare_type_is_data_vis_def.hpp"
#include "stan/language/ast/fun/bare_type_order_id_vis_def.hpp"
#include "stan/language/ast/fun/bare_type_set_is_data_vis_def.hpp"
#include "stan/language/ast/fun/bare_type_total_dims_vis_def.hpp"
#include "stan/language/ast/fun/bare_type_vis_def.hpp"
#include "stan/language/ast/fun/block_type_bounds_vis_def.hpp"
#include "stan/language/ast/fun/block_type_is_specialized_vis_def.hpp"
#include "stan/language/ast/fun/block_type_offset_multiplier_vis_def.hpp"
#include "stan/language/ast/fun/block_type_params_total_vis_def.hpp"
#include "stan/language/ast/fun/ends_with_def.hpp"
#include "stan/language/ast/fun/expression_bare_type_vis_def.hpp"
#include "stan/language/ast/fun/fun_name_exists_def.hpp"
#include "stan/language/ast/fun/get_ccdf_def.hpp"
#include "stan/language/ast/fun/get_cdf_def.hpp"
#include "stan/language/ast/fun/get_prob_fun_def.hpp"
#include "stan/language/ast/fun/has_ccdf_suffix_def.hpp"
#include "stan/language/ast/fun/has_cdf_suffix_def.hpp"
#include "stan/language/ast/fun/has_lp_suffix_def.hpp"
#include "stan/language/ast/fun/has_non_param_var_def.hpp"
#include "stan/language/ast/fun/has_non_param_var_vis_def.hpp"
#include "stan/language/ast/fun/has_prob_fun_suffix_def.hpp"
#include "stan/language/ast/fun/has_rng_suffix_def.hpp"
#include "stan/language/ast/fun/has_var_def.hpp"
#include "stan/language/ast/fun/has_var_vis_def.hpp"
#include "stan/language/ast/fun/indexed_type_def.hpp"
#include "stan/language/ast/fun/infer_type_indexing_def.hpp"
#include "stan/language/ast/fun/is_assignable_def.hpp"
#include "stan/language/ast/fun/is_multi_index_def.hpp"
#include "stan/language/ast/fun/is_multi_index_vis_def.hpp"
#include "stan/language/ast/fun/is_nil_def.hpp"
#include "stan/language/ast/fun/is_nil_vis_def.hpp"
#include "stan/language/ast/fun/is_no_op_statement_vis_def.hpp"
#include "stan/language/ast/fun/is_nonempty_def.hpp"
#include "stan/language/ast/fun/is_space_def.hpp"
#include "stan/language/ast/fun/is_user_defined_def.hpp"
#include "stan/language/ast/fun/is_user_defined_prob_function_def.hpp"
#include "stan/language/ast/fun/num_index_op_dims_def.hpp"
#include "stan/language/ast/fun/print_scope_def.hpp"
#include "stan/language/ast/fun/promote_primitive_def.hpp"
#include "stan/language/ast/fun/returns_type_def.hpp"
#include "stan/language/ast/fun/returns_type_vis_def.hpp"
#include "stan/language/ast/fun/strip_ccdf_suffix_def.hpp"
#include "stan/language/ast/fun/strip_cdf_suffix_def.hpp"
#include "stan/language/ast/fun/strip_prob_fun_suffix_def.hpp"
#include "stan/language/ast/fun/var_occurs_vis_def.hpp"
#include "stan/language/ast/fun/var_type_arg1_vis_def.hpp"
#include "stan/language/ast/fun/var_type_arg2_vis_def.hpp"
#include "stan/language/ast/fun/var_type_name_vis_def.hpp"
#include "stan/language/ast/fun/write_bare_expr_type_def.hpp"
#include "stan/language/ast/fun/write_block_var_type_def.hpp"
#include "stan/language/ast/fun/write_expression_vis_def.hpp"
#include "stan/language/ast/fun/write_idx_vis_def.hpp"
#include "stan/language/ast/node/algebra_solver_control_def.hpp"
#include "stan/language/ast/node/algebra_solver_def.hpp"
#include "stan/language/ast/node/array_expr_def.hpp"
#include "stan/language/ast/node/assgn_def.hpp"
#include "stan/language/ast/node/binary_op_def.hpp"
#include "stan/language/ast/node/block_var_decl_def.hpp"
#include "stan/language/ast/node/break_continue_statement_def.hpp"
#include "stan/language/ast/node/conditional_op_def.hpp"
#include "stan/language/ast/node/conditional_statement_def.hpp"
#include "stan/language/ast/node/double_literal_def.hpp"
#include "stan/language/ast/node/expression_def.hpp"
#include "stan/language/ast/node/for_array_statement_def.hpp"
#include "stan/language/ast/node/for_matrix_statement_def.hpp"
#include "stan/language/ast/node/for_statement_def.hpp"
#include "stan/language/ast/node/fun_def.hpp"
#include "stan/language/ast/node/function_decl_def_def.hpp"
#include "stan/language/ast/node/function_decl_defs_def.hpp"
#include "stan/language/ast/node/idx_def.hpp"
#include "stan/language/ast/node/increment_log_prob_statement_def.hpp"
#include "stan/language/ast/node/index_op_def.hpp"
#include "stan/language/ast/node/index_op_sliced_def.hpp"
#include "stan/language/ast/node/int_literal_def.hpp"
#include "stan/language/ast/node/integrate_1d_def.hpp"
#include "stan/language/ast/node/integrate_ode_control_def.hpp"
#include "stan/language/ast/node/integrate_ode_def.hpp"
#include "stan/language/ast/node/lb_idx_def.hpp"
#include "stan/language/ast/node/local_var_decl_def.hpp"
#include "stan/language/ast/node/lub_idx_def.hpp"
#include "stan/language/ast/node/map_rect_def.hpp"
#include "stan/language/ast/node/matrix_expr_def.hpp"
#include "stan/language/ast/node/multi_idx_def.hpp"
#include "stan/language/ast/node/offset_multiplier_def.hpp"
#include "stan/language/ast/node/omni_idx_def.hpp"
#include "stan/language/ast/node/print_statement_def.hpp"
#include "stan/language/ast/node/printable_def.hpp"
#include "stan/language/ast/node/program_def.hpp"
#include "stan/language/ast/node/range_def.hpp"
#include "stan/language/ast/node/reject_statement_def.hpp"
#include "stan/language/ast/node/return_statement_def.hpp"
#include "stan/language/ast/node/row_vector_expr_def.hpp"
#include "stan/language/ast/node/sample_def.hpp"
#include "stan/language/ast/node/statement_def.hpp"
#include "stan/language/ast/node/statements_def.hpp"
#include "stan/language/ast/node/ub_idx_def.hpp"
#include "stan/language/ast/node/unary_op_def.hpp"
#include "stan/language/ast/node/uni_idx_def.hpp"
#include "stan/language/ast/node/var_decl_def.hpp"
#include "stan/language/ast/node/variable_def.hpp"
#include "stan/language/ast/node/variable_dims_def.hpp"
#include "stan/language/ast/node/while_statement_def.hpp"
#include "stan/language/ast/scope_def.hpp"
#include "stan/language/ast/sigs/function_signatures_def.hpp"
#include "stan/language/ast/type/bare_array_type_def.hpp"
#include "stan/language/ast/type/bare_expr_type_def.hpp"
#include "stan/language/ast/type/block_array_type_def.hpp"
#include "stan/language/ast/type/block_var_type_def.hpp"
#include "stan/language/ast/type/cholesky_factor_corr_block_type_def.hpp"
#include "stan/language/ast/type/cholesky_factor_cov_block_type_def.hpp"
#include "stan/language/ast/type/corr_matrix_block_type_def.hpp"
#include "stan/language/ast/type/cov_matrix_block_type_def.hpp"
#include "stan/language/ast/type/double_block_type_def.hpp"
#include "stan/language/ast/type/double_type_def.hpp"
#include "stan/language/ast/type/ill_formed_type_def.hpp"
#include "stan/language/ast/type/int_block_type_def.hpp"
#include "stan/language/ast/type/int_type_def.hpp"
#include "stan/language/ast/type/local_array_type_def.hpp"
#include "stan/language/ast/type/local_var_type_def.hpp"
#include "stan/language/ast/type/matrix_block_type_def.hpp"
#include "stan/language/ast/type/matrix_local_type_def.hpp"
#include "stan/language/ast/type/matrix_type_def.hpp"
#include "stan/language/ast/type/ordered_block_type_def.hpp"
#include "stan/language/ast/type/positive_ordered_block_type_def.hpp"
#include "stan/language/ast/type/row_vector_block_type_def.hpp"
#include "stan/language/ast/type/row_vector_local_type_def.hpp"
#include "stan/language/ast/type/row_vector_type_def.hpp"
#include "stan/language/ast/type/simplex_block_type_def.hpp"
#include "stan/language/ast/type/unit_vector_block_type_def.hpp"
#include "stan/language/ast/type/vector_block_type_def.hpp"
#include "stan/language/ast/type/vector_local_type_def.hpp"
#include "stan/language/ast/type/vector_type_def.hpp"
#include "stan/language/ast/type/void_type_def.hpp"
#include "stan/language/ast/variable_map_def.hpp"
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/recursive_variant.hpp>
#endif
| 55.244755
| 73
| 0.826329
|
alashworth
|
c7c9ca4378f7e79de21c67be42dea9eb9a293b84
| 1,809
|
hpp
|
C++
|
MineClone/src/World/Blocks/Block.hpp
|
Harry09/MineClone
|
ee893640b7570c38b5930569e2e67a18a5afce53
|
[
"MIT"
] | null | null | null |
MineClone/src/World/Blocks/Block.hpp
|
Harry09/MineClone
|
ee893640b7570c38b5930569e2e67a18a5afce53
|
[
"MIT"
] | null | null | null |
MineClone/src/World/Blocks/Block.hpp
|
Harry09/MineClone
|
ee893640b7570c38b5930569e2e67a18a5afce53
|
[
"MIT"
] | 1
|
2020-09-02T10:36:39.000Z
|
2020-09-02T10:36:39.000Z
|
#pragma once
#include <memory>
#include <vector>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include "BlockMesh.hpp"
#include "Maths/Coords.hpp"
class ChunkSegment;
class Block
{
public:
static constexpr int BlockFaceCount = static_cast<int>(BlockFace::Size);
protected:
ChunkSegment& _chunk;
coords::LocalPos _localPos = { 0.f, 0.f, 0.f };
Blocks _blockType;
TextureId _faceTexture[BlockFaceCount] = { TextureId::None };
public:
Block(ChunkSegment& chunk, const coords::LocalPos& localPos, Blocks blockType) noexcept;
Block(const Block& other) noexcept;
Block& operator=(const Block& other) noexcept;
Block(Block&& other) noexcept;
Block& operator=(Block&& other) noexcept;
~Block() = default;
const coords::LocalPos& getLocalPos() const { return _localPos; }
coords::WorldPos getWorldPos() const;
Block* getNeighbor(BlockFace face) const;
bool hasNeighbor(BlockFace face) const { return getNeighbor(face) != nullptr; }
template<BlockFace... Faces>
const auto getVertices(TextureAtlas& textureAtlas) const
{
std::vector<Vertex> vertices;
int offset = 0;
((getVerticesImp<Faces>(vertices, offset, textureAtlas), offset++), ...);
return vertices;
}
protected:
template<BlockFace... Faces>
constexpr void setTexture(TextureId textureId)
{
((_faceTexture[static_cast<int>(Faces)] = textureId), ...);
}
private:
template<BlockFace Face>
const void getVerticesImp(std::vector<Vertex>& vertices, int offset, TextureAtlas& textureAtlas) const
{
if (!hasNeighbor(Face))
{
unsigned faceValue = static_cast<unsigned>(Face);
std::array<Vertex, 6> mesh = getSingleBlockMesh<Face>(_localPos, _faceTexture[faceValue], textureAtlas);
vertices.reserve(vertices.size() + 6);
vertices.insert(vertices.end(), mesh.begin(), mesh.end());
}
}
};
| 22.333333
| 107
| 0.722499
|
Harry09
|
c7cfc4d8a7c98de1980110212c8fd4f4f656f25a
| 4,927
|
cpp
|
C++
|
osrm-backend/src/engine/engine.cpp
|
shiyuan/osrm
|
ce730ce5e471870b86b460c09051cd301476ef07
|
[
"MIT"
] | 1
|
2017-04-15T22:58:23.000Z
|
2017-04-15T22:58:23.000Z
|
src/engine/engine.cpp
|
zummach/osrm
|
7ab1b0893729064aa35b29d78cec605eb9831433
|
[
"BSD-2-Clause"
] | 1
|
2019-11-21T09:59:27.000Z
|
2019-11-21T09:59:27.000Z
|
osrm-ch/src/engine/engine.cpp
|
dingchunda/osrm-backend
|
8750749b83bd9193ca3481c630eefda689ecb73c
|
[
"BSD-2-Clause"
] | null | null | null |
#include "engine/api/route_parameters.hpp"
#include "engine/engine.hpp"
#include "engine/engine_config.hpp"
#include "engine/status.hpp"
#include "engine/plugins/match.hpp"
#include "engine/plugins/nearest.hpp"
#include "engine/plugins/table.hpp"
#include "engine/plugins/tile.hpp"
#include "engine/plugins/trip.hpp"
#include "engine/plugins/viaroute.hpp"
#include "engine/datafacade/datafacade_base.hpp"
#include "engine/datafacade/internal_datafacade.hpp"
#include "engine/datafacade/shared_datafacade.hpp"
#include "storage/shared_barriers.hpp"
#include "util/make_unique.hpp"
#include "util/simple_logger.hpp"
#include <boost/assert.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/thread/lock_types.hpp>
#include <algorithm>
#include <fstream>
#include <utility>
#include <vector>
namespace
{
// Abstracted away the query locking into a template function
// Works the same for every plugin.
template <typename ParameterT, typename PluginT, typename ResultT>
osrm::engine::Status
RunQuery(const std::unique_ptr<osrm::storage::SharedBarriers> &lock,
osrm::engine::datafacade::BaseDataFacade &facade,
const ParameterT ¶meters,
PluginT &plugin,
ResultT &result)
{
if (!lock)
{
return plugin.HandleRequest(parameters, result);
}
BOOST_ASSERT(lock);
// this locks aquires shared ownership of the query mutex: other requets are allowed
// to run, but data updates need to wait for all queries to finish until they can aquire an exclusive lock
boost::interprocess::sharable_lock<boost::interprocess::named_sharable_mutex> query_lock(
lock->query_mutex);
auto &shared_facade = static_cast<osrm::engine::datafacade::SharedDataFacade &>(facade);
shared_facade.CheckAndReloadFacade();
// Get a shared data lock so that other threads won't update
// things while the query is running
boost::shared_lock<boost::shared_mutex> data_lock{shared_facade.data_mutex};
osrm::engine::Status status = plugin.HandleRequest(parameters, result);
return status;
}
template <typename Plugin, typename Facade, typename... Args>
std::unique_ptr<Plugin> create(Facade &facade, Args... args)
{
return osrm::util::make_unique<Plugin>(facade, std::forward<Args>(args)...);
}
} // anon. ns
namespace osrm
{
namespace engine
{
Engine::Engine(const EngineConfig &config)
: lock(config.use_shared_memory ? std::make_unique<storage::SharedBarriers>()
: std::unique_ptr<storage::SharedBarriers>())
{
if (config.use_shared_memory)
{
query_data_facade = util::make_unique<datafacade::SharedDataFacade>();
}
else
{
if (!config.storage_config.IsValid())
{
throw util::exception("Invalid file paths given!");
}
query_data_facade =
util::make_unique<datafacade::InternalDataFacade>(config.storage_config);
}
// Register plugins
using namespace plugins;
route_plugin = create<ViaRoutePlugin>(*query_data_facade, config.max_locations_viaroute);
table_plugin = create<TablePlugin>(*query_data_facade, config.max_locations_distance_table);
nearest_plugin = create<NearestPlugin>(*query_data_facade, config.max_results_nearest);
trip_plugin = create<TripPlugin>(*query_data_facade, config.max_locations_trip);
match_plugin = create<MatchPlugin>(*query_data_facade, config.max_locations_map_matching);
tile_plugin = create<TilePlugin>(*query_data_facade);
}
// make sure we deallocate the unique ptr at a position where we know the size of the plugins
Engine::~Engine() = default;
Engine::Engine(Engine &&) noexcept = default;
Engine &Engine::operator=(Engine &&) noexcept = default;
Status Engine::Route(const api::RouteParameters ¶ms, util::json::Object &result) const
{
return RunQuery(lock, *query_data_facade, params, *route_plugin, result);
}
Status Engine::Table(const api::TableParameters ¶ms, util::json::Object &result) const
{
return RunQuery(lock, *query_data_facade, params, *table_plugin, result);
}
Status Engine::Nearest(const api::NearestParameters ¶ms, util::json::Object &result) const
{
return RunQuery(lock, *query_data_facade, params, *nearest_plugin, result);
}
Status Engine::Trip(const api::TripParameters ¶ms, util::json::Object &result) const
{
return RunQuery(lock, *query_data_facade, params, *trip_plugin, result);
}
Status Engine::Match(const api::MatchParameters ¶ms, util::json::Object &result) const
{
return RunQuery(lock, *query_data_facade, params, *match_plugin, result);
}
Status Engine::Tile(const api::TileParameters ¶ms, std::string &result) const
{
return RunQuery(lock, *query_data_facade, params, *tile_plugin, result);
}
} // engine ns
} // osrm ns
| 33.97931
| 110
| 0.733509
|
shiyuan
|
c7d021bca8c0f014831ab539c537d48241ef27ec
| 855
|
cpp
|
C++
|
Old Files/SingleRoad_Square/alpha_sq.cpp
|
karenl7/stlhj
|
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
|
[
"MIT"
] | 6
|
2019-01-30T00:11:55.000Z
|
2022-03-09T02:44:51.000Z
|
Old Files/SingleRoad_Square/alpha_sq.cpp
|
StanfordASL/stlhj
|
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
|
[
"MIT"
] | null | null | null |
Old Files/SingleRoad_Square/alpha_sq.cpp
|
StanfordASL/stlhj
|
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
|
[
"MIT"
] | 4
|
2018-09-08T00:16:55.000Z
|
2022-03-09T02:44:54.000Z
|
void alpha_sq(
beacls::FloatVec& alpha,
beacls::FloatVec xs,
FLOAT_TYPE dim,
const size_t numel,
FLOAT_TYPE alpha_offset,
FLOAT_TYPE length){
if (dim == 0){
std::transform(xs.cbegin(), xs.cend(), alpha.begin(),
[alpha_offset, length](const auto &xs_i) {
return 1- std::pow(((xs_i - alpha_offset)/length),2); });
}
else if (dim == 1) {
beacls::FloatVec alpha_temp;
alpha_temp.assign(numel, 0.);
std::transform(xs.cbegin(), xs.cend(), alpha_temp.begin(),
[alpha_offset, length](const auto &xs_i) {
return 1- std::pow(((xs_i - alpha_offset)/length),2); });
std::transform(alpha_temp.cbegin(), alpha_temp.cend(), alpha.begin(), alpha.begin(),
[](const auto &alpha_temp_i, const auto &alpha_i) {
return std::min(alpha_temp_i,alpha_i); });
}
}
| 31.666667
| 88
| 0.604678
|
karenl7
|
c7d121c06ecf1e5bc536f40fd44537bdeba871f7
| 6,930
|
cpp
|
C++
|
source/camera.cpp
|
khoih-prog/example-standalone-inferencing-linux
|
7237ef0b5cd4cdfca2c61912a8ccc5c29e42570c
|
[
"Apache-2.0"
] | 7
|
2021-06-14T21:28:47.000Z
|
2022-01-18T17:51:54.000Z
|
source/camera.cpp
|
khoih-prog/example-standalone-inferencing-linux
|
7237ef0b5cd4cdfca2c61912a8ccc5c29e42570c
|
[
"Apache-2.0"
] | null | null | null |
source/camera.cpp
|
khoih-prog/example-standalone-inferencing-linux
|
7237ef0b5cd4cdfca2c61912a8ccc5c29e42570c
|
[
"Apache-2.0"
] | 5
|
2021-05-03T12:45:32.000Z
|
2022-02-08T19:28:18.000Z
|
/* Edge Impulse Linux SDK
* Copyright (c) 2021 EdgeImpulse Inc.
*
* 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 <unistd.h>
#include "opencv2/opencv.hpp"
#include "opencv2/videoio/videoio_c.h"
#include "edge-impulse-sdk/classifier/ei_run_classifier.h"
#include "iostream"
static bool use_debug = false;
// If you don't want to allocate this much memory you can use a signal_t structure as well
// and read directly from a cv::Mat object, but on Linux this should be OK
static float features[EI_CLASSIFIER_INPUT_WIDTH * EI_CLASSIFIER_INPUT_HEIGHT];
/**
* Resize and crop to the set width/height from model_metadata.h
*/
void resize_and_crop(cv::Mat *in_frame, cv::Mat *out_frame) {
// to resize... we first need to know the factor
float factor_w = static_cast<float>(EI_CLASSIFIER_INPUT_WIDTH) / static_cast<float>(in_frame->cols);
float factor_h = static_cast<float>(EI_CLASSIFIER_INPUT_HEIGHT) / static_cast<float>(in_frame->rows);
float largest_factor = factor_w > factor_h ? factor_w : factor_h;
cv::Size resize_size(static_cast<int>(largest_factor * static_cast<float>(in_frame->cols)),
static_cast<int>(largest_factor * static_cast<float>(in_frame->rows)));
cv::Mat resized;
cv::resize(*in_frame, resized, resize_size);
int crop_x = resize_size.width > resize_size.height ?
(resize_size.width - resize_size.height) / 2 :
0;
int crop_y = resize_size.height > resize_size.width ?
(resize_size.height - resize_size.width) / 2 :
0;
cv::Rect crop_region(crop_x, crop_y, EI_CLASSIFIER_INPUT_WIDTH, EI_CLASSIFIER_INPUT_HEIGHT);
if (use_debug) {
printf("crop_region x=%d y=%d width=%d height=%d\n", crop_x, crop_y, EI_CLASSIFIER_INPUT_WIDTH, EI_CLASSIFIER_INPUT_HEIGHT);
}
*out_frame = resized(crop_region);
}
int main(int argc, char** argv) {
// If you see: OpenCV: not authorized to capture video (status 0), requesting... Abort trap: 6
// This might be a permissions issue. Are you running this command from a simulated shell (like in Visual Studio Code)?
// Try it from a real terminal.
if (argc < 2) {
printf("Requires one parameter (ID of the webcam).\n");
printf("You can find these via `v4l2-ctl --list-devices`.\n");
printf("E.g. for:\n");
printf(" C922 Pro Stream Webcam (usb-70090000.xusb-2.1):\n");
printf(" /dev/video0\n");
printf("The ID of the webcam is 0\n");
exit(1);
}
for (int ix = 2; ix < argc; ix++) {
if (strcmp(argv[ix], "--debug") == 0) {
printf("Enabling debug mode\n");
use_debug = true;
}
}
// open the webcam...
cv::VideoCapture camera(atoi(argv[1]));
if (!camera.isOpened()) {
std::cerr << "ERROR: Could not open camera" << std::endl;
return 1;
}
if (use_debug) {
// create a window to display the images from the webcam
cv::namedWindow("Webcam", cv::WINDOW_AUTOSIZE);
}
// this will contain the image from the webcam
cv::Mat frame;
// display the frame until you press a key
while (1) {
// 100ms. between inference
int64_t next_frame = (int64_t)(ei_read_timer_ms() + 100);
// capture the next frame from the webcam
camera >> frame;
cv::Mat cropped;
resize_and_crop(&frame, &cropped);
size_t feature_ix = 0;
for (int rx = 0; rx < (int)cropped.rows; rx++) {
for (int cx = 0; cx < (int)cropped.cols; cx++) {
cv::Vec3b pixel = cropped.at<cv::Vec3b>(rx, cx);
uint8_t b = pixel.val[0];
uint8_t g = pixel.val[1];
uint8_t r = pixel.val[2];
features[feature_ix++] = (r << 16) + (g << 8) + b;
}
}
ei_impulse_result_t result;
// construct a signal from the features buffer
signal_t signal;
numpy::signal_from_buffer(features, EI_CLASSIFIER_INPUT_WIDTH * EI_CLASSIFIER_INPUT_HEIGHT, &signal);
// and run the classifier
EI_IMPULSE_ERROR res = run_classifier(&signal, &result, false);
if (res != 0) {
printf("ERR: Failed to run classifier (%d)\n", res);
return 1;
}
#if EI_CLASSIFIER_OBJECT_DETECTION == 1
printf("Classification result (%d ms.):\n", result.timing.dsp + result.timing.classification);
bool found_bb = false;
for (size_t ix = 0; ix < EI_CLASSIFIER_OBJECT_DETECTION_COUNT; ix++) {
auto bb = result.bounding_boxes[ix];
if (bb.value == 0) {
continue;
}
found_bb = true;
printf(" %s (%f) [ x: %u, y: %u, width: %u, height: %u ]\n", bb.label, bb.value, bb.x, bb.y, bb.width, bb.height);
}
if (!found_bb) {
printf(" no objects found\n");
}
#else
printf("%d ms. ", result.timing.dsp + result.timing.classification);
for (size_t ix = 0; ix < EI_CLASSIFIER_LABEL_COUNT; ix++) {
printf("%s: %.05f", result.classification[ix].label, result.classification[ix].value);
if (ix != EI_CLASSIFIER_LABEL_COUNT - 1) {
printf(", ");
}
}
printf("\n");
#endif
// show the image on the window
if (use_debug) {
cv::imshow("Webcam", cropped);
// wait (10ms) for a key to be pressed
if (cv::waitKey(10) >= 0)
break;
}
int64_t sleep_ms = next_frame > (int64_t)ei_read_timer_ms() ? next_frame - (int64_t)ei_read_timer_ms() : 0;
if (sleep_ms > 0) {
usleep(sleep_ms * 1000);
}
}
return 0;
}
#if !defined(EI_CLASSIFIER_SENSOR) || EI_CLASSIFIER_SENSOR != EI_CLASSIFIER_SENSOR_CAMERA
#error "Invalid model for current sensor."
#endif
| 37.459459
| 132
| 0.624964
|
khoih-prog
|
c7d413983e1c4fa4031ac193ad74a471a07255e1
| 31,837
|
cpp
|
C++
|
share/prototypes/bootstrap-redux/basecode/language/core/parser/parser.cpp
|
basecode-lang/bootstrap
|
8e787e4fa66438e01897a67a026557f9fe7d5b57
|
[
"MIT"
] | 32
|
2018-05-14T23:26:54.000Z
|
2020-06-14T10:13:20.000Z
|
basecode/language/core/parser/parser.cpp
|
blockspacer/bootstrap-redux
|
2d0e0d7d2b1f6f203c3dd01f6929805042db8ec7
|
[
"MIT"
] | 79
|
2018-08-01T11:50:45.000Z
|
2020-11-17T13:40:06.000Z
|
basecode/language/core/parser/parser.cpp
|
blockspacer/bootstrap-redux
|
2d0e0d7d2b1f6f203c3dd01f6929805042db8ec7
|
[
"MIT"
] | 14
|
2021-01-08T05:05:19.000Z
|
2022-03-27T14:56:56.000Z
|
// ----------------------------------------------------------------------------
// ____ _
// | _\ | |
// | |_)| __ _ ___ ___ ___ ___ __| | ___ TM
// | _< / _` / __|/ _ \/ __/ _ \ / _` |/ _ \
// | |_)| (_| \__ \ __/ (_| (_) | (_| | __/
// |____/\__,_|___/\___|\___\___/ \__,_|\___|
//
// C O M P I L E R P R O J E C T
//
// Copyright (C) 2019 Jeff Panici
// All rights reserved.
//
// This software source file is licensed under the terms of MIT license.
// For details, please read the LICENSE file.
//
// ----------------------------------------------------------------------------
#include <utility>
#include <basecode/defer.h>
#include <basecode/adt/hashable.h>
#include <basecode/errors/errors.h>
#include "parser.h"
namespace basecode::language::core::parser {
parser_t::parser_t(
workspace::session_t& session,
utf8::source_buffer_t& buffer,
entity_list_t tokens) : _tokens(std::move(tokens)),
_session(session),
_buffer(buffer),
_scopes(session.allocator()),
_blocks(session.allocator()),
_parents(session.allocator()),
_rules(session.allocator()),
_frame_allocator(session.allocator()),
_rule_table(session.allocator()) {
}
bool parser_t::has_more() const {
return _token_index < _tokens.size()
&& _rules[_token_index]->id != lexer::token_type_t::end_of_input;
}
entity_t parser_t::token() const {
return _tokens[_token_index];
}
production_rule_t* parser_t::infix(
lexer::token_type_t token_type,
int32_t bp,
const led_callback_t& led) {
auto s = terminal(token_type, bp);
if (led) {
s->led = led;
} else {
s->led = [](context_t& ctx, entity_t lhs) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::binary_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::binary_operator_t>(
ast_node,
lhs,
ctx.parser->expression(*ctx.r, ctx.rule->lbp));
return ast_node;
};
}
return s;
}
production_rule_t* parser_t::prefix(
lexer::token_type_t token_type,
const nud_callback_t& nud) {
auto s = terminal(token_type);
if (nud) {
s->nud = nud;
} else {
s->nud = [](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::unary_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::unary_operator_t>(
ast_node,
ctx.parser->expression(*ctx.r, 80));
return ast_node;
};
}
return s;
}
production_rule_t* parser_t::postfix(
lexer::token_type_t token_type,
int32_t bp,
const led_callback_t& led) {
auto s = terminal(token_type, bp);
if (led) {
s->led = led;
} else {
s->led = [](context_t& ctx, entity_t lhs) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::unary_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::unary_operator_t>(ast_node, lhs);
return ast_node;
};
}
return s;
}
production_rule_t* parser_t::terminal(
lexer::token_type_t token_type,
int32_t bp) {
auto s = _rule_table.find(token_type);
if (s) {
if (bp >= s->lbp)
s->lbp = bp;
} else {
auto p = _frame_allocator.allocate(
sizeof(production_rule_t),
alignof(production_rule_t));
s = new (p) production_rule_t {
.id = token_type,
.lbp = bp,
.nud = [](context_t& ctx) {
const auto& loc = ctx.registry->get<source_location_t>(ctx.token);
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::undefined_production_rule,
loc);
return null_entity;
},
.led = [](context_t& ctx, entity_t lhs) {
const auto& loc = ctx.registry->get<source_location_t>(ctx.token);
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::missing_operator_production_rule,
loc);
return null_entity;
},
};
_rule_table.insert(token_type, s);
}
return s;
}
production_rule_t* parser_t::literal(
lexer::token_type_t token_type,
ast::node_type_t node_type) {
auto literal = prefix(
token_type,
[](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ctx.rule->detail.node_type,
ctx.token,
ctx.parent);
return ast_node;
});
literal->detail.node_type = node_type;
return literal;
}
production_rule_t* parser_t::constant(
lexer::token_type_t token_type,
ast::node_type_t node_type) {
auto constant = prefix(
token_type,
[](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ctx.rule->detail.node_type,
ctx.token,
ctx.parent);
return ast_node;
});
constant->detail.node_type = node_type;
return constant;
}
production_rule_t* parser_t::infix_right(
lexer::token_type_t token_type,
int32_t bp,
const led_callback_t& led) {
auto s = terminal(token_type, bp);
if (led) {
s->led = led;
} else {
s->led = [](context_t& ctx, entity_t lhs) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::binary_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::binary_operator_t>(
ast_node,
lhs,
ctx.parser->expression(*ctx.r, ctx.rule->lbp - 1));
return ast_node;
};
}
return s;
}
bool parser_t::apply(result_t& r) {
_rules.reserve(_tokens.size());
auto& registry = _session.registry();
for (auto entity : _tokens) {
const auto& token = registry.get<lexer::token_t>(entity);
auto s = _rule_table.find(token.type);
if (!s) {
const auto& loc = registry.get<source_location_t>(entity);
add_source_highlighted_error(
r,
errors::parser::invalid_token,
loc);
return false;
}
_rules.add(s);
}
return true;
}
entity_t parser_t::parse(result_t& r) {
auto& registry = _session.registry();
auto module_node = registry.create();
registry.assign<ast::node_t>(
module_node,
_session.allocator(),
ast::node_type_t::module,
null_entity,
null_entity);
auto scope_node = registry.create();
registry.assign<ast::node_t>(
scope_node,
_session.allocator(),
ast::node_type_t::scope,
null_entity,
module_node);
registry.assign<ast::scope_t>(
scope_node,
_session.allocator(),
null_entity);
auto block_node = registry.create();
registry.assign<ast::node_t>(
block_node,
_session.allocator(),
ast::node_type_t::block,
null_entity,
module_node);
registry.assign<ast::block_t>(
block_node,
_session.allocator(),
null_entity,
scope_node);
std::string_view name;
if (_buffer.path().empty()) {
name = _session.intern_pool().intern("(anonymous source)"sv);
} else {
auto base_filename = _buffer
.path()
.filename()
.replace_extension("");
name = _session.intern_pool().intern(base_filename.string());
}
registry.assign<ast::module_t>(
module_node,
_session.allocator(),
_buffer.path(),
name,
block_node);
_scopes.push(scope_node);
_blocks.push(block_node);
_parents.push(block_node);
while (has_more()) {
auto stmt_entity = registry.create();
registry.assign<ast::node_t>(
stmt_entity,
_session.allocator(),
ast::node_type_t::statement,
null_entity,
*_parents.top());
_parents.push(stmt_entity);
defer(_parents.pop());
_comma_rule->lbp = 25; // binding power for statements
auto expr = null_entity;
auto terminator_token = null_entity;
while (true) {
expr = expression(r);
if (expr == null_entity) {
const auto& loc = registry.get<source_location_t>(token());
add_source_highlighted_error(
r,
errors::parser::expected_expression,
loc);
return null_entity;
}
auto& expr_node = registry.get<ast::node_t>(expr);
auto& stmt_node = registry.get<ast::node_t>(stmt_entity);
switch (expr_node.type) {
case ast::node_type_t::directive: {
stmt_node.directives.add(expr);
expr = null_entity;
break;
}
case ast::node_type_t::annotation: {
stmt_node.annotations.add(expr);
expr = null_entity;
break;
}
case ast::node_type_t::line_comment:
case ast::node_type_t::block_comment: {
stmt_node.comments.add(expr);
expr = null_entity;
break;
}
default: {
break;
}
}
terminator_token = token();
const auto& t = registry.get<lexer::token_t>(terminator_token);
if (t.type == lexer::token_type_t::semicolon)
break;
}
if (!advance(r, lexer::token_type_t::semicolon))
break;
auto& stmt_node = registry.get<ast::node_t>(stmt_entity);
stmt_node.token = terminator_token;
registry.assign<ast::statement_t>(
stmt_entity,
_session.allocator(),
expr);
auto& block = registry.get<ast::block_t>(*_blocks.top());
block.children.add(stmt_entity);
}
_scopes.pop();
assert(_scopes.empty());
_blocks.pop();
assert(_blocks.empty());
_parents.pop();
assert(_parents.empty());
return module_node;
}
bool parser_t::initialize(result_t& r) {
terminal(lexer::token_type_t::comma);
terminal(lexer::token_type_t::semicolon);
terminal(lexer::token_type_t::right_paren);
terminal(lexer::token_type_t::right_bracket);
terminal(lexer::token_type_t::else_keyword);
terminal(lexer::token_type_t::end_of_input);
terminal(lexer::token_type_t::right_curly_brace);
postfix(lexer::token_type_t::caret, 80);
prefix(lexer::token_type_t::minus);
prefix(lexer::token_type_t::binary_not_operator);
prefix(lexer::token_type_t::logical_not_operator);
prefix(
lexer::token_type_t::line_comment,
[](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::line_comment,
ctx.token,
ctx.parent);
return ast_node;
});
prefix(
lexer::token_type_t::block_comment,
[](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::block_comment,
ctx.token,
ctx.parent);
return ast_node;
});
literal(lexer::token_type_t::block_literal, ast::node_type_t::block_literal);
literal(lexer::token_type_t::number_literal, ast::node_type_t::number_literal);
literal(lexer::token_type_t::string_literal, ast::node_type_t::string_literal);
constant(lexer::token_type_t::nil_keyword, ast::node_type_t::nil_literal);
constant(lexer::token_type_t::true_keyword, ast::node_type_t::boolean_literal);
constant(lexer::token_type_t::false_keyword, ast::node_type_t::boolean_literal);
constant(lexer::token_type_t::value_sink, ast::node_type_t::value_sink_literal);
constant(lexer::token_type_t::uninitialized, ast::node_type_t::uninitialized_literal);
infix_right(lexer::token_type_t::exponent_operator, 75);
infix_right(lexer::token_type_t::logical_or_operator, 30);
infix_right(lexer::token_type_t::logical_and_operator, 30);
infix(lexer::token_type_t::less_than, 40);
infix(lexer::token_type_t::in_operator, 40);
infix(lexer::token_type_t::greater_than, 40);
infix(lexer::token_type_t::equal_operator, 40);
infix(lexer::token_type_t::not_equal_operator, 40);
infix(lexer::token_type_t::inclusive_range_operator, 40);
infix(lexer::token_type_t::exclusive_range_operator, 40);
infix(lexer::token_type_t::less_than_equal_operator, 40);
infix(lexer::token_type_t::greater_than_equal_operator, 40);
infix(lexer::token_type_t::minus, 50);
infix(lexer::token_type_t::xor_operator, 70);
infix(lexer::token_type_t::shl_operator, 70);
infix(lexer::token_type_t::shr_operator, 70);
infix(lexer::token_type_t::rol_operator, 70);
infix(lexer::token_type_t::ror_operator, 70);
infix(lexer::token_type_t::add_operator, 50);
infix(lexer::token_type_t::divide_operator, 60);
infix(lexer::token_type_t::modulo_operator, 60);
infix(lexer::token_type_t::multiply_operator, 60);
infix(lexer::token_type_t::binary_or_operator, 70);
infix(lexer::token_type_t::binary_and_operator, 70);
// infix(
// lexer::token_type_t::block_comment,
// 10,
// [](context_t& ctx, entity_t lhs) {
// auto& node = ctx.registry->get<ast::node_t>(lhs);
// auto ast_node = ctx.registry->create();
// ctx.registry->assign<ast::node_t>(
// ast_node,
// ctx.allocator,
// ast::node_type_t::block_comment,
// ctx.token,
// ctx.parent);
// node.comments.add(ast_node);
// return ctx.parser->expression(*ctx.r, ctx.rule->lbp);
// });
assignment(lexer::token_type_t::bind_operator);
assignment(lexer::token_type_t::assignment_operator);
compound_assignment(
lexer::token_type_t::subtract_assignment_operator,
lexer::token_type_t::minus);
compound_assignment(
lexer::token_type_t::add_assignment_operator,
lexer::token_type_t::add_operator);
compound_assignment(
lexer::token_type_t::divide_assignment_operator,
lexer::token_type_t::divide_operator);
compound_assignment(
lexer::token_type_t::modulo_assignment_operator,
lexer::token_type_t::modulo_operator);
compound_assignment(
lexer::token_type_t::multiply_assignment_operator,
lexer::token_type_t::multiply_operator);
compound_assignment(
lexer::token_type_t::binary_or_assignment_operator,
lexer::token_type_t::binary_or_operator);
compound_assignment(
lexer::token_type_t::binary_and_assignment_operator,
lexer::token_type_t::binary_and_operator);
infix_right(lexer::token_type_t::lambda_operator, 20);
infix_right(lexer::token_type_t::associative_operator, 20);
_comma_rule = infix_right(lexer::token_type_t::comma, 25);
infix(
lexer::token_type_t::left_bracket,
90,
[](context_t& ctx, entity_t lhs) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::binary_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::binary_operator_t>(
ast_node,
lhs,
ctx.parser->expression(*ctx.r));
if (!ctx.parser->advance(*ctx.r, lexer::token_type_t::right_bracket))
return null_entity;
return ast_node;
});
infix(
lexer::token_type_t::member_select_operator,
90,
[](context_t& ctx, entity_t lhs) {
source_location_t loc;
if (!ctx.parser->is_node_valid_lvalue(lhs, loc)) {
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::member_select_operator_requires_identifier_lvalue,
loc);
return null_entity;
}
auto rhs_token = ctx.parser->token();
if (!ctx.parser->advance(*ctx.r, lexer::token_type_t::identifier))
return null_entity;
auto rhs_ident_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
rhs_ident_node,
ctx.allocator,
ast::node_type_t::identifier,
rhs_token,
ctx.parent);
ctx.registry->assign<ast::identifier_t>(
rhs_ident_node,
ctx.scope,
ctx.block);
auto& token = ctx.registry->get<lexer::token_t>(rhs_token);
auto& scope = ctx.registry->get<ast::scope_t>(ctx.scope);
scope.identifiers.insert(token.value, rhs_ident_node);
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::binary_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::binary_operator_t>(ast_node, lhs, rhs_ident_node);
return ast_node;
});
prefix(
lexer::token_type_t::left_paren,
[](context_t& ctx) {
auto expr = ctx.parser->expression(*ctx.r);
if (!ctx.parser->advance(*ctx.r, lexer::token_type_t::right_paren))
return null_entity;
return expr;
});
prefix(
lexer::token_type_t::identifier,
[](context_t& ctx) {
auto& scope = ctx.registry->get<ast::scope_t>(ctx.scope);
auto& token = ctx.registry->get<lexer::token_t>(ctx.token);
auto var = scope.identifiers.search(token.value);
if (var) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::identifier_reference,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::identifier_ref_t>(ast_node, *var);
return ast_node;
}
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::identifier,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::identifier_t>(
ast_node,
ctx.scope,
ctx.block);
scope.identifiers.insert(token.value, ast_node);
return ast_node;
});
prefix(
lexer::token_type_t::annotation,
[](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::annotation,
ctx.token,
ctx.parent);
auto& annotation = ctx.registry->assign<ast::annotation_t>(ast_node);
annotation.lhs = ctx.parser->expression(*ctx.r, 0);
annotation.rhs = ctx.parser->expression(*ctx.r, 0);
return ast_node;
});
prefix(
lexer::token_type_t::directive,
[](context_t& ctx) {
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::directive,
ctx.token,
ctx.parent);
auto& directive = ctx.registry->assign<ast::directive_t>(ast_node);
directive.lhs = ctx.parser->expression(*ctx.r, 0);
directive.rhs = ctx.parser->expression(*ctx.r, 0);
return ast_node;
});
return apply(r);
}
production_rule_t* parser_t::rule() const {
return _rules[_token_index];
}
void parser_t::comma_binding_power(int32_t bp) {
_comma_rule->lbp = bp;
}
production_rule_t* parser_t::compound_assignment(
lexer::token_type_t token_type,
lexer::token_type_t op_type) {
auto rule = infix(
token_type,
20,
[](context_t& ctx, entity_t lhs) {
{
source_location_t loc;
if (!ctx.parser->is_node_valid_lvalue(lhs, loc)) {
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::assignment_requires_valid_lvalue,
loc);
return null_entity;
}
}
auto rhs = ctx.parser->expression(
*ctx.r,
ctx.rule->lbp - 1);
if (rhs == null_entity)
return null_entity;
const auto& rhs_node = ctx.registry->get<ast::node_t>(rhs);
if (rhs_node.type == ast::node_type_t::assignment_operator) {
const auto& loc = ctx.registry->get<source_location_t>(rhs_node.token);
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::invalid_assignment_expression,
loc);
return null_entity;
}
const auto& token = ctx.registry->get<lexer::token_t>(ctx.token);
auto bin_op_token = ctx.registry->create();
ctx.registry->assign<lexer::token_t>(
bin_op_token,
ctx.rule->detail.op_type,
std::string_view(token.value.data(), 1));
auto bin_op_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
bin_op_node,
ctx.allocator,
ast::node_type_t::binary_operator,
bin_op_token,
ctx.parent);
ctx.registry->assign<ast::binary_operator_t>(bin_op_node, lhs, rhs);
auto assignment_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
assignment_node,
ctx.allocator,
ast::node_type_t::assignment_operator,
ctx.token,
ctx.parent);
ctx.registry->assign<ast::assignment_operator_t>(assignment_node, lhs, bin_op_node);
return assignment_node;
});
rule->detail.op_type = op_type;
return rule;
}
entity_t parser_t::expression(result_t& r, int32_t rbp) {
if (!has_more()) return null_entity;
auto current_rule = rule();
auto current_token = token();
context_t ctx{
.r = &r,
.parser = this,
.rule = current_rule,
.token = current_token,
.scope = *_scopes.top(),
.block = *_blocks.top(),
.parent = *_parents.top(),
.registry = &_session.registry(),
.allocator = _session.allocator()
};
if (!advance(r))
return null_entity;
auto lhs = current_rule->nud(ctx);
auto next_rule = rule();
while (rbp < next_rule->lbp) {
ctx.token = token();
ctx.rule = next_rule;
ctx.scope = *_scopes.top();
ctx.block = *_blocks.top();
ctx.parent = *_parents.top();
if (!advance(r)) return null_entity;
lhs = next_rule->led(ctx, lhs);
next_rule = rule();
}
return lhs;
}
bool parser_t::expect(result_t& r, lexer::token_type_t type) {
if (type == lexer::token_type_t::none) return true;
auto entity = token();
auto& registry = _session.registry();
const auto& t = registry.get<lexer::token_t>(entity);
if (type != t.type) {
const auto& loc = registry.get<source_location_t>(entity);
add_source_highlighted_error(
r,
errors::parser::unexpected_token,
loc,
lexer::token_type_to_name(type),
lexer::token_type_to_name(t.type));
return false;
}
return true;
}
bool parser_t::advance(result_t& r, lexer::token_type_t type) {
if (type != lexer::token_type_t::none && !expect(r, type))
return false;
if (_token_index < _tokens.size()) {
++_token_index;
return true;
} else {
return false;
}
}
production_rule_t* parser_t::assignment(lexer::token_type_t token_type) {
return infix(
token_type,
20,
[](context_t& ctx, entity_t lhs) {
{
source_location_t loc;
if (!ctx.parser->is_node_valid_lvalue(lhs, loc)) {
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::assignment_requires_valid_lvalue,
loc);
return null_entity;
}
}
auto ast_node = ctx.registry->create();
ctx.registry->assign<ast::node_t>(
ast_node,
ctx.allocator,
ast::node_type_t::assignment_operator,
ctx.token,
ctx.parent);
auto rhs = ctx.parser->expression(
*ctx.r,
ctx.rule->lbp - 1);
if (rhs == null_entity)
return null_entity;
const auto& node = ctx.registry->get<ast::node_t>(rhs);
if (node.type == ast::node_type_t::assignment_operator) {
const auto& loc = ctx.registry->get<source_location_t>(node.token);
ctx.parser->add_source_highlighted_error(
*ctx.r,
errors::parser::invalid_assignment_expression,
loc);
return null_entity;
}
ctx.registry->assign<ast::assignment_operator_t>(
ast_node,
lhs,
rhs);
return ast_node;
});
}
bool parser_t::is_node_valid_lvalue(entity_t expr, source_location_t& loc) {
auto& registry = _session.registry();
const auto node = registry.try_get<ast::node_t>(expr);
if (!node) return false;
if (node->type == ast::node_type_t::identifier
|| node->type == ast::node_type_t::identifier_reference) {
return true;
}
if (node->type == ast::node_type_t::binary_operator) {
const auto& token = registry.get<lexer::token_t>(node->token);
if (token.type == lexer::token_type_t::comma
|| token.type == lexer::token_type_t::left_bracket
|| token.type == lexer::token_type_t::member_select_operator) {
return true;
}
}
if (node->type == ast::node_type_t::unary_operator) {
const auto& token = registry.get<lexer::token_t>(node->token);
if (token.type == lexer::token_type_t::caret) {
return true;
}
}
loc = registry.get<source_location_t>(node->token);
return false;
}
}
| 36.385143
| 100
| 0.493106
|
basecode-lang
|
c7d743869bf6717e7052798f344c50ccf064d45c
| 890
|
cpp
|
C++
|
leetcode/contest-219/5245.cpp
|
upupming/algorithm
|
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
|
[
"MIT"
] | 107
|
2019-10-25T07:46:59.000Z
|
2022-03-29T11:10:56.000Z
|
leetcode/contest-219/5245.cpp
|
upupming/algorithm
|
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
|
[
"MIT"
] | 1
|
2021-08-13T05:42:27.000Z
|
2021-08-13T05:42:27.000Z
|
leetcode/contest-219/5245.cpp
|
upupming/algorithm
|
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
|
[
"MIT"
] | 18
|
2020-12-09T14:24:22.000Z
|
2022-03-30T06:56:01.000Z
|
#include <bits/stdc++.h>
using namespace std;
/*
最优解一定满足两个性质:
1. 长宽高排序之后答案不变
2. 答案就是排序之后每个长方体最大值之和(可以构成单调子序列的那些长方体)
*/
class Solution {
public:
int maxHeight(vector<vector<int>>& cuboids) {
int n = cuboids.size();
// 一定要用引用
for (auto& c : cuboids) {
sort(c.begin(), c.end());
}
sort(cuboids.begin(), cuboids.end(), greater<vector<int>>());
vector<int> f(n);
int ans = 0;
// 最长单调下降子序列
for (int i = 0; i < n; i++) {
f[i] = cuboids[i][2];
for (int j = 0; j < i; j++) {
if (cuboids[i][0] <= cuboids[j][0] &&
cuboids[i][1] <= cuboids[j][1] &&
cuboids[i][2] <= cuboids[j][2])
f[i] = max(f[i], f[j] + cuboids[i][2]);
}
ans = max(ans, f[i]);
}
return ans;
}
};
| 25.428571
| 69
| 0.437079
|
upupming
|
93a87647d6418306fc902f4418cb4125cef44ff0
| 1,683
|
hpp
|
C++
|
System.Windows.Forms/include/Switch/System/Windows/Forms/FormBorderStyle.hpp
|
kkptm/CppLikeCSharp
|
b2d8d9da9973c733205aa945c9ba734de0c734bc
|
[
"MIT"
] | 4
|
2021-10-14T01:43:00.000Z
|
2022-03-13T02:16:08.000Z
|
System.Windows.Forms/include/Switch/System/Windows/Forms/FormBorderStyle.hpp
|
kkptm/CppLikeCSharp
|
b2d8d9da9973c733205aa945c9ba734de0c734bc
|
[
"MIT"
] | null | null | null |
System.Windows.Forms/include/Switch/System/Windows/Forms/FormBorderStyle.hpp
|
kkptm/CppLikeCSharp
|
b2d8d9da9973c733205aa945c9ba734de0c734bc
|
[
"MIT"
] | 2
|
2022-03-13T02:16:06.000Z
|
2022-03-14T14:32:57.000Z
|
/// @file
/// @brief Contains Switch::System::Windows::Forms::BorderStyle enum.
#pragma once
#include <Switch/System/Enum.hpp>
namespace Switch {
namespace System {
namespace Windows {
namespace Forms {
/// @brief Specifies the border styles for a form.
enum class FormBorderStyle {
/// @brief No border.
None,
/// @brief A fixed, single-line border.
FixedSingle,
/// @brief A fixed, three-dimensional border.
Fixed3D,
/// @brief A thick, fixed dialog-style border.
FixedDialog = 3,
/// @brief A resizable border.
Sizable = 4,
/// @brief A tool window border
FixedToolWindow = 5,
/// @brief A resizable tool window border.
SizableToolWindow = 6,
};
}
}
}
}
/// @cond
template<>
struct EnumRegister<System::Windows::Forms::FormBorderStyle> {
void operator()(System::Collections::Generic::IDictionary<System::Windows::Forms::FormBorderStyle, string>& values, bool& flags) {
values[System::Windows::Forms::FormBorderStyle::None] = "None";
values[System::Windows::Forms::FormBorderStyle::FixedSingle] = "FixedSingle";
values[System::Windows::Forms::FormBorderStyle::Fixed3D] = "Fixed3D";
values[System::Windows::Forms::FormBorderStyle::FixedDialog] = "FixedDialog";
values[System::Windows::Forms::FormBorderStyle::Sizable] = "Sizable";
values[System::Windows::Forms::FormBorderStyle::FixedToolWindow] = "FixedToolWindow";
values[System::Windows::Forms::FormBorderStyle::Fixed3D] = "SizableToolWindow";
flags = false;
}
};
/// @endcond
using namespace Switch;
| 33.66
| 132
| 0.639929
|
kkptm
|
93ab36c964bc04cac5d0c0e2e3db84a9370d46a0
| 474
|
cpp
|
C++
|
jni/WiEngine_binding/gridactions/com_wiyun_engine_actions_grid_Waves3D.cpp
|
zchajax/WiEngine
|
ea2fa297f00aa5367bb5b819d6714ac84a8a8e25
|
[
"MIT"
] | 39
|
2015-01-23T10:01:31.000Z
|
2021-06-10T03:01:18.000Z
|
jni/WiEngine_binding/gridactions/com_wiyun_engine_actions_grid_Waves3D.cpp
|
luckypen/WiEngine
|
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
|
[
"MIT"
] | 1
|
2015-04-15T08:07:47.000Z
|
2015-04-15T08:07:47.000Z
|
jni/WiEngine_binding/gridactions/com_wiyun_engine_actions_grid_Waves3D.cpp
|
luckypen/WiEngine
|
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
|
[
"MIT"
] | 20
|
2015-01-20T07:36:10.000Z
|
2019-09-15T01:02:19.000Z
|
#include "com_wiyun_engine_actions_grid_Waves3D.h"
#include "wyWaves3D.h"
extern jfieldID g_fid_BaseObject_mPointer;
JNIEXPORT void JNICALL Java_com_wiyun_engine_actions_grid_Waves3D_nativeInit
(JNIEnv * env, jobject thiz, jfloat duration, jint gridX, jint gridY, jfloat amplitude, jint waves) {
wyWaves3D* g = WYNEW wyWaves3D(duration, gridX, gridY, amplitude, waves);
env->SetIntField(thiz, g_fid_BaseObject_mPointer, (jint)g);
wyObjectAutoRelease(g);
}
| 39.5
| 104
| 0.78903
|
zchajax
|
93aed6408e1594864ceb8cde169762462cd38966
| 5,248
|
cpp
|
C++
|
SDK/PUBG_ReplayEditorStepperWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 7
|
2019-03-06T11:04:52.000Z
|
2019-07-10T20:00:51.000Z
|
SDK/PUBG_ReplayEditorStepperWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | null | null | null |
SDK/PUBG_ReplayEditorStepperWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 10
|
2019-03-06T11:53:46.000Z
|
2021-02-18T14:01:11.000Z
|
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_ReplayEditorStepperWidget_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.AddItem
// ()
// Parameters:
// class FString* KeyItem (Parm, ZeroConstructor)
void UReplayEditorStepperWidget_C::AddItem(class FString* KeyItem)
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.AddItem");
UReplayEditorStepperWidget_C_AddItem_Params params;
params.KeyItem = KeyItem;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.SetItem
// ()
// Parameters:
// class FString* KeyItem (Parm, ZeroConstructor)
void UReplayEditorStepperWidget_C::SetItem(class FString* KeyItem)
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.SetItem");
UReplayEditorStepperWidget_C_SetItem_Params params;
params.KeyItem = KeyItem;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.GetSelectedItem
// ()
// Parameters:
// class FString CurItem (Parm, OutParm, ZeroConstructor)
void UReplayEditorStepperWidget_C::GetSelectedItem(class FString* CurItem)
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.GetSelectedItem");
UReplayEditorStepperWidget_C_GetSelectedItem_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (CurItem != nullptr)
*CurItem = params.CurItem;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.ShowCurString
// ()
void UReplayEditorStepperWidget_C::ShowCurString()
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.ShowCurString");
UReplayEditorStepperWidget_C_ShowCurString_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.Construct
// (BlueprintCosmetic, Event)
void UReplayEditorStepperWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.Construct");
UReplayEditorStepperWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.BndEvt__ButtonLeft_K2Node_ComponentBoundEvent_155_OnButtonClickedEvent__DelegateSignature
// ()
void UReplayEditorStepperWidget_C::BndEvt__ButtonLeft_K2Node_ComponentBoundEvent_155_OnButtonClickedEvent__DelegateSignature()
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.BndEvt__ButtonLeft_K2Node_ComponentBoundEvent_155_OnButtonClickedEvent__DelegateSignature");
UReplayEditorStepperWidget_C_BndEvt__ButtonLeft_K2Node_ComponentBoundEvent_155_OnButtonClickedEvent__DelegateSignature_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.BndEvt__ButtonRight_K2Node_ComponentBoundEvent_177_OnButtonClickedEvent__DelegateSignature
// ()
void UReplayEditorStepperWidget_C::BndEvt__ButtonRight_K2Node_ComponentBoundEvent_177_OnButtonClickedEvent__DelegateSignature()
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.BndEvt__ButtonRight_K2Node_ComponentBoundEvent_177_OnButtonClickedEvent__DelegateSignature");
UReplayEditorStepperWidget_C_BndEvt__ButtonRight_K2Node_ComponentBoundEvent_177_OnButtonClickedEvent__DelegateSignature_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.ExecuteUbergraph_ReplayEditorStepperWidget
// ()
// Parameters:
// int* EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UReplayEditorStepperWidget_C::ExecuteUbergraph_ReplayEditorStepperWidget(int* EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function ReplayEditorStepperWidget.ReplayEditorStepperWidget_C.ExecuteUbergraph_ReplayEditorStepperWidget");
UReplayEditorStepperWidget_C_ExecuteUbergraph_ReplayEditorStepperWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 30.870588
| 206
| 0.780869
|
realrespecter
|
93b19508039e9c7acd3fd32dae05e5fd7cf2933f
| 35
|
cpp
|
C++
|
src/gui/gui.cpp
|
lchsk/knight-libs
|
14cb06e4092bf78abd7a5d0d5313b10236ee8926
|
[
"MIT"
] | null | null | null |
src/gui/gui.cpp
|
lchsk/knight-libs
|
14cb06e4092bf78abd7a5d0d5313b10236ee8926
|
[
"MIT"
] | null | null | null |
src/gui/gui.cpp
|
lchsk/knight-libs
|
14cb06e4092bf78abd7a5d0d5313b10236ee8926
|
[
"MIT"
] | null | null | null |
#include "gui.hpp"
namespace K {}
| 8.75
| 18
| 0.657143
|
lchsk
|
93b3f63512c632be8d567f4856a32d979c0f1eeb
| 368
|
cpp
|
C++
|
web/httpd/kernel/chunks.cpp
|
jjzhang166/balancer
|
84addf52873d8814b8fd30289f2fcfcec570c151
|
[
"Unlicense"
] | 39
|
2015-03-12T19:49:24.000Z
|
2020-11-11T09:58:15.000Z
|
web/httpd/kernel/chunks.cpp
|
jjzhang166/balancer
|
84addf52873d8814b8fd30289f2fcfcec570c151
|
[
"Unlicense"
] | null | null | null |
web/httpd/kernel/chunks.cpp
|
jjzhang166/balancer
|
84addf52873d8814b8fd30289f2fcfcec570c151
|
[
"Unlicense"
] | 11
|
2016-01-14T16:42:00.000Z
|
2022-01-17T11:47:33.000Z
|
#include "chunks.h"
#include <util/stream/output.h>
using namespace NSrvKernel;
template <>
void Out<TChunk>(TOutputStream& o, const TChunk& p) {
o.Write(p.Data(), p.Length());
}
template <>
void Out<TChunkList>(TOutputStream& o, const TChunkList& lst) {
for (TChunkList::TConstIterator it = lst.Begin(); it != lst.End(); ++it) {
o << *it;
}
}
| 20.444444
| 78
| 0.63587
|
jjzhang166
|
93b6cd6f6932802b8424570691e10e609b4f97ed
| 10,715
|
hpp
|
C++
|
include/memoria/prototypes/bt/container/bt_c_leaf_variable.hpp
|
victor-smirnov/memoria
|
c36a957c63532176b042b411b1646c536e71a658
|
[
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2
|
2021-07-30T16:54:24.000Z
|
2021-09-08T15:48:17.000Z
|
include/memoria/prototypes/bt/container/bt_c_leaf_variable.hpp
|
victor-smirnov/memoria
|
c36a957c63532176b042b411b1646c536e71a658
|
[
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | null | null | null |
include/memoria/prototypes/bt/container/bt_c_leaf_variable.hpp
|
victor-smirnov/memoria
|
c36a957c63532176b042b411b1646c536e71a658
|
[
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2
|
2020-03-14T15:15:25.000Z
|
2020-06-15T11:26:56.000Z
|
// Copyright 2015 Victor Smirnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memoria/prototypes/bt/tools/bt_tools.hpp>
#include <memoria/prototypes/bt/bt_macros.hpp>
#include <memoria/core/container/macros.hpp>
#include <memoria/prototypes/bt/nodes/leaf_node_so.hpp>
#include <memoria/prototypes/bt/nodes/branch_node_so.hpp>
#include <vector>
namespace memoria {
MEMORIA_V1_CONTAINER_PART_BEGIN(bt::LeafVariableName)
using typename Base::TreeNodePtr;
using typename Base::TreeNodeConstPtr;
using typename Base::Iterator;
using typename Base::Position;
using typename Base::TreePathT;
using typename Base::CtrSizeT;
using typename Base::BranchNodeEntry;
using typename Base::BlockUpdateMgr;
// TODO: noexcept
template <int32_t Stream>
struct InsertStreamEntryFn
{
template <
int32_t Idx,
typename SubstreamType,
typename Entry
>
VoidResult stream(SubstreamType&& obj, int32_t idx, const Entry& entry) noexcept
{
if (obj)
{
return obj.insert_entries(idx, 1, [&](psize_t block, psize_t row) -> const auto& {
return entry.get(bt::StreamTag<Stream>(), bt::StreamTag<Idx>(), block);
});
}
else {
return make_generic_error("Substream {} is empty", Idx);
}
}
template <typename CtrT, typename NTypes, typename... Args>
VoidResult treeNode(LeafNodeSO<CtrT, NTypes>& node, int32_t idx, Args&&... args) noexcept
{
MEMORIA_TRY_VOID(node.layout(255));
return node.template processSubstreams<IntList<Stream>>(*this, idx, std::forward<Args>(args)...);
}
};
template <int32_t Stream, typename Entry>
VoidResult ctr_try_insert_stream_entry_no_mgr(const TreeNodePtr& leaf, int32_t idx, const Entry& entry) noexcept
{
InsertStreamEntryFn<Stream> fn;
return self().leaf_dispatcher().dispatch(leaf, fn, idx, entry);
}
template <int32_t Stream, typename Entry>
bool ctr_try_insert_stream_entry(
Iterator& iter,
int32_t idx,
const Entry& entry
)
{
auto& self = this->self();
self.ctr_cow_clone_path(iter.path(), 0);
BlockUpdateMgr mgr(self);
self.ctr_update_block_guard(iter.iter_leaf());
mgr.add(iter.iter_leaf().as_mutable());
auto status = self.template ctr_try_insert_stream_entry_no_mgr<Stream>(iter.iter_leaf().as_mutable(), idx, entry);
if (status.is_error()) {
if (status.is_packed_error())
{
mgr.rollback();
return false;
}
else {
MEMORIA_PROPAGATE_ERROR(status).do_throw();
}
}
return true;
}
bool ctr_with_block_manager(
TreeNodePtr& leaf,
int structure_idx,
int stream_idx,
const std::function<VoidResult (int, int)>& insert_fn
)
{
auto& self = this->self();
BlockUpdateMgr mgr(self);
self.ctr_update_block_guard(leaf);
mgr.add(leaf);
VoidResult status = insert_fn(structure_idx, stream_idx);
if (status.is_ok()) {
return true;
}
else if (status.memoria_error()->error_category() == ErrorCategory::PACKED)
{
mgr.rollback();
return false;
}
else {
status.get_or_throw();
return false;
}
}
template <int32_t Stream>
struct RemoveFromLeafFn
{
template <
int32_t Idx,
typename SubstreamType
>
VoidResult stream(SubstreamType&& obj, int32_t idx) noexcept
{
return obj.remove_entries(idx, 1);
}
template <typename CtrT, typename NTypes>
VoidResult treeNode(LeafNodeSO<CtrT, NTypes>& node, int32_t idx) noexcept
{
MEMORIA_TRY_VOID(node.layout(255));
return node.template processSubstreams<IntList<Stream>>(*this, idx);
}
};
template <int32_t Stream>
bool ctr_try_remove_stream_entry(TreePathT& path, int32_t idx)
{
auto& self = this->self();
self.ctr_cow_clone_path(path, 0);
BlockUpdateMgr mgr(self);
self.ctr_update_block_guard(path.leaf());
mgr.add(path.leaf().as_mutable());
RemoveFromLeafFn<Stream> fn;
VoidResult status = self.leaf_dispatcher().dispatch(path.leaf().as_mutable(), fn, idx);
if (status.is_ok()) {
return true;
}
else if (status.is_packed_error()) {
mgr.rollback();
return false;
}
else {
status.get_or_throw();
return false;
}
}
//=========================================================================================
template <typename SubstreamsList>
struct UpdateStreamEntryBufferFn
{
template <
int32_t StreamIdx,
int32_t AllocatorIdx,
int32_t Idx,
typename SubstreamType,
typename Entry
>
VoidResult stream(SubstreamType&& obj, int32_t idx, const Entry& entry) noexcept
{
return obj.update_entries(idx, 1, [&](auto block, auto){
return entry.get(bt::StreamTag<StreamIdx>(), bt::StreamTag<Idx>(), block);
});
}
template <typename CtrT, typename NTypes, typename... Args>
VoidResult treeNode(LeafNodeSO<CtrT, NTypes>& node, int32_t idx, Args&&... args) noexcept
{
return node.template processSubstreams<
SubstreamsList
>(
*this,
idx,
std::forward<Args>(args)...
);
}
};
template <typename SubstreamsList, typename Entry>
bool ctr_try_update_stream_entry(Iterator& iter, int32_t idx, const Entry& entry)
{
auto& self = this->self();
self.ctr_cow_clone_path(iter.path(), 0);
BlockUpdateMgr mgr(self);
self.ctr_update_block_guard(iter.iter_leaf().as_mutable());
mgr.add(iter.iter_leaf().as_mutable());
UpdateStreamEntryBufferFn<SubstreamsList> fn;
VoidResult status = self.leaf_dispatcher().dispatch(
iter.iter_leaf().as_mutable(),
fn,
idx,
entry
);
if (status.is_ok()) {
return true;
}
else if (status.memoria_error()->error_category() == ErrorCategory::PACKED)
{
mgr.rollback();
return false;
}
else {
status.get_or_throw();
return false;
}
}
template <typename Fn, typename... Args>
bool update(Iterator& iter, Fn&& fn, Args&&... args)
{
auto& self = this->self();
return self.ctr_update_atomic(iter, std::forward<Fn>(fn), VLSelector(), std::forward<Fn>(args)...);
}
MEMORIA_V1_DECLARE_NODE_FN(TryMergeNodesFn, mergeWith);
bool ctr_try_merge_leaf_nodes(TreePathT& tgt_path, TreePathT& src_path);
bool ctr_merge_leaf_nodes(TreePathT& tgt, TreePathT& src, bool only_if_same_parent = false);
bool ctr_merge_current_leaf_nodes(TreePathT& tgt, TreePathT& src);
MEMORIA_V1_CONTAINER_PART_END
#define M_TYPE MEMORIA_V1_CONTAINER_TYPE(bt::LeafVariableName)
#define M_PARAMS MEMORIA_V1_CONTAINER_TEMPLATE_PARAMS
M_PARAMS
bool M_TYPE::ctr_try_merge_leaf_nodes(TreePathT& tgt_path, TreePathT& src_path)
{
auto& self = this->self();
self.ctr_check_same_paths(tgt_path, src_path, 1);
auto src_parent = self.ctr_get_node_parent(src_path, 0);
auto parent_idx = self.ctr_get_child_idx(src_parent, src_path.leaf()->id());
self.ctr_cow_clone_path(tgt_path, 0);
BlockUpdateMgr mgr(self);
TreeNodeConstPtr tgt = tgt_path.leaf();
TreeNodeConstPtr src = src_path.leaf();
self.ctr_update_block_guard(tgt);
// FIXME: Need to leave src node untouched on merge.
mgr.add(tgt.as_mutable());
//MEMORIA_TRY(tgt_sizes, self.ctr_get_node_sizes(tgt));
VoidResult res = self.leaf_dispatcher().dispatch_1st_const(src, tgt.as_mutable(), TryMergeNodesFn());
if (res.is_error())
{
if (res.is_packed_error())
{
mgr.rollback();
return false;
}
else {
MEMORIA_PROPAGATE_ERROR(res).do_throw();
}
}
self.ctr_remove_non_leaf_node_entry(tgt_path, 1, parent_idx).get_or_throw();
self.ctr_update_path(tgt_path, 0);
self.ctr_cow_ref_children_after_merge(src.as_mutable());
self.ctr_unref_block(src->id());
self.ctr_check_path(tgt_path, 0);
return true;
}
M_PARAMS
bool M_TYPE::ctr_merge_leaf_nodes(TreePathT& tgt_path, TreePathT& src_path, bool only_if_same_parent)
{
auto& self = this->self();
auto same_parent = self.ctr_is_the_same_parent(tgt_path, src_path, 0);
if (same_parent)
{
auto merged = self.ctr_merge_current_leaf_nodes(tgt_path, src_path);
if (!merged)
{
self.ctr_assign_path_nodes(tgt_path, src_path);
self.ctr_expect_next_node(src_path, 0);
}
return merged;
}
else if (!only_if_same_parent)
{
auto merged = self.ctr_merge_branch_nodes(tgt_path, src_path, 1, only_if_same_parent);
self.ctr_assign_path_nodes(tgt_path, src_path, 0);
self.ctr_expect_next_node(src_path, 0);
if (merged)
{
return self.ctr_merge_current_leaf_nodes(tgt_path, src_path);
}
}
return false;
}
M_PARAMS
bool M_TYPE::ctr_merge_current_leaf_nodes(TreePathT& tgt, TreePathT& src)
{
auto& self = this->self();
auto merged = self.ctr_try_merge_leaf_nodes(tgt, src);
if (merged)
{
self.ctr_remove_redundant_root(tgt, 0);
return true;
}
else {
return false;
}
}
#undef M_TYPE
#undef M_PARAMS
}
| 26.522277
| 122
| 0.602706
|
victor-smirnov
|
93b8ae2ccb30914bf41e94c39d0ab0d2910f05d0
| 818
|
cpp
|
C++
|
codeforces/D - Minimum Triangulation/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/D - Minimum Triangulation/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/D - Minimum Triangulation/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Mar/22/2019 21:42
* solution_verdict: Accepted language: GNU C++14
* run_time: 31 ms memory_used: 0 KB
* problem: https://codeforces.com/contest/1140/problem/D
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;long ans=0;
for(long i=2;i<n;i++)
ans+=(i*(i+1));
cout<<ans<<endl;
return 0;
}
| 43.052632
| 111
| 0.360636
|
kzvd4729
|
93b9f51c946aa792d1050b0463bb5d673cc7ac2a
| 6,155
|
cpp
|
C++
|
src/dio.cpp
|
johnsonjason/RVDbg
|
63790440d3089bf74985171947483f5bfbcbe06b
|
[
"MIT"
] | 16
|
2019-09-05T01:12:21.000Z
|
2022-01-10T12:33:31.000Z
|
src/dio.cpp
|
longmode/RVDbg
|
63790440d3089bf74985171947483f5bfbcbe06b
|
[
"MIT"
] | null | null | null |
src/dio.cpp
|
longmode/RVDbg
|
63790440d3089bf74985171947483f5bfbcbe06b
|
[
"MIT"
] | 3
|
2018-09-07T08:51:26.000Z
|
2019-01-06T07:39:13.000Z
|
#include "stdafx.h"
#include "dio.h"
/*++
Routine Description:
Initializes WSA data / Winsock
Parameters:
None
Return Value:
None
--*/
void dio::InitializeNetwork()
{
WSAData WsaData;
WSAStartup(MAKEWORD(2, 2), &WsaData);
}
/*++
Routine Description:
Starts the Debug Server, which interfaces with the Debug Client
The Debug Server is what receives user input while the Debug Client is the actual debugger that manipulates the process
Parameters:
Ip - The IP address for the debug server, typically loopback
Port - The port number to use for the debug server
Return Value:
None
--*/
dio::Server::Server(std::string Ip, std::uint16_t Port)
{
SOCKADDR_IN SocketAddress = { 0 };
SocketAddress.sin_addr.s_addr = inet_addr(Ip.c_str());
SocketAddress.sin_port = htons(Port);
SocketAddress.sin_family = AF_INET;
ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(ServerSocket, reinterpret_cast<SOCKADDR*>(&SocketAddress), sizeof(SocketAddress));
listen(ServerSocket, 1);
BoundDebugger = accept(ServerSocket, NULL, NULL);
}
dio::Server::~Server()
{
closesocket(this->ServerSocket);
closesocket(this->BoundDebugger);
}
/*++
Routine Description:
Sends a command to the debug client
Parameters:
ControlCode - A single byte-sized value that represents the type of command operation
CommandParamOne - Optional command parameter
CommandParamTwo - Optional command parameter
Return Value:
None
--*/
void dio::Server::SendCommand(BYTE ControlCode, DWORD_PTR CommandParamOne, DWORD_PTR CommandParamTwo)
{
//
// Create a buffer that can store ControlCode, CommandParamOne, and CommandParamTwo
//
const size_t ControlSize = sizeof(ControlCode) + sizeof(CommandParamOne) + sizeof(CommandParamTwo);
BYTE Buffer[ControlSize] = { 0 };
//
// Set each value in the buffer, separated and parsed by size
//
memset(Buffer, ControlCode, sizeof(ControlCode));
memcpy(Buffer + sizeof(ControlCode), &CommandParamOne, sizeof(CommandParamOne));
memcpy(Buffer + sizeof(ControlCode) + sizeof(CommandParamOne), &CommandParamTwo, sizeof(CommandParamTwo));
//
// Send the buffer's data to the debugger
//
send(BoundDebugger, reinterpret_cast<char*>(Buffer), sizeof(Buffer), 0);
}
/*++
Routine Description:
Receives a command from a debug client
Parameters:
None
Return Value:
None
--*/
std::tuple<BYTE, DWORD_PTR, DWORD_PTR> dio::Server::ReceiveCommand()
{
BYTE ControlCode = NULL;
DWORD_PTR CommandParamOne = NULL;
DWORD_PTR CommandParamTwo = NULL;
const size_t ControlSize = sizeof(BYTE) + sizeof(DWORD_PTR) + sizeof(DWORD_PTR);
BYTE Buffer[ControlSize] = { 0 };
DWORD Status = recv(BoundDebugger, reinterpret_cast<char*>(Buffer), sizeof(Buffer), 0);
if (Status == SOCKET_ERROR || Status == NULL)
{
return { CTL_ERROR_CON, 0, 0 };
}
//
// Parse the buffer into each individual command attribute
// Convert each individual command attribute into a tuple
//
memcpy(&ControlCode, Buffer, sizeof(ControlCode));
memcpy(&CommandParamOne, Buffer + sizeof(ControlCode), sizeof(CommandParamOne));
memcpy(&CommandParamTwo, Buffer + sizeof(ControlCode) + sizeof(CommandParamOne), sizeof(CommandParamTwo));
std::tuple<BYTE, DWORD_PTR, DWORD_PTR> Command(ControlCode, CommandParamOne, CommandParamTwo);
//
// If the control code is greater than 16...TBA
//
if (std::get<0>(Command) > 16)
{
}
return Command;
}
std::string dio::Server::ReceiveString()
{
char Buffer[2048] = { 0 };
recv(BoundDebugger, Buffer, sizeof(Buffer), 0);
return std::string(Buffer);
}
dio::Client::Client(std::string Ip, std::uint16_t Port)
{
SOCKADDR_IN SocketAddress = { 0 };
SocketAddress.sin_addr.s_addr = inet_addr(Ip.c_str());
SocketAddress.sin_port = htons(Port);
SocketAddress.sin_family = AF_INET;
ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(ClientSocket, reinterpret_cast<SOCKADDR*>(&SocketAddress), sizeof(SocketAddress));
}
/*++
Routine Description:
Sends a command to the debug server
Parameters:
ControlCode - A single byte-sized value that represents the type of command operation
CommandParamOne - Optional command parameter
CommandParamTwo - Optional command parameter
Return Value:
None
--*/
void dio::Client::SendCommand(BYTE ControlCode, DWORD_PTR CommandParamOne, DWORD_PTR CommandParamTwo)
{
//
// Create a buffer that can store ControlCode, CommandParamOne, and CommandParamTwo
//
const size_t ControlSize = sizeof(ControlCode) + sizeof(CommandParamOne) + sizeof(CommandParamTwo);
BYTE Buffer[ControlSize] = { 0 };
//
// Set each value in the buffer, separated and parsed by size
//
memset(Buffer, ControlCode, sizeof(ControlCode));
memset(Buffer + sizeof(ControlCode), CommandParamOne, sizeof(CommandParamOne));
memset(Buffer + sizeof(ControlCode) + sizeof(CommandParamOne), CommandParamTwo, sizeof(CommandParamTwo));
//
// Send the buffer's data to the debugger
//
send(ClientSocket, reinterpret_cast<char*>(Buffer), sizeof(Buffer), 0);
}
/*++
Routine Description:
Receives a command from a debug server
Parameters:
None
Return Value:
None
--*/
std::tuple<BYTE, DWORD_PTR, DWORD_PTR> dio::Client::ReceiveCommand()
{
BYTE ControlCode = NULL;
DWORD_PTR CommandParamOne = NULL;
DWORD_PTR CommandParamTwo = NULL;
const size_t ControlSize = sizeof(BYTE) + sizeof(DWORD_PTR) + sizeof(DWORD_PTR);
BYTE Buffer[ControlSize] = { 0 };
DWORD Status = recv(ClientSocket, reinterpret_cast<char*>(Buffer), sizeof(Buffer), 0);
if (Status == SOCKET_ERROR || Status == NULL)
{
return { CTL_ERROR_CON, 0, 0 };
}
//
// Parse the buffer into each individual command attribute
// Convert each individual command attribute into a tuple
//
memcpy(&ControlCode, Buffer, sizeof(ControlCode));
memcpy(&CommandParamOne, Buffer + sizeof(ControlCode), sizeof(CommandParamOne));
memcpy(&CommandParamTwo, Buffer + sizeof(ControlCode) + sizeof(CommandParamOne), sizeof(CommandParamTwo));
std::tuple<BYTE, DWORD_PTR, DWORD_PTR> Command(ControlCode, CommandParamOne, CommandParamTwo);
return Command;
}
void dio::Client::SendString(std::string Data)
{
send(ClientSocket, Data.c_str(), Data.size(), 0);
}
| 23.314394
| 120
| 0.740374
|
johnsonjason
|
93bf148cd21c563abccc25de1deed48e7822c07d
| 1,142
|
cpp
|
C++
|
gui/shapes/Line.cpp
|
TrapGameStudio/MouseTraps
|
1160f8b6ef865b180f418bd6d83f40d59d938130
|
[
"MIT"
] | null | null | null |
gui/shapes/Line.cpp
|
TrapGameStudio/MouseTraps
|
1160f8b6ef865b180f418bd6d83f40d59d938130
|
[
"MIT"
] | null | null | null |
gui/shapes/Line.cpp
|
TrapGameStudio/MouseTraps
|
1160f8b6ef865b180f418bd6d83f40d59d938130
|
[
"MIT"
] | 1
|
2020-04-19T23:20:25.000Z
|
2020-04-19T23:20:25.000Z
|
#include "Line.h"
/// <summary>
/// Construct a line from 2 Points.
/// </summary>
/// <param name="p1">point 1</param>
/// <param name="p2">point 2</param>
Line::Line(Point* p1, Point* p2) {
this->p1 = p1;
this->p2 = p2;
}
/// <summary>
/// Construct a line from the coordinate of 2 points.
/// </summary>
/// <param name="x1">x coordinate of the first point</param>
/// <param name="y1">y coordinate of the first point</param>
/// <param name="x2">x coordinate of the second point</param>
/// <param name="y2">y coordinate of the second point</param>
Line::Line(float x1, float y1, float x2, float y2) {
p1 = new Point(x1, y1);
p2 = new Point(x2, y2);
}
/// <summary>
/// Get the length of the line.
/// </summary>
/// <returns>the length</returns>
float Line::length() {
return p1->getDistanceTo(p2);
}
int Line::compareTo(const Line* l) const {
float diff = this->p1->getDistanceSquareTo(this->p2) - l->p1->getDistanceSquareTo(l->p2);
if (diff == 0) {
return 0;
} else if (diff > 0) {
return 1;
} else {
return -1;
}
}
Line::~Line() {
delete p1;
delete p2;
}
| 22.84
| 93
| 0.595447
|
TrapGameStudio
|
93bf946d7e2beedad2beb2e86aceadfcfc7eaa1d
| 1,385
|
cpp
|
C++
|
tutorial/more_basics/Expressions.cpp
|
luanics/cpp-illustrated
|
6049de2119a53d656a63b65d9441e680355ef196
|
[
"MIT"
] | null | null | null |
tutorial/more_basics/Expressions.cpp
|
luanics/cpp-illustrated
|
6049de2119a53d656a63b65d9441e680355ef196
|
[
"MIT"
] | null | null | null |
tutorial/more_basics/Expressions.cpp
|
luanics/cpp-illustrated
|
6049de2119a53d656a63b65d9441e680355ef196
|
[
"MIT"
] | null | null | null |
#include "luanics/testing/Tutorial.hpp"
#include <type_traits>
BEGIN_CHAPTER(Expressions)
// As a reminder...
// Decltype
//
// X (input) -> decltype(X) (output)
// =================================================
// identifier of type T -> T
// -------------------------------------------------
// xvalue expression of type T -> T&&
// lvalue expression of type T -> T&
// prvalue expression of type T -> T
// =================================================
SECTION(Decltype) {
int x = 1;
int const y = 2;
int const & z = x;
// From Introspection.cpp: Variable names as identifiers
EXPECT_TRUE((std::is_same<FIX(bool), decltype(x)>::value));
EXPECT_TRUE((std::is_same<FIX(bool), decltype(y)>::value));
EXPECT_TRUE((std::is_same<FIX(bool), decltype(z)>::value));
// Variable names as expressions
EXPECT_TRUE((std::is_same<FIX(bool), decltype((x))>::value));
EXPECT_TRUE((std::is_same<FIX(bool), decltype((y))>::value));
EXPECT_TRUE((std::is_same<FIX(bool), decltype((z))>::value));
// Other expressions
EXPECT_TRUE((std::is_same<FIX(bool), decltype(std::move(x))>::value));
EXPECT_TRUE((std::is_same<FIX(bool), decltype(x + x)>::value));
}
SECTION(Literals) {
// What is the type of a literal expression? Note that it is NOT const
EXPECT_TRUE((std::is_same<FIX(int const), decltype(4)>::value));
}
END_CHAPTER(Expressions)
| 31.477273
| 71
| 0.587004
|
luanics
|
93c1749c635261908f933ed879fa893a9326b5b1
| 1,539
|
cpp
|
C++
|
apps/opencs/model/world/idtableproxymodel.cpp
|
Bodillium/openmw
|
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
|
[
"Unlicense"
] | null | null | null |
apps/opencs/model/world/idtableproxymodel.cpp
|
Bodillium/openmw
|
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
|
[
"Unlicense"
] | null | null | null |
apps/opencs/model/world/idtableproxymodel.cpp
|
Bodillium/openmw
|
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
|
[
"Unlicense"
] | null | null | null |
#include "idtableproxymodel.hpp"
#include <vector>
#include "idtablebase.hpp"
void CSMWorld::IdTableProxyModel::updateColumnMap()
{
mColumnMap.clear();
if (mFilter)
{
std::vector<int> columns = mFilter->getReferencedColumns();
const IdTableBase& table = dynamic_cast<const IdTableBase&> (*sourceModel());
for (std::vector<int>::const_iterator iter (columns.begin()); iter!=columns.end(); ++iter)
mColumnMap.insert (std::make_pair (*iter,
table.searchColumnIndex (static_cast<CSMWorld::Columns::ColumnId> (*iter))));
}
}
bool CSMWorld::IdTableProxyModel::filterAcceptsRow (int sourceRow, const QModelIndex& sourceParent)
const
{
if (!mFilter)
return true;
return mFilter->test (
dynamic_cast<IdTableBase&> (*sourceModel()), sourceRow, mColumnMap);
}
CSMWorld::IdTableProxyModel::IdTableProxyModel (QObject *parent)
: QSortFilterProxyModel (parent)
{
setSortCaseSensitivity (Qt::CaseInsensitive);
}
QModelIndex CSMWorld::IdTableProxyModel::getModelIndex (const std::string& id, int column) const
{
return mapFromSource (dynamic_cast<IdTableBase&> (*sourceModel()).getModelIndex (id, column));
}
void CSMWorld::IdTableProxyModel::setFilter (const boost::shared_ptr<CSMFilter::Node>& filter)
{
mFilter = filter;
updateColumnMap();
invalidateFilter();
}
bool CSMWorld::IdTableProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
return QSortFilterProxyModel::lessThan(left, right);
}
| 27.482143
| 99
| 0.708902
|
Bodillium
|
93c3aaaf2f479fd8e17c86dc5e96d16e699a4d43
| 1,197
|
cpp
|
C++
|
Source/Windows/GithubIssuesWindow.cpp
|
humdingerb/Issues
|
115ac2c3bc04e2f967fc884fa3fd7eb46aea6bbf
|
[
"MIT"
] | null | null | null |
Source/Windows/GithubIssuesWindow.cpp
|
humdingerb/Issues
|
115ac2c3bc04e2f967fc884fa3fd7eb46aea6bbf
|
[
"MIT"
] | null | null | null |
Source/Windows/GithubIssuesWindow.cpp
|
humdingerb/Issues
|
115ac2c3bc04e2f967fc884fa3fd7eb46aea6bbf
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2015 Your Name <your@email.address>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "GithubIssuesWindow.h"
#include "GithubRepository.h"
#include "Constants.h"
#include "IssuesContainerView.h"
#include <interface/MenuBar.h>
#include <interface/MenuItem.h>
#include <interface/StringItem.h>
#include <interface/GroupLayout.h>
#include <interface/LayoutBuilder.h>
#include <posix/stdio.h>
GithubIssuesWindow::GithubIssuesWindow(GithubRepository *repository)
:BWindow(BRect(0,0,1,1), "Issues", B_TITLED_WINDOW, B_FRAME_EVENTS | B_AUTO_UPDATE_SIZE_LIMITS)
,fRepository(repository)
,fIssuesContainerView(NULL)
{
SetTitle(fRepository->name.String());
SetupViews();
CenterOnScreen();
}
GithubIssuesWindow::~GithubIssuesWindow()
{
}
void
GithubIssuesWindow::SetupViews()
{
fIssuesContainerView = new IssuesContainerView(fRepository->name, fRepository->owner);
fIssuesContainerView->SetExplicitMinSize(BSize(380, B_SIZE_UNSET));
fIssuesContainerView->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
SetLayout(new BGroupLayout(B_VERTICAL));
BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
.Add(fIssuesContainerView);
}
| 25.468085
| 96
| 0.785297
|
humdingerb
|
93c3ea338ec81545bc85c39ee99a047e03304c99
| 4,013
|
cpp
|
C++
|
test/separator_test.cpp
|
thm-mni-ii/sea
|
3d3f63c3d17ab91f0aaada3c4315ba98367a3460
|
[
"MIT"
] | 17
|
2019-01-03T11:17:31.000Z
|
2021-10-31T19:19:41.000Z
|
test/separator_test.cpp
|
thm-mni-ii/sea
|
3d3f63c3d17ab91f0aaada3c4315ba98367a3460
|
[
"MIT"
] | 106
|
2018-03-03T16:37:17.000Z
|
2020-08-31T09:24:52.000Z
|
test/separator_test.cpp
|
thm-mni-ii/sea
|
3d3f63c3d17ab91f0aaada3c4315ba98367a3460
|
[
"MIT"
] | 4
|
2018-05-21T13:30:01.000Z
|
2019-06-12T07:43:43.000Z
|
#include <sealib/flow/separator.h>
#include <gtest/gtest.h>
#include <sealib/iterator/dfs.h>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <sealib/collection/bitset.h>
#include <sealib/graph/graphcreator.h>
namespace Sealib {
static uint64_t n = 50;
static uint64_t deg = 4;
TEST(SeparatorTest, VSeparator) {
Bitset<> s = Bitset<>(n);
Bitset<> t = Bitset<>(n);
UndirectedGraph g = GraphCreator::kRegular(n, deg);
for (uint64_t i = 0; i < 5; i++) {
s.insert(i, true);
}
// finding 5 separate vertices from all s vertices
uint64_t nt = 5;
for (uint64_t i = 5; i < n; i++) {
bool align = false;
for (uint64_t j = 0; j < 5; j++) {
for (uint64_t k = 0; k < g.deg(j); k++) {
if (g.head(j, k) == i) align = true;
}
}
if (!align && nt > 0) {
t.insert(i, true);
nt--;
} else {
t.insert(i, false);
}
}
Bitset<> vs = Bitset<>(n);
vs = Separator::standardVSeparate(s, t, g, 50, DFS::getStandardDFSIterator);
// erase connections from other vertices to vertices in vs
for (uint64_t i = 0; i < n; i++) {
if (vs.get(i)) {
for (uint64_t j = 0; j < g.getNode(i).getDegree(); j++) {
g.getNode(g.getNode(i).getAdj()[j].first)
.getAdj()[g.getNode(i).getAdj()[j].second]
.first = g.getNode(i).getAdj()[j].first;
g.getNode(g.getNode(i).getAdj()[j].first)
.getAdj()[g.getNode(i).getAdj()[j].second]
.second = g.getNode(i).getAdj()[j].second;
}
}
}
// searching t vertices starting at all vertices in s
for (uint64_t i = 0; i < n; i++) {
if (s.get(i)) {
Iterator<UserCall> *iter = DFS::getStandardDFSIterator(g, i);
UserCall x = iter->next();
while (x.type != UserCall::postexplore || x.u != i) {
switch (x.type) {
case UserCall::preexplore:
if (t.get(x.u)) FAIL();
break;
}
x = iter->next();
}
free(iter);
}
}
SUCCEED();
}
TEST(SeparatorTest, ESeparator) {
Bitset<> s = Bitset<>(n);
Bitset<> t = Bitset<>(n);
UndirectedGraph g = GraphCreator::kRegular(n, deg);
for (uint64_t i = 0; i < 5; i++) {
s.insert(i, true);
}
// finding 5 separate vertices from all s vertices
uint64_t nt = 5;
for (uint64_t i = 5; i < n; i++) {
bool align = false;
for (uint64_t j = 0; j < 5; j++) {
for (uint64_t k = 0; k < g.deg(j); k++) {
if (g.head(j, k) == i) align = true;
}
}
if (!align && nt > 0) {
t.insert(i, true);
nt--;
} else {
t.insert(i, false);
}
}
std::vector<std::pair<uint64_t, uint64_t>> es;
es = Separator::standardESeparate(s, t, g, 50, DFS::getStandardDFSIterator);
// erase edges (make u = k)
for (uint64_t i = 0; i < es.size(); i++) {
for (uint64_t j = 0; j < g.getNode(es[i].first).getDegree(); j++) {
if (g.head(es[i].first, j) == es[i].second) {
g.getNode(es[i].first).getAdj()[j].first = es[i].first;
}
}
}
// searching t vertices starting at all vertices in s
for (uint64_t i = 0; i < n; i++) {
if (s.get(i)) {
Iterator<UserCall> *iter = DFS::getStandardDFSIterator(g, i);
UserCall x = iter->next();
while (x.type != UserCall::postexplore || x.u != i) {
switch (x.type) {
case UserCall::preexplore:
if (t.get(x.u)) FAIL();
break;
}
x = iter->next();
}
free(iter);
}
}
SUCCEED();
}
} // namespace Sealib
| 31.108527
| 80
| 0.468727
|
thm-mni-ii
|
93c68bb20cff1fd86d67754871a90d0445784680
| 1,826
|
cpp
|
C++
|
Common/MapGuideCommon/Services/RenderingService.cpp
|
achilex/MgDev
|
f7baf680a88d37659af32ee72b9a2046910b00d8
|
[
"PHP-3.0"
] | 2
|
2017-04-19T01:38:30.000Z
|
2020-07-31T03:05:32.000Z
|
Common/MapGuideCommon/Services/RenderingService.cpp
|
achilex/MgDev
|
f7baf680a88d37659af32ee72b9a2046910b00d8
|
[
"PHP-3.0"
] | null | null | null |
Common/MapGuideCommon/Services/RenderingService.cpp
|
achilex/MgDev
|
f7baf680a88d37659af32ee72b9a2046910b00d8
|
[
"PHP-3.0"
] | 1
|
2021-12-29T10:46:12.000Z
|
2021-12-29T10:46:12.000Z
|
//
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// 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 St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "MapGuideCommon.h"
//////////////////////////////////////////////////////////////////
/// <summary>
/// Default Constructor
/// </summary>
MgRenderingService::MgRenderingService() : MgService()
{
}
/////////////////////////////////////////////////////////////////
/// <summary>
/// Get the class Id
/// </summary>
/// <returns>
/// The integer value
/// </returns>
INT32 MgRenderingService::GetClassId()
{
return m_cls_id;
}
//////////////////////////////////////////////////////////////////
/// <summary>
/// Dispose this object
/// </summary>
/// <returns>
/// Nothing
/// </returns>
void MgRenderingService::Dispose()
{
delete this;
}
MgBatchPropertyCollection* MgRenderingService::QueryFeatureProperties(
MgMap* map,
MgStringCollection* layerNames,
MgGeometry* filterGeometry,
INT32 selectionVariant,
CREFSTRING featureFilter,
INT32 maxFeatures,
INT32 layerAttributeFilter,
bool bIncludeFeatureBBOX)
{
throw new MgNotImplementedException(L"MgRenderingService.QueryFeatureProperties", __LINE__, __WFILE__, NULL, L"", NULL);
}
| 28.984127
| 124
| 0.640745
|
achilex
|
93cbf0c0d0f9d7ce039184dff6cd44601027bdcf
| 2,818
|
cpp
|
C++
|
dependencies-include/nxogre/src/NxOgreSimpleShape.cpp
|
bach74/Lisa
|
6f79b909f734883cd05a0ccf8679199ae2e301cf
|
[
"MIT",
"Unlicense"
] | 2
|
2016-06-23T21:20:19.000Z
|
2020-03-25T15:01:07.000Z
|
dependencies-include/nxogre/src/NxOgreSimpleShape.cpp
|
bach74/Lisa
|
6f79b909f734883cd05a0ccf8679199ae2e301cf
|
[
"MIT",
"Unlicense"
] | null | null | null |
dependencies-include/nxogre/src/NxOgreSimpleShape.cpp
|
bach74/Lisa
|
6f79b909f734883cd05a0ccf8679199ae2e301cf
|
[
"MIT",
"Unlicense"
] | null | null | null |
/** \file NxOgreSimpleShape.cpp
* \see NxOgreSimpleShape.h
* \version 1.0-21
*
* \licence NxOgre a wrapper for the PhysX physics library.
* Copyright (C) 2005-8 Robin Southern of NxOgre.org http://www.nxogre.org
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "NxOgreStable.h"
#include "NxOgreSimpleShape.h"
#include "NxOgreHelpers.h"
#include "OgreStringVector.h"
namespace NxOgre {
//////////////////////////////////////////////////////////////////////////////////////
SimpleShape* SimpleShape::createFromString(const NxString& str) {
Ogre::StringVector strings = Ogre::StringUtil::split(str, ":", 2);
SimpleShape* shape = 0;
if (strings.size() != 2)
return shape;
Ogre::StringUtil::toLowerCase(strings[0]);
Ogre::StringUtil::trim(strings[0]);
Ogre::StringUtil::trim(strings[1]);
if (strings[0] == "cube" || strings[0] == "box") {
NxVec3 size(1,1,1);
size = NxFromString<NxVec3>(strings[1]);
shape = new SimpleBox(size);
}
return shape;
}
//////////////////////////////////////////////////////////////////////////////////////
SimpleBox* SimpleShape::getAsBox() {
return static_cast<SimpleBox*>(this);
}
//////////////////////////////////////////////////////////////////////////////////////
SimpleSphere* SimpleShape::getAsSphere() {
return static_cast<SimpleSphere*>(this);
}
//////////////////////////////////////////////////////////////////////////////////////
SimpleCapsule* SimpleShape::getAsCapsule() {
return static_cast<SimpleCapsule*>(this);
}
//////////////////////////////////////////////////////////////////////////////////////
SimpleConvex* SimpleShape::getAsConvex() {
return static_cast<SimpleConvex*>(this);
}
//////////////////////////////////////////////////////////////////////////////////////
SimplePlane* SimpleShape::getAsPlane() {
return static_cast<SimplePlane*>(this);
}
//////////////////////////////////////////////////////////////////////////////////////
}; //End of NxOgre namespace.
| 32.767442
| 87
| 0.529808
|
bach74
|