hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5df5dd9b588e787cca0c343de28b3cd84fa752b7
| 443
|
cpp
|
C++
|
lectures/week-02/calc.cpp
|
programming-workshop-2/course-material
|
898ca41343f49c0c96e380bd569631e2be339a8c
|
[
"MIT"
] | 1
|
2017-01-13T17:44:15.000Z
|
2017-01-13T17:44:15.000Z
|
lectures/week-02/calc.cpp
|
programming-workshop-2/course-material
|
898ca41343f49c0c96e380bd569631e2be339a8c
|
[
"MIT"
] | null | null | null |
lectures/week-02/calc.cpp
|
programming-workshop-2/course-material
|
898ca41343f49c0c96e380bd569631e2be339a8c
|
[
"MIT"
] | 2
|
2017-02-01T00:36:54.000Z
|
2017-03-14T16:01:00.000Z
|
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
char op;
double v1, v2, ans;
op = argv[1][0];
v1 = atof(argv[2]);
v2 = atof(argv[3]);
switch (op)
{
case '+': ans = v1 + v2; break;
case '-': ans = v1 - v2; break;
case '/': ans = v1 / v2; break;
case 'x': ans = v1 * v2; break;
}
cout << v1 << " " << op << " " << v2 << " = " << ans << endl;
return 0;
}
| 17.038462
| 63
| 0.48307
|
programming-workshop-2
|
5df70854e8ea8137f0b0b570138c80120d0cbee3
| 1,013
|
cpp
|
C++
|
cpp_kernels/port_width_widening/src/krnl_base.cpp
|
kapil2099/Vitis_Accel_Examples
|
05f898ab0fb808421316fad9fb7dd862d92eb623
|
[
"Apache-2.0"
] | null | null | null |
cpp_kernels/port_width_widening/src/krnl_base.cpp
|
kapil2099/Vitis_Accel_Examples
|
05f898ab0fb808421316fad9fb7dd862d92eb623
|
[
"Apache-2.0"
] | null | null | null |
cpp_kernels/port_width_widening/src/krnl_base.cpp
|
kapil2099/Vitis_Accel_Examples
|
05f898ab0fb808421316fad9fb7dd862d92eb623
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2020 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://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.
*/
#define size 512
extern "C" {
void krnl_base(const int *a, const int *b, int *res) {
int X_accum = 0;
int Y_accum = 0;
int i, j;
int X_aux[size];
int y_aux[size];
SUM_X:
for (i = 0; i < size; i++) {
X_accum += a[i];
X_aux[i] = X_accum;
}
SUM_Y:
for (i = 0; i < size; i++) {
Y_accum += b[i];
y_aux[i] = Y_accum;
}
MUL:
for (i = 0; i < size; i++) {
res[i] = X_aux[i] * y_aux[i];
}
}
}
| 22.021739
| 75
| 0.641658
|
kapil2099
|
5dfa47f3c8891104f93dbb311354153378ac67ab
| 1,844
|
cpp
|
C++
|
LayZ/src/math/vec2.cpp
|
AliKhudiyev/LayZ-Renderer-Engine
|
8e8943295f6f80a05c1ba2b7c7c1b3e51779a272
|
[
"MIT"
] | 11
|
2020-06-25T20:52:56.000Z
|
2021-04-27T05:37:22.000Z
|
LayZ/src/math/vec2.cpp
|
AliKhudiyev/LayZ-Renderer-Engine
|
8e8943295f6f80a05c1ba2b7c7c1b3e51779a272
|
[
"MIT"
] | 3
|
2020-06-29T14:21:52.000Z
|
2020-07-06T17:41:45.000Z
|
LayZ/src/math/vec2.cpp
|
AliKhudiyev/LayZ-Renderer-Engine
|
8e8943295f6f80a05c1ba2b7c7c1b3e51779a272
|
[
"MIT"
] | 2
|
2020-07-09T22:07:14.000Z
|
2021-02-05T22:04:57.000Z
|
#include "math/vec2.h"
#include <cassert>
namespace lyz { namespace math {
vec2::vec2(float x, float y) {
data[0] = x;
data[1] = y;
}
vec2::vec2(const float* fdata) {
data[0] = fdata[0];
data[1] = fdata[1];
}
vec2::vec2(const vec2& vec) {
data[0] = vec.data[0];
data[1] = vec.data[1];
}
vec2::~vec2() {
;
}
float vec2::dist(const vec2 & vec) const
{
return powf(powf(data[0] - vec.data[0], 2) + pow(data[1] - vec.data[1], 2), 0.5);
}
float vec2::dot(const vec2 & vec) const
{
return data[0] * vec.data[0] + data[1] * vec.data[1];
}
vec2 vec2::add(const vec2 & vec) const
{
return vec2(data[0] + vec.data[0], data[1] + vec.data[1]);
}
vec2 vec2::subtract(const vec2 & vec) const
{
return vec2(data[0] - vec.data[0], data[1] - vec.data[1]);
}
vec2 vec2::mult(const vec2& vec) const
{
return vec2(data[0] * vec.data[0], data[1] * vec.data[1]);
}
vec2 vec2::mult(float val) const
{
return vec2(val * data[0], val * data[1]);
}
float vec2::operator[](unsigned int i) const
{
assert(i < 2);
return data[i];
}
vec2 vec2::operator+(const vec2 & vec) const
{
return vec2();
}
vec2 vec2::operator-(const vec2 & vec) const
{
return add(vec);
}
vec2& vec2::operator+=(const vec2 & vec)
{
*this = *this + vec;
return *this;
}
vec2& vec2::operator-=(const vec2 & vec)
{
*this = *this - vec;
return *this;
}
vec2& vec2::operator=(const vec2& vec) {
data[0] = vec.data[0];
data[1] = vec.data[1];
return *this;
}
bool vec2::operator==(const vec2 & vec) const
{
return (data[0] == vec.data[0] && data[1] == vec.data[1]);
}
bool vec2::operator!=(const vec2 & vec) const
{
return !(*this == vec);
}
} }
std::ostream &operator<<(std::ostream &stream, const lyz::math::vec2 &v) {
stream << "(" << v[0] << ", " << v[1] << ")";
return stream;
}
| 17.730769
| 83
| 0.574837
|
AliKhudiyev
|
b9012a8282cdeded891a00442d30a674680ee591
| 1,041
|
cpp
|
C++
|
lib/LuaObject.cpp
|
indie-zen-plugins/ZLua
|
6fff6e889a27152ed85b0c0c0786e6b8706f2247
|
[
"MIT"
] | null | null | null |
lib/LuaObject.cpp
|
indie-zen-plugins/ZLua
|
6fff6e889a27152ed85b0c0c0786e6b8706f2247
|
[
"MIT"
] | null | null | null |
lib/LuaObject.cpp
|
indie-zen-plugins/ZLua
|
6fff6e889a27152ed85b0c0c0786e6b8706f2247
|
[
"MIT"
] | null | null | null |
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Lua plugin for Zen Scripting
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "LuaObject.hpp"
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace ZLua {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#if 0
LuaObject::LuaObject(PyObject* _pObj)
: m_pObj(_pObj)
{
}
#endif
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
LuaObject::~LuaObject()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#if 0
PyObject*
LuaObject::get()
{
return m_pObj;
}
#endif
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace ZLua
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 26.692308
| 81
| 0.225744
|
indie-zen-plugins
|
b90893dc93ae8e7389089097e352775b5ef4e2bc
| 19,599
|
cpp
|
C++
|
src/pronet/pro_net/pro_net.cpp
|
libpronet/libpronet
|
78f52fbe002767915553bdf58fb10453e63bf502
|
[
"Apache-2.0"
] | 35
|
2018-10-29T06:31:09.000Z
|
2022-03-21T08:13:39.000Z
|
src/pronet/pro_net/pro_net.cpp
|
libpronet/libpronet
|
78f52fbe002767915553bdf58fb10453e63bf502
|
[
"Apache-2.0"
] | null | null | null |
src/pronet/pro_net/pro_net.cpp
|
libpronet/libpronet
|
78f52fbe002767915553bdf58fb10453e63bf502
|
[
"Apache-2.0"
] | 11
|
2018-11-03T04:45:29.000Z
|
2021-11-23T06:09:20.000Z
|
/*
* Copyright (C) 2018-2019 Eric Tung <libpronet@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License"),
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of LibProNet (https://github.com/libpronet/libpronet)
*/
#include "pro_net.h"
#include "pro_acceptor.h"
#include "pro_connector.h"
#include "pro_mcast_transport.h"
#include "pro_service_host.h"
#include "pro_service_hub.h"
#include "pro_ssl_handshaker.h"
#include "pro_ssl_transport.h"
#include "pro_tcp_handshaker.h"
#include "pro_tcp_transport.h"
#include "pro_tp_reactor_task.h"
#include "pro_udp_transport.h"
#include "../pro_util/pro_bsd_wrapper.h"
#include "../pro_util/pro_version.h"
#include "../pro_util/pro_z.h"
#include <cassert>
#include <cstddef>
#if defined(__cplusplus)
extern "C" {
#endif
/////////////////////////////////////////////////////////////////////////////
////
extern
void
PRO_CALLTYPE
ProSslInit();
/////////////////////////////////////////////////////////////////////////////
////
PRO_NET_API
void
PRO_CALLTYPE
ProNetInit()
{
static bool s_flag = false;
if (s_flag)
{
return;
}
s_flag = true;
pbsd_startup();
ProSslInit();
}
PRO_NET_API
void
PRO_CALLTYPE
ProNetVersion(unsigned char* major, /* = NULL */
unsigned char* minor, /* = NULL */
unsigned char* patch) /* = NULL */
{
if (major != NULL)
{
*major = PRO_VER_MAJOR;
}
if (minor != NULL)
{
*minor = PRO_VER_MINOR;
}
if (patch != NULL)
{
*patch = PRO_VER_PATCH;
}
}
PRO_NET_API
IProReactor*
PRO_CALLTYPE
ProCreateReactor(unsigned long ioThreadCount,
long ioThreadPriority) /* = 0 */
{
ProNetInit();
CProTpReactorTask* const reactorTask = new CProTpReactorTask;
if (!reactorTask->Start(ioThreadCount, ioThreadPriority))
{
delete reactorTask;
return (NULL);
}
return (reactorTask);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteReactor(IProReactor* reactor)
{
if (reactor == NULL)
{
return;
}
CProTpReactorTask* const p = (CProTpReactorTask*)reactor;
p->Stop();
delete p;
}
PRO_NET_API
IProAcceptor*
PRO_CALLTYPE
ProCreateAcceptor(IProAcceptorObserver* observer,
IProReactor* reactor,
const char* localIp, /* = NULL */
unsigned short localPort) /* = 0 */
{
ProNetInit();
CProAcceptor* const acceptor = CProAcceptor::CreateInstance(false);
if (acceptor == NULL)
{
return (NULL);
}
if (!acceptor->Init(
observer, (CProTpReactorTask*)reactor, localIp, localPort, 0))
{
acceptor->Release();
return (NULL);
}
return ((IProAcceptor*)acceptor);
}
PRO_NET_API
IProAcceptor*
PRO_CALLTYPE
ProCreateAcceptorEx(IProAcceptorObserver* observer,
IProReactor* reactor,
const char* localIp, /* = NULL */
unsigned short localPort, /* = 0 */
unsigned long timeoutInSeconds) /* = 0 */
{
ProNetInit();
CProAcceptor* const acceptor = CProAcceptor::CreateInstance(true);
if (acceptor == NULL)
{
return (NULL);
}
if (!acceptor->Init(observer, (CProTpReactorTask*)reactor,
localIp, localPort, timeoutInSeconds))
{
acceptor->Release();
return (NULL);
}
return ((IProAcceptor*)acceptor);
}
PRO_NET_API
unsigned short
PRO_CALLTYPE
ProGetAcceptorPort(IProAcceptor* acceptor)
{
assert(acceptor != NULL);
if (acceptor == NULL)
{
return (0);
}
CProAcceptor* const p = (CProAcceptor*)acceptor;
return (p->GetLocalPort());
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteAcceptor(IProAcceptor* acceptor)
{
if (acceptor == NULL)
{
return;
}
CProAcceptor* const p = (CProAcceptor*)acceptor;
p->Fini();
p->Release();
}
PRO_NET_API
IProConnector*
PRO_CALLTYPE
ProCreateConnector(bool enableUnixSocket,
IProConnectorObserver* observer,
IProReactor* reactor,
const char* remoteIp,
unsigned short remotePort,
const char* localBindIp, /* = NULL */
unsigned long timeoutInSeconds) /* = 0 */
{
ProNetInit();
CProConnector* const connector =
CProConnector::CreateInstance(enableUnixSocket, false, 0, 0);
if (connector == NULL)
{
return (NULL);
}
if (!connector->Init(observer, (CProTpReactorTask*)reactor,
remoteIp, remotePort, localBindIp, timeoutInSeconds))
{
connector->Release();
return (NULL);
}
return ((IProConnector*)connector);
}
PRO_NET_API
IProConnector*
PRO_CALLTYPE
ProCreateConnectorEx(bool enableUnixSocket,
unsigned char serviceId,
unsigned char serviceOpt,
IProConnectorObserver* observer,
IProReactor* reactor,
const char* remoteIp,
unsigned short remotePort,
const char* localBindIp, /* = NULL */
unsigned long timeoutInSeconds) /* = 0 */
{
ProNetInit();
CProConnector* const connector = CProConnector::CreateInstance(
enableUnixSocket, true, serviceId, serviceOpt);
if (connector == NULL)
{
return (NULL);
}
if (!connector->Init(observer, (CProTpReactorTask*)reactor,
remoteIp, remotePort, localBindIp, timeoutInSeconds))
{
connector->Release();
return (NULL);
}
return ((IProConnector*)connector);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteConnector(IProConnector* connector)
{
if (connector == NULL)
{
return;
}
CProConnector* const p = (CProConnector*)connector;
p->Fini();
p->Release();
}
PRO_NET_API
IProTcpHandshaker*
PRO_CALLTYPE
ProCreateTcpHandshaker(IProTcpHandshakerObserver* observer,
IProReactor* reactor,
PRO_INT64 sockId,
bool unixSocket,
const void* sendData, /* = NULL */
size_t sendDataSize, /* = 0 */
size_t recvDataSize, /* = 0 */
bool recvFirst, /* = false */
unsigned long timeoutInSeconds) /* = 0 */
{
ProNetInit();
CProTcpHandshaker* const handshaker = CProTcpHandshaker::CreateInstance();
if (handshaker == NULL)
{
return (NULL);
}
if (!handshaker->Init(observer, (CProTpReactorTask*)reactor,
sockId, unixSocket, sendData, sendDataSize, recvDataSize,
recvFirst, timeoutInSeconds))
{
handshaker->Release();
return (NULL);
}
return ((IProTcpHandshaker*)handshaker);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteTcpHandshaker(IProTcpHandshaker* handshaker)
{
if (handshaker == NULL)
{
return;
}
CProTcpHandshaker* const p = (CProTcpHandshaker*)handshaker;
p->Fini();
p->Release();
}
PRO_NET_API
IProSslHandshaker*
PRO_CALLTYPE
ProCreateSslHandshaker(IProSslHandshakerObserver* observer,
IProReactor* reactor,
PRO_SSL_CTX* ctx,
PRO_INT64 sockId,
bool unixSocket,
const void* sendData, /* = NULL */
size_t sendDataSize, /* = 0 */
size_t recvDataSize, /* = 0 */
bool recvFirst, /* = false */
unsigned long timeoutInSeconds) /* = 0 */
{
ProNetInit();
CProSslHandshaker* const handshaker = CProSslHandshaker::CreateInstance();
if (handshaker == NULL)
{
return (NULL);
}
if (!handshaker->Init(observer, (CProTpReactorTask*)reactor,
ctx, sockId, unixSocket, sendData, sendDataSize, recvDataSize,
recvFirst, timeoutInSeconds))
{
handshaker->Release();
return (NULL);
}
return ((IProSslHandshaker*)handshaker);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteSslHandshaker(IProSslHandshaker* handshaker)
{
if (handshaker == NULL)
{
return;
}
CProSslHandshaker* const p = (CProSslHandshaker*)handshaker;
p->Fini();
p->Release();
}
PRO_NET_API
IProTransport*
PRO_CALLTYPE
ProCreateTcpTransport(IProTransportObserver* observer,
IProReactor* reactor,
PRO_INT64 sockId,
bool unixSocket,
size_t sockBufSizeRecv, /* = 0 */
size_t sockBufSizeSend, /* = 0 */
size_t recvPoolSize, /* = 0 */
bool suspendRecv) /* = false */
{
ProNetInit();
CProTcpTransport* const trans =
CProTcpTransport::CreateInstance(false, recvPoolSize);
if (trans == NULL)
{
return (NULL);
}
if (!trans->Init(observer, (CProTpReactorTask*)reactor, sockId,
unixSocket, sockBufSizeRecv, sockBufSizeSend, suspendRecv))
{
trans->Release();
return (NULL);
}
return (trans);
}
PRO_NET_API
IProTransport*
PRO_CALLTYPE
ProCreateUdpTransport(IProTransportObserver* observer,
IProReactor* reactor,
const char* localIp, /* = NULL */
unsigned short localPort, /* = 0 */
size_t sockBufSizeRecv, /* = 0 */
size_t sockBufSizeSend, /* = 0 */
size_t recvPoolSize, /* = 0 */
const char* defaultRemoteIp, /* = NULL */
unsigned short defaultRemotePort) /* = 0 */
{
ProNetInit();
CProUdpTransport* const trans =
CProUdpTransport::CreateInstance(recvPoolSize);
if (trans == NULL)
{
return (NULL);
}
if (!trans->Init(observer, (CProTpReactorTask*)reactor,
localIp, localPort, defaultRemoteIp, defaultRemotePort,
sockBufSizeRecv, sockBufSizeSend))
{
trans->Release();
return (NULL);
}
return (trans);
}
PRO_NET_API
IProTransport*
PRO_CALLTYPE
ProCreateMcastTransport(IProTransportObserver* observer,
IProReactor* reactor,
const char* mcastIp,
unsigned short mcastPort, /* = 0 */
const char* localBindIp, /* = NULL */
size_t sockBufSizeRecv, /* = 0 */
size_t sockBufSizeSend, /* = 0 */
size_t recvPoolSize) /* = 0 */
{
ProNetInit();
CProMcastTransport* const trans =
CProMcastTransport::CreateInstance(recvPoolSize);
if (trans == NULL)
{
return (NULL);
}
if (!trans->Init(observer, (CProTpReactorTask*)reactor,
mcastIp, mcastPort, localBindIp, sockBufSizeRecv, sockBufSizeSend))
{
trans->Release();
return (NULL);
}
return (trans);
}
PRO_NET_API
IProTransport*
PRO_CALLTYPE
ProCreateSslTransport(IProTransportObserver* observer,
IProReactor* reactor,
PRO_SSL_CTX* ctx,
PRO_INT64 sockId,
bool unixSocket,
size_t sockBufSizeRecv, /* = 0 */
size_t sockBufSizeSend, /* = 0 */
size_t recvPoolSize, /* = 0 */
bool suspendRecv) /* = false */
{
ProNetInit();
CProSslTransport* const trans =
CProSslTransport::CreateInstance(recvPoolSize);
if (trans == NULL)
{
return (NULL);
}
if (!trans->Init(observer, (CProTpReactorTask*)reactor, ctx, sockId,
unixSocket, sockBufSizeRecv, sockBufSizeSend, suspendRecv))
{
trans->Release();
return (NULL);
}
return (trans);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteTransport(IProTransport* trans)
{
if (trans == NULL)
{
return;
}
const PRO_TRANS_TYPE type = trans->GetType();
if (type == PRO_TRANS_TCP)
{
CProTcpTransport* const p = (CProTcpTransport*)trans;
p->Fini();
p->Release();
}
else if (type == PRO_TRANS_UDP)
{
CProUdpTransport* const p = (CProUdpTransport*)trans;
p->Fini();
p->Release();
}
else if (type == PRO_TRANS_MCAST)
{
CProMcastTransport* const p = (CProMcastTransport*)trans;
p->Fini();
p->Release();
}
else if (type == PRO_TRANS_SSL)
{
CProSslTransport* const p = (CProSslTransport*)trans;
p->Fini();
p->Release();
}
else
{
}
}
PRO_NET_API
IProServiceHub*
PRO_CALLTYPE
ProCreateServiceHub(IProReactor* reactor,
unsigned short servicePort,
bool enableLoadBalance) /* = false */
{
ProNetInit();
CProServiceHub* const hub = CProServiceHub::CreateInstance(
false, /* enableServiceExt is false */
enableLoadBalance
);
if (hub == NULL)
{
return (NULL);
}
if (!hub->Init(reactor, servicePort, 0))
{
hub->Release();
return (NULL);
}
return ((IProServiceHub*)hub);
}
PRO_NET_API
IProServiceHub*
PRO_CALLTYPE
ProCreateServiceHubEx(IProReactor* reactor,
unsigned short servicePort,
bool enableLoadBalance, /* = false */
unsigned long timeoutInSeconds) /* = 0 */
{
ProNetInit();
CProServiceHub* const hub = CProServiceHub::CreateInstance(
true, /* enableServiceExt is true */
enableLoadBalance
);
if (hub == NULL)
{
return (NULL);
}
if (!hub->Init(reactor, servicePort, timeoutInSeconds))
{
hub->Release();
return (NULL);
}
return ((IProServiceHub*)hub);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteServiceHub(IProServiceHub* hub)
{
if (hub == NULL)
{
return;
}
CProServiceHub* const p = (CProServiceHub*)hub;
p->Fini();
p->Release();
}
PRO_NET_API
IProServiceHost*
PRO_CALLTYPE
ProCreateServiceHost(IProServiceHostObserver* observer,
IProReactor* reactor,
unsigned short servicePort)
{
ProNetInit();
CProServiceHost* const host = CProServiceHost::CreateInstance(0); /* serviceId is 0 */
if (host == NULL)
{
return (NULL);
}
if (!host->Init(observer, reactor, servicePort))
{
host->Release();
return (NULL);
}
return ((IProServiceHost*)host);
}
PRO_NET_API
IProServiceHost*
PRO_CALLTYPE
ProCreateServiceHostEx(IProServiceHostObserver* observer,
IProReactor* reactor,
unsigned short servicePort,
unsigned char serviceId)
{
ProNetInit();
assert(serviceId > 0);
if (serviceId == 0)
{
return (NULL);
}
CProServiceHost* const host = CProServiceHost::CreateInstance(serviceId);
if (host == NULL)
{
return (NULL);
}
if (!host->Init(observer, reactor, servicePort))
{
host->Release();
return (NULL);
}
return ((IProServiceHost*)host);
}
PRO_NET_API
void
PRO_CALLTYPE
ProDeleteServiceHost(IProServiceHost* host)
{
if (host == NULL)
{
return;
}
CProServiceHost* const p = (CProServiceHost*)host;
p->Fini();
p->Release();
}
PRO_NET_API
PRO_INT64
PRO_CALLTYPE
ProOpenTcpSockId(const char* localIp, /* = NULL */
unsigned short localPort)
{
ProNetInit();
assert(localPort > 0);
if (localPort == 0)
{
return (-1);
}
const char* const anyIp = "0.0.0.0";
if (localIp == NULL || localIp[0] == '\0')
{
localIp = anyIp;
}
pbsd_sockaddr_in localAddr;
memset(&localAddr, 0, sizeof(pbsd_sockaddr_in));
localAddr.sin_family = AF_INET;
localAddr.sin_port = pbsd_hton16(localPort);
localAddr.sin_addr.s_addr = pbsd_inet_aton(localIp);
if (localAddr.sin_addr.s_addr == (PRO_UINT32)-1)
{
return (-1);
}
PRO_INT64 sockId = pbsd_socket(AF_INET, SOCK_STREAM, 0);
if (sockId == -1)
{
return (-1);
}
if (pbsd_bind(sockId, &localAddr, false) != 0)
{
ProCloseSockId(sockId);
sockId = -1;
}
return (sockId);
}
PRO_NET_API
PRO_INT64
PRO_CALLTYPE
ProOpenUdpSockId(const char* localIp, /* = NULL */
unsigned short localPort)
{
ProNetInit();
assert(localPort > 0);
if (localPort == 0)
{
return (-1);
}
const char* const anyIp = "0.0.0.0";
if (localIp == NULL || localIp[0] == '\0')
{
localIp = anyIp;
}
pbsd_sockaddr_in localAddr;
memset(&localAddr, 0, sizeof(pbsd_sockaddr_in));
localAddr.sin_family = AF_INET;
localAddr.sin_port = pbsd_hton16(localPort);
localAddr.sin_addr.s_addr = pbsd_inet_aton(localIp);
if (localAddr.sin_addr.s_addr == (PRO_UINT32)-1)
{
return (-1);
}
PRO_INT64 sockId = pbsd_socket(AF_INET, SOCK_DGRAM, 0);
if (sockId == -1)
{
return (-1);
}
if (pbsd_bind(sockId, &localAddr, false) != 0)
{
ProCloseSockId(sockId);
sockId = -1;
}
return (sockId);
}
PRO_NET_API
void
PRO_CALLTYPE
ProCloseSockId(PRO_INT64 sockId,
bool linger) /* = false */
{
if (sockId == -1)
{
return;
}
ProDecServiceLoad(sockId); /* for load-balance */
pbsd_closesocket(sockId, linger);
}
/////////////////////////////////////////////////////////////////////////////
////
class CProNetDotCpp
{
public:
CProNetDotCpp()
{
ProNetInit();
}
};
static volatile CProNetDotCpp g_s_initiator;
/////////////////////////////////////////////////////////////////////////////
////
#if defined(__cplusplus)
} /* extern "C" */
#endif
| 23.641737
| 90
| 0.537987
|
libpronet
|
b90b75b2c2ee62d27dd11fdb8f49398f1df80d9b
| 65,944
|
cpp
|
C++
|
Samples/Win7Samples/netds/tapi/tapi3/cpp/tapirecv/Processing.cpp
|
windows-development/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 8
|
2017-04-30T17:38:27.000Z
|
2021-11-29T00:59:03.000Z
|
Samples/Win7Samples/netds/tapi/tapi3/cpp/tapirecv/Processing.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | null | null | null |
Samples/Win7Samples/netds/tapi/tapi3/cpp/tapirecv/Processing.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 2
|
2020-08-11T13:21:49.000Z
|
2021-09-01T10:41:51.000Z
|
/*
Copyright (c) 1999 - 2000 Microsoft Corporation
Module Name:
Processing.cpp
Abstract:
Implementation of the ITTAPIEventNotification interface. An application
must implement and register this interface in order to receive calls and
events related to calls. See TAPI documentation for more information on
this interface.
This file also contains a collection of functions related to event
processing
*/
#include "common.h"
#include "Processing.h"
#include "WorkerThread.h"
#include "AVIFileWriter.h"
//
// the name of the file we will save the incoming audio to
//
#define SZ_OUTPUTFILENAME "recording.wav"
//
// the worker thread for asycnhronous message processing
//
CWorkerThread g_WorkerThread;
///////////////////////////////////////////////////////////////////////////////
//
// ITTAPIEventNotification::Event
//
// the method on the tapi callback object that will be called
// when tapi notifies the application of an event
//
// this method should return as soon as possible, so we are not
// going to actually process the events here. Instead, we will post
// events to a worker thread for asynchronous processing.
//
// in a real life application that could be another thread, the
// application's main thread, or we could post events to a window.
//
///////////////////////////////////////////////////////////////////////////////
HRESULT STDMETHODCALLTYPE CTAPIEventNotification::Event(IN TAPI_EVENT TapiEvent,
IN IDispatch *pEvent)
{
LogMessage("CTAPIEventNotification::Event "
"posting message for asynchronous processing");
//
// AddRef the event so it doesn't go away after we return
//
pEvent->AddRef();
//
// Post a message to our own worker thread to be processed asynchronously
//
g_WorkerThread.PostMessage(WM_PRIVATETAPIEVENT,
(WPARAM) TapiEvent,
(LPARAM) pEvent);
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// GetTerminalFromStreamEvent
//
//
// given pCallMediaEvent, find the one and only terminal selected on its stream
//
// return the terminal and S_OK if success, error otherwise
//
///////////////////////////////////////////////////////////////////////////////
HRESULT GetTerminalFromStreamEvent(IN ITCallMediaEvent *pCallMediaEvent,
OUT ITTerminal **ppTerminal)
{
HRESULT hr = E_FAIL;
//
// don't return garbage
//
*ppTerminal = NULL;
//
// Get the stream for this event.
//
ITStream *pStream = NULL;
hr = pCallMediaEvent->get_Stream(&pStream);
if ( FAILED(hr) )
{
LogMessage("GetTerminalFromStreamEvent: "
"Failed to get stream from pCallMediaEvent hr = 0x%lx", hr);
return hr;
}
//
// Enumerate terminals on this stream.
//
IEnumTerminal *pEnumTerminal = NULL;
hr = pStream->EnumerateTerminals(&pEnumTerminal);
pStream->Release();
pStream = NULL;
if ( FAILED(hr) )
{
LogMessage("GetTerminalFromStreamEvent: "
"Failed to enumerate terminals hr = 0x%lx", hr);
return hr;
}
//
// we should have at most one terminal selected on the stream, so
// get the first terminal
//
ITTerminal *pTerminal = NULL;
hr = pEnumTerminal->Next(1, &pTerminal, NULL);
if ( hr != S_OK )
{
LogMessage("GetTerminalFromStreamEvent: "
"Failed to get a terminal from enumeration hr = 0x%lx", hr);
pEnumTerminal->Release();
pEnumTerminal = NULL;
return E_FAIL;
}
*ppTerminal = pTerminal;
pTerminal = NULL;
//
// we should not have any more terminals on this stream,
// double-check this.
//
hr = pEnumTerminal->Next(1, &pTerminal, NULL);
if (hr == S_OK)
{
LogError("GetTerminalFromStreamEvent: "
"more than one terminal on the stream!");
_ASSERTE(FALSE);
pTerminal->Release();
pTerminal = NULL;
}
pEnumTerminal->Release();
pEnumTerminal = NULL;
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// IsMessageForActiveCall
//
// return TRUE if the event received is for the currently active call
//
///////////////////////////////////////////////////////////////////////////////
BOOL IsMessageForActiveCall(IN ITCallStateEvent *pCallStateEvent)
{
EnterCriticalSection(&g_CurrentCallCritSection);
//
// if we don't have an active call we have not received call notification
// for a call that we own, so return FALSE
//
if (NULL == g_pCurrentCall)
{
LogMessage("IsMessageForActiveCall: no active call. return FALSE");
LeaveCriticalSection(&g_CurrentCallCritSection);
return FALSE;
}
//
// get the call corresponding to the event
//
ITCallInfo *pCallInfo = NULL;
HRESULT hr = pCallStateEvent->get_Call(&pCallInfo);
if (FAILED(hr))
{
LogError("IsMessageForActiveCall: failed to get call. "
"returning FALSE");
LeaveCriticalSection(&g_CurrentCallCritSection);
return FALSE;
}
//
// get IUnknown of the call from the event
//
IUnknown *pIncomingCallUnk = NULL;
hr = pCallInfo->QueryInterface(IID_IUnknown, (void**)&pIncomingCallUnk);
pCallInfo->Release();
pCallInfo = NULL;
if (FAILED(hr))
{
LogError("IsMessageForActiveCall: "
"failed to qi incoming call for IUnknown. returning FALSE");
LeaveCriticalSection(&g_CurrentCallCritSection);
return FALSE;
}
//
// get IUnknown of the call from the event
//
IUnknown *pCurrentCallUnk = NULL;
hr = g_pCurrentCall->QueryInterface(IID_IUnknown, (void**)&pCurrentCallUnk);
LeaveCriticalSection(&g_CurrentCallCritSection);
if (FAILED(hr))
{
LogError("IsMessageForActiveCall: "
"Failed to QI current call for IUnknown. returning FALSE.");
pIncomingCallUnk->Release();
pIncomingCallUnk = NULL;
return FALSE;
}
//
// compare IUnknowns of the current call and the event call
// if they are the same, this is the same call
//
BOOL bSameCall = FALSE;
if (pCurrentCallUnk == pIncomingCallUnk)
{
bSameCall = TRUE;
}
else
{
LogMessage("IsMessageForActiveCall: "
"current and event calls are different. returning FALSE.");
bSameCall = FALSE;
}
pCurrentCallUnk->Release();
pCurrentCallUnk = NULL;
pIncomingCallUnk->Release();
pIncomingCallUnk = NULL;
return bSameCall;
}
///////////////////////////////////////////////////////////////////////////////
//
// GetAddressFromCall
//
//
// return ITAddress of the address corresponding to the supplied
// ITBasicCallControl
//
///////////////////////////////////////////////////////////////////////////////
HRESULT GetAddressFromCall(IN ITBasicCallControl *pCallControl,
OUT ITAddress **ppAddress)
{
HRESULT hr = E_FAIL;
//
// don't return garbage
//
*ppAddress = NULL;
//
// get ITCallInfo so we can get the call's address
//
ITCallInfo *pCallInfo = NULL;
hr = pCallControl->QueryInterface(IID_ITCallInfo, (void**)&pCallInfo);
if (FAILED(hr))
{
LogError("GetAddressFromCall: "
"Failed to QI call for ITCallInfo");
return hr;
}
//
// get the call's address
//
ITAddress *pAddress = NULL;
hr = pCallInfo->get_Address(&pAddress);
pCallInfo->Release();
pCallInfo = NULL;
if (FAILED(hr))
{
LogError("GetAddressFromCall: failed to get address");
}
else
{
*ppAddress = pAddress;
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
// CreateRenderMediaStreamingTerminal
//
// create rendering media streaming terminal.
//
// if success, return the pointer to the terminal
// if failed, return NULL
//
///////////////////////////////////////////////////////////////////////////////
ITTerminal *CreateRenderMediaStreamingTerminal(IN ITBasicCallControl *pCallControl)
{
HRESULT hr = E_FAIL;
//
// get address from call
//
ITAddress *pAddress = NULL;
hr = GetAddressFromCall(pCallControl, &pAddress);
if (FAILED(hr))
{
LogError("CreateRenderMediaStreamingTerminal: failed to get address from call");
return NULL;
}
//
// get the terminal support interface from the address
//
ITTerminalSupport *pTerminalSupport = NULL;
hr = pAddress->QueryInterface( IID_ITTerminalSupport,
(void **)&pTerminalSupport );
pAddress->Release();
pAddress = NULL;
if (FAILED(hr))
{
LogError("CreateRenderMediaStreamingTerminal: "
"failed to QI pAddress for ITTerminalSupport");
return NULL;
}
//
// get string for the terminal's class id
//
WCHAR *pszTerminalClass = NULL;
hr = StringFromIID(CLSID_MediaStreamTerminal, &pszTerminalClass);
if (FAILED(hr))
{
LogError("CreateRenderMediaStreamingTerminal: "
"Failed to generate string from terminal's class id");
pTerminalSupport->Release();
pTerminalSupport = NULL;
return NULL;
}
//
// make bstr out of the class id
//
BSTR bstrTerminalClass = SysAllocString (pszTerminalClass);
//
// free the string returned by StringFromIID
//
CoTaskMemFree(pszTerminalClass);
pszTerminalClass = NULL;
//
// create media streaming terminal for rendering
//
ITTerminal *pTerminal = NULL;
hr = pTerminalSupport->CreateTerminal(bstrTerminalClass,
TAPIMEDIATYPE_AUDIO,
TD_RENDER,
&pTerminal);
//
// release resources no longer needed
//
SysFreeString(bstrTerminalClass);
bstrTerminalClass = NULL;
pTerminalSupport->Release();
pTerminalSupport = NULL;
if (FAILED(hr))
{
LogError("CreateRenderMediaStreamingTerminal: "
"failed to create media streaming terminal hr = 0x%lx", hr);
return NULL;
}
//
// successfully created media streaming terminal. return.
//
LogMessage("CreateRenderMediaStreamingTerminal: "
"Terminal created successfully");
return pTerminal;
}
///////////////////////////////////////////////////////////////////////////////
//
// SetAudioFormat
//
// tell media streaming terminal the audio format we would like
// to receive
//
///////////////////////////////////////////////////////////////////////////////
HRESULT SetAudioFormat(IN ITTerminal *pTerminal)
{
HRESULT hr = E_FAIL;
//
// get ITAMMediaFormat interface on the terminal
//
ITAMMediaFormat *pITMediaFormat = NULL;
hr = pTerminal->QueryInterface(IID_ITAMMediaFormat,
(void **)&pITMediaFormat);
if (FAILED(hr))
{
LogError("SetAudioFormat: failed to QI terminal for ITAMMediaFormat");
return hr;
}
//
// will ask media streaming terminal for audio in this format
//
WAVEFORMATEX WaveFormat;
ZeroMemory(&WaveFormat, sizeof(WAVEFORMATEX));
WaveFormat.wFormatTag = WAVE_FORMAT_PCM; // pcm
WaveFormat.nChannels = 1; // mono
WaveFormat.nSamplesPerSec = 8000; // 8 khz
WaveFormat.nAvgBytesPerSec = 16000; // 16000 bytes per sec
WaveFormat.nBlockAlign = 2; // 2 bytes per block
WaveFormat.wBitsPerSample = 16; // 16 bits per sample
WaveFormat.cbSize = 0; // no extra format-specific data
//
// configure the wave format we want
//
AM_MEDIA_TYPE MediaType;
MediaType.majortype = MEDIATYPE_Audio;
MediaType.subtype = MEDIASUBTYPE_PCM;
MediaType.bFixedSizeSamples = TRUE;
MediaType.bTemporalCompression = FALSE;
MediaType.lSampleSize = 0;
MediaType.formattype = FORMAT_WaveFormatEx;
MediaType.pUnk = NULL;
MediaType.cbFormat = sizeof(WAVEFORMATEX);
MediaType.pbFormat = (BYTE*)&WaveFormat;
//
// log the wave format we are setting on the terminal
//
LogMessage("SetAudioFormat: setting wave format on terminal. ");
LogFormat(&WaveFormat);
//
// set the format
//
hr = pITMediaFormat->put_MediaFormat(&MediaType);
if (FAILED(hr))
{
//
// try to see what format the terminal wanted
//
LogError("SetAudioFormat: failed to set format");
AM_MEDIA_TYPE *pMediaFormat = NULL;
HRESULT hr2 = pITMediaFormat->get_MediaFormat(&pMediaFormat);
if (SUCCEEDED(hr2))
{
if (pMediaFormat->formattype == FORMAT_WaveFormatEx)
{
//
// log the terminal's format
//
LogError("SetAudioFormat: terminal's format is");
LogFormat((WAVEFORMATEX*) pMediaFormat->pbFormat);
}
else
{
LogError("SetAudioFormat: "
"terminal's format is not WAVEFORMATEX");
}
//
// note: we are responsible for deallocating the format returned by
// get_MediaFormat
//
DeleteMediaType(pMediaFormat);
} // succeeded getting terminal's format
else
{
LogError("SetAudioFormat: failed to get terminal's format");
}
}
pITMediaFormat->Release();
pITMediaFormat = NULL;
LogError("SetAudioFormat: completed");
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
// SetAllocatorProperties
//
// suggest allocator properties to the terminal
//
///////////////////////////////////////////////////////////////////////////////
HRESULT SetAllocatorProperties(IN ITTerminal *pTerminal)
{
//
// different buffer sizes may produce different sound quality, depending
// on the underlying transport that is being used.
//
// this function illustrates how an app can control the number and size of
// buffers. A multiple of 30 ms (480 bytes at 16-bit 8 KHz PCM) is the most
// appropriate sample size for IP (especailly G.723.1).
//
// However, small buffers can cause poor audio quality on some voice boards.
//
// If this method is not called, the allocator properties suggested by the
// connecting filter will be used.
//
HRESULT hr = E_FAIL;
//
// get ITAllocator properties interface on the terminal
//
ITAllocatorProperties *pITAllocatorProperties = NULL;
hr = pTerminal->QueryInterface(IID_ITAllocatorProperties,
(void **)&pITAllocatorProperties);
if (FAILED(hr))
{
LogError("SetAllocatorProperties: "
"failed to QI terminal for ITAllocatorProperties");
return hr;
}
//
// configure allocator properties
//
// suggest the size and number of the samples for MST to pre-allocate.
//
ALLOCATOR_PROPERTIES AllocProps;
AllocProps.cBuffers = 5; // ask MST to allocate 5 buffers
AllocProps.cbBuffer = 4800; // 4800 bytes each
AllocProps.cbAlign = 1; // no need to align buffers
AllocProps.cbPrefix = 0; // no extra memory preceeding the actual data
hr = pITAllocatorProperties->SetAllocatorProperties(&AllocProps);
if (FAILED(hr))
{
LogError("SetAllocatorProperties: "
"failed to set allocator properties. hr = 0x%lx", hr);
pITAllocatorProperties->Release();
pITAllocatorProperties = NULL;
return hr;
}
//
// ask media streaming terminal to allocate buffers for us.
// TRUE is the default, so strictly speaking, we didn't have to call
// this method.
//
hr = pITAllocatorProperties->SetAllocateBuffers(TRUE);
pITAllocatorProperties->Release();
pITAllocatorProperties = NULL;
if (FAILED(hr))
{
LogError("SetAllocatorProperties: "
"failed to SetAllocateBuffers, hr = 0x%lx", hr);
return hr;
}
//
// succeeded setting allocator properties
//
LogMessage("SetAllocatorProperties: succeeded.");
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// SelectAndInitializeTerminal
//
//
// Set audio format and allocator properties on the terminal and
// select the terminal on the stream
//
///////////////////////////////////////////////////////////////////////////////
HRESULT SelectAndInitializeTerminal(IN ITTerminal *pRecordTerminal,
IN ITStream *pStream)
{
HRESULT hr = E_FAIL;
//
// set audio format on the created terminal
//
hr = SetAudioFormat(pRecordTerminal);
if (FAILED(hr))
{
//
// the terminal does not support the wave format we wanted.
// no big deal for the receiver, we'll just have to create the
// file in the format requested by MST.
//
LogMessage("CreateAndSelectMST: "
"Failed to set audio format on recording terminal. "
"Continuing");
}
//
// set allocator properties for this terminal
//
hr = SetAllocatorProperties(pRecordTerminal);
if (FAILED(hr))
{
//
// not a fatal error. our allocator props were rejected,
// but this does not necessarily mean streaming will fail.
//
LogError("CreateAndSelectMST: Failed to set "
"allocator properties on recording terminal");
}
//
// select terminal on the stream
//
hr = pStream->SelectTerminal(pRecordTerminal);
if (FAILED(hr))
{
LogError("CreateAndSelectMST: Failed to select "
"terminal on the stream");
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
// IsRenderingStream
//
// returns TRUE if the stream's direction is TD_RENDER
//
///////////////////////////////////////////////////////////////////////////////
BOOL IsRenderingStream(ITStream *pStream)
{
//
// check the stream's direction
//
TERMINAL_DIRECTION TerminalDirection;
HRESULT hr = pStream->get_Direction(&TerminalDirection);
if (FAILED(hr))
{
LogError("IsRenderingStream: Failed to get stream direction");
return FALSE;
}
if (TD_RENDER == TerminalDirection)
{
return TRUE;
}
else
{
return FALSE;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// IsAudioStream
//
// returns TRUE if the stream's type is TAPIMEDIATYPE_AUDIO
//
///////////////////////////////////////////////////////////////////////////////
BOOL IsAudioStream(ITStream *pStream)
{
//
// check the stream's media type
//
long nMediaType = 0;
HRESULT hr = pStream->get_MediaType(&nMediaType);
if (FAILED(hr))
{
LogError("IsAudioStream: Failed to get media type");
return FALSE;
}
//
// return true if the stream is audio
//
if (TAPIMEDIATYPE_AUDIO == nMediaType)
{
return TRUE;
}
else
{
return FALSE;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// CreateAndSelectMST
//
// check the call's streams. create media streaming terminal on the first
// incoming audio stream
//
// returns:
//
// S_OK if a terminal was created and selected
// S_FALSE if no appropriate stream was found
// error if failed
//
///////////////////////////////////////////////////////////////////////////////
HRESULT CreateAndSelectMST()
{
LogMessage("CreateAndSelectMST: started");
//
// we should already have the call
//
if (NULL == g_pCurrentCall)
{
LogError("CreateAndSelectMST: g_pCurrentCall is NULL");
return E_UNEXPECTED;
}
HRESULT hr = E_FAIL;
//
// get the ITStreamControl interface for this call
//
ITStreamControl *pStreamControl = NULL;
hr = g_pCurrentCall->QueryInterface(IID_ITStreamControl,
(void**)&pStreamControl);
if (FAILED(hr))
{
LogError("CreateAndSelectMST: failed to QI call for ITStreamControl");
return hr;
}
//
// enumerate the streams on the call
//
IEnumStream *pEnumStreams = NULL;
hr = pStreamControl->EnumerateStreams(&pEnumStreams);
pStreamControl->Release();
pStreamControl = NULL;
if (FAILED(hr))
{
LogError("CreateAndSelectMST: failed to enumerate streams on call");
return hr;
}
//
// walk through the list of streams on the call
// for the first incoming audio stream, create a media streaming terminal
// and select it on the stream
//
BOOL bTerminalCreatedAndSelected = FALSE;
while (!bTerminalCreatedAndSelected)
{
ITStream *pStream = NULL;
hr = pEnumStreams->Next(1, &pStream, NULL);
if (S_OK != hr)
{
//
// no more streams or error
//
LogError("CreateAndSelectMST: didn't find an incoming audio stream."
" terminal not selected.");
break;
}
//
// create and select media streaming terminal on the first incoming
// audio stream
//
if ( IsRenderingStream(pStream) && IsAudioStream(pStream))
{
LogMessage("CreateAndSelectMST: creating mst");
//
// create media streaming terminal and select it on the stream
//
ITTerminal *pRecordTerminal = NULL;
pRecordTerminal = CreateRenderMediaStreamingTerminal(g_pCurrentCall);
if (NULL != pRecordTerminal)
{
hr = SelectAndInitializeTerminal(pRecordTerminal, pStream);
pRecordTerminal->Release();
pRecordTerminal = NULL;
if (SUCCEEDED(hr))
{
//
// set the flag, so we can break out of the loop
//
bTerminalCreatedAndSelected = TRUE;
}
} // media streaming terminal created successfully
} // stream is rendering and audio
else
{
//
// the stream is of wrong direction, or type
//
}
pStream->Release();
pStream = NULL;
} // while (enumerating streams on the call)
//
// done with the stream enumeration. release
//
pEnumStreams->Release();
pEnumStreams = NULL;
if (bTerminalCreatedAndSelected)
{
LogMessage("CreateAndSelectMST: terminal selected");
return S_OK;
}
else
{
LogMessage("CreateAndSelectMST: no terminal selected");
return S_FALSE;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// GetTerminalFromMediaEvent
//
//
// get the terminal selected on the event's stream
//
///////////////////////////////////////////////////////////////////////////////
HRESULT GetTerminalFromMediaEvent(IN ITCallMediaEvent *pCallMediaEvent,
OUT ITTerminal **ppTerminal)
{
HRESULT hr = E_FAIL;
//
// don't return garbage if we fail
//
*ppTerminal = NULL;
//
// get the stream corresponding to this event
//
ITStream *pStream = NULL;
hr = pCallMediaEvent->get_Stream(&pStream);
if ( FAILED(hr) )
{
LogError("GetTerminalFromMediaEvent: "
"failed to get stream hr = 0x%lx", hr);
return hr;
}
//
// find the terminal on this stream
//
//
// get terminal enumeration on the stream
//
IEnumTerminal *pEnumTerminal = NULL;
hr = pStream->EnumerateTerminals(&pEnumTerminal);
pStream->Release();
pStream = NULL;
if ( FAILED(hr) )
{
LogError("GetTerminalFromMediaEvent: failed to enumerate terminals, "
"hr = 0x%lx", hr);
return hr;
}
//
// walk through terminal enumeration
//
ULONG nTerminalsFetched = 0;
ITTerminal *pStreamTerminal = NULL;
//
// assuming there is at most one terminal selected on the stream
//
hr = pEnumTerminal->Next(1, &pStreamTerminal, &nTerminalsFetched);
pEnumTerminal->Release();
pEnumTerminal = NULL;
if (S_OK != hr)
{
LogError("GetTerminalFromMediaEvent: enumeration returned no "
"terminals, hr = 0x%lx", hr);
return hr;
}
*ppTerminal = pStreamTerminal;
LogMessage("GetTerminalFromMediaEvent: succeeded");
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// GetNumberOfSamplesOnStream
//
// read the terminal's allocator properties to return the number of samples
// the terminal provides
//
///////////////////////////////////////////////////////////////////////////////
HRESULT GetNumberOfSamplesOnStream(IN IMediaStream *pTerminalMediaStream,
IN OUT DWORD *pnNumberOfSamples)
{
HRESULT hr = S_OK;
//
// don't return garbage
//
*pnNumberOfSamples = 0;
//
// get allocator properties
//
ITAllocatorProperties *pAllocProperites = NULL;
hr = pTerminalMediaStream->QueryInterface(IID_ITAllocatorProperties,
(void **)&pAllocProperites);
if (FAILED(hr))
{
LogError("GetNumberOfSamplesOnStream: "
"Failed to QI terminal for ITAllocatorProperties");
return hr;
}
//
// we want to know the number of samples we will be getting
//
ALLOCATOR_PROPERTIES AllocProperties;
hr = pAllocProperites->GetAllocatorProperties(&AllocProperties);
pAllocProperites->Release();
pAllocProperites = NULL;
if (FAILED(hr))
{
LogError("GetNumberOfSamplesOnStream: "
"Failed to get terminal's allocator properties");
return hr;
}
*pnNumberOfSamples = AllocProperties.cBuffers;
//
// log the number of buffers and their sizes
//
LogMessage("GetNumberOfSamplesOnStream: [%ld] samples, [%ld] bytes each",
*pnNumberOfSamples, AllocProperties.cbBuffer);
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// ReleaseEvents
//
//
// close the handles passed into the function and release the array of handles
//
///////////////////////////////////////////////////////////////////////////////
void ReleaseEvents(IN OUT HANDLE *pEvents, // array of events to be freed
IN DWORD nNumberOfEvents // number of events in the array
)
{
//
// close all the handles in the array
//
for (DWORD i = 0; i < nNumberOfEvents; i++)
{
CloseHandle(pEvents[i]);
pEvents[i] = NULL;
}
//
// free the array itself
//
FreeMemory(pEvents);
pEvents = NULL;
}
///////////////////////////////////////////////////////////////////////////////
//
// AllocateEvents
//
// allocate the array of events of size nNumberOfSamples
//
// return pointer to the allocated and initialized array if success
// or NULL if failed
//
///////////////////////////////////////////////////////////////////////////////
HANDLE *AllocateEvents(IN DWORD nNumberOfEvents)
{
//
// pointer to an array of event handles
//
HANDLE *pSampleReadyEvents = NULL;
pSampleReadyEvents =
(HANDLE*)AllocateMemory(sizeof(HANDLE) * nNumberOfEvents);
if (NULL == pSampleReadyEvents)
{
LogError("AllocateEvents: Failed to allocate sample ready events.");
return NULL;
}
//
// create an event for every allocated handle
//
for (DWORD i = 0; i < nNumberOfEvents; i++)
{
pSampleReadyEvents[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
if (NULL == pSampleReadyEvents[i])
{
LogError("AllocateEvents: "
"Failed to create event for sample %d", i);
//
// close handles we have created already
//
for (DWORD j = 0; j< i; j++)
{
CloseHandle(pSampleReadyEvents[j]);
pSampleReadyEvents[j] = NULL;
}
FreeMemory(pSampleReadyEvents);
pSampleReadyEvents = NULL;
return NULL;
}
} // creating events for each sample
//
// succeded creating events. return the pointer to the array
//
return pSampleReadyEvents;
}
///////////////////////////////////////////////////////////////////////////////
//
// ReleaseSamples
//
// aborts and releases every sample in the array of samples of size
// nNumberOfSamples and deallocates the array itself
//
// ppStreamSamples becomes invalid when the function returns
//
///////////////////////////////////////////////////////////////////////////////
void ReleaseSamples(IN OUT IStreamSample **ppStreamSamples,
IN DWORD nNumberOfSamples)
{
for (DWORD i = 0; i < nNumberOfSamples; i++)
{
ppStreamSamples[i]->CompletionStatus(COMPSTAT_WAIT |
COMPSTAT_ABORT,
INFINITE);
//
// regardless of the error code, release the sample
//
ppStreamSamples[i]->Release();
ppStreamSamples[i] = NULL;
}
FreeMemory(ppStreamSamples);
ppStreamSamples = NULL;
}
///////////////////////////////////////////////////////////////////////////////
//
// AllocateStreamSamples
//
// allocate the array of nNumberOfSamples samples, and initialize each sample
// pointer in the array with samples from the supplied stream.
//
// return pointer to the allocated and initialized array if success
// or NULL if failed
//
///////////////////////////////////////////////////////////////////////////////
IStreamSample **AllocateStreamSamples(IN IMediaStream *pMediaStream,
IN DWORD nNumberOfSamples)
{
//
// allocate stream sample array
//
IStreamSample **ppStreamSamples = (IStreamSample **)
AllocateMemory( sizeof(IStreamSample*) * nNumberOfSamples );
if (NULL == ppStreamSamples)
{
LogError("AllocateStreamSamples: Failed to allocate stream sample array");
return NULL;
}
//
// allocate samples from the stream and put them into the array
//
for (DWORD i = 0; i < nNumberOfSamples; i++)
{
HRESULT hr = pMediaStream->AllocateSample(0, &ppStreamSamples[i]);
if (FAILED(hr))
{
LogError("AllocateStreamSamples: Failed to allocateSample. "
"Sample #%d", i);
for (DWORD j = 0; j < i; j++)
{
ppStreamSamples[j]->Release();
ppStreamSamples[j] = NULL;
}
FreeMemory(ppStreamSamples);
ppStreamSamples = NULL;
return NULL;
} // failed AllocateSample()
} // allocating samples on the stream
//
// succeeded allocating samples
//
return ppStreamSamples;
}
///////////////////////////////////////////////////////////////////////////////
//
// AssociateEventsWithSamples
//
// call Update() on every sample of the array of stream samples to associate it
// with an event from the array of events. The events will be signaled when the
// corresponding sample has data and is ready to be written to a file
//
///////////////////////////////////////////////////////////////////////////////
HRESULT AssociateEventsWithSamples(IN HANDLE *pSampleReadyEvents,
IN IStreamSample **ppStreamSamples,
IN DWORD nNumberOfSamples)
{
for (DWORD i = 0; i < nNumberOfSamples; i++)
{
//
// the event passed to Update will be signaled when the sample is
// filled with data
//
HRESULT hr =
ppStreamSamples[i]->Update(0, pSampleReadyEvents[i], NULL, 0);
if (FAILED(hr))
{
LogError("AssociateEventsWithSamples: "
"Failed to call update on sample #%d", i);
//
// abort the samples we have Update()'d
//
for (DWORD j = 0; j < i; j++)
{
//
// no need to check the return code here -- best effort attempt
// if failed -- too bad
//
ppStreamSamples[j]->CompletionStatus(COMPSTAT_WAIT |
COMPSTAT_ABORT,
INFINITE);
}
return hr;
} // Update() failed
} // Update()'ing all samples
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// GetAudioFormat
//
// return a pointer to wave format structure for the audio data produced by
// the stream. the caller is responsible for deallocating returned stucture
//
// returns NULL if failed
//
//////////////////////////////////////////////////////////////////////////////
WAVEFORMATEX *GetAudioFormat(IMediaStream *pTerminalMediaStream)
{
//
// get ITAMMediaFormat interface on the terminal, so we can query for
// audio format
//
ITAMMediaFormat *pITMediaFormat = NULL;
HRESULT hr = pTerminalMediaStream->QueryInterface(IID_ITAMMediaFormat,
(void **)&pITMediaFormat);
if (FAILED(hr))
{
LogError("GetAudioFormat: "
"failed to QI terminal for ITAMMediaFormat");
return NULL;
}
//
// use ITAMMediaFormat to get terminal's media format
//
AM_MEDIA_TYPE *pMediaType = NULL;
hr = pITMediaFormat->get_MediaFormat(&pMediaType);
pITMediaFormat->Release();
pITMediaFormat = NULL;
if (FAILED(hr))
{
LogError("GetAudioFormat: failed to get_MediaFormat hr = 0x%lx", hr);
return NULL;
}
//
// did we get back a format that we can use?
//
if ((pMediaType->pbFormat == NULL) ||
pMediaType->formattype != FORMAT_WaveFormatEx)
{
LogError("GetAudioFormat: invalid format");
DeleteMediaType(pMediaType);
pMediaType = NULL;
return NULL;
}
//
// allocate and return wave format
//
WAVEFORMATEX *pFormat =
(WAVEFORMATEX *)AllocateMemory(pMediaType->cbFormat);
if (NULL != pFormat)
{
CopyMemory(pFormat, pMediaType->pbFormat, pMediaType->cbFormat);
}
else
{
LogError("GetAudioFormat: Failed to allocate memory for audio format");
}
//
// remember to release AM_MEDIA_TYPE that we no longer need
//
DeleteMediaType(pMediaType);
pMediaType = NULL;
return pFormat;
}
///////////////////////////////////////////////////////////////////////////////
//
// WriteSampleToFile
//
// This function writes the data portion of the sample into the file
//
///////////////////////////////////////////////////////////////////////////////
HRESULT WriteSampleToFile(IN IStreamSample *pStreamSample, // sample to record
IN CAVIFileWriter *pFileWriter) // file to record to
{
//
// get the sample's IMemoryData interface so we can get to the
// sample's data
//
IMemoryData *pSampleMemoryData = NULL;
HRESULT hr = pStreamSample->QueryInterface(IID_IMemoryData,
(void **)&pSampleMemoryData);
if (FAILED(hr))
{
LogError("WriteSampleToFile: "
"Failed to qi sample for IMemoryData");
return hr;
}
//
// get to the sample's data buffer
//
DWORD nBufferSize = 0;
BYTE *pnDataBuffer = NULL;
DWORD nActualDataSize = 0;
hr = pSampleMemoryData->GetInfo(&nBufferSize,
&pnDataBuffer,
&nActualDataSize);
pSampleMemoryData->Release();
pSampleMemoryData = NULL;
if (FAILED(hr))
{
LogError("WriteSampleToFile: "
"Failed to get to the sample's data");
return hr;
}
//
// write the data buffer to the avi file
//
LogMessage("WriteSampleToFile: received a sample of size %ld bytes",
nActualDataSize);
ULONG nBytesWritten = 0;
hr = pFileWriter->Write(pnDataBuffer,
nActualDataSize,
&nBytesWritten);
if (FAILED(hr) || (0 == nBytesWritten))
{
LogError("WriteSampleToFile: FileWriter.Write() wrote no data.");
return E_FAIL;
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
// GetSampleID
//
// given the return code fom WaitForMultipleObjects, this function determines
// which sample was signal and returns S_OK and the id of the signaled sample
// or E_FAIL if WaitForMultipleEvents returned an error
//
///////////////////////////////////////////////////////////////////////////////
HRESULT GetSampleID(IN DWORD nWaitCode, // code from WaitForMultiple...
IN DWORD nNumberOfSamples, // the total number of samples
IN OUT DWORD *pnSampleID) // the calculated id of the
// signaled sample
{
//
// event abandoned?
//
if ( (nWaitCode >= WAIT_ABANDONED_0) &&
(nWaitCode < WAIT_ABANDONED_0 + nNumberOfSamples) )
{
LogError("GetSampleID: event for sample #%lu abandoned.",
nWaitCode - WAIT_ABANDONED_0);
return E_FAIL;
}
//
// any other error?
//
if ( (WAIT_OBJECT_0 > nWaitCode) ||
(WAIT_OBJECT_0 + nNumberOfSamples <= nWaitCode) )
{
LogMessage("GetSampleID: "
"waiting for samples failed or timed out. "
"WaitForMultipleObjects returned %lu", nWaitCode);
return E_FAIL;
}
//
// which sample was signaled?
//
*pnSampleID = nWaitCode - WAIT_OBJECT_0;
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// WriteStreamToFile
//
// extract samples from the terminal's media stream and write them into a file
//
// returns when the call is disconnected (call disconnect causes media streaming
// terminal to abort the samples
//
///////////////////////////////////////////////////////////////////////////////
HRESULT WriteStreamToFile(IN IMediaStream *pTerminalMediaStream)
{
LogMessage("WriteStreamToFile: started");
HRESULT hr = E_FAIL;
//
// get the number of stream samples we will be using
//
DWORD nNumberOfSamples = 0;
hr = GetNumberOfSamplesOnStream(pTerminalMediaStream, &nNumberOfSamples);
if (FAILED(hr))
{
LogError("WriteStreamToFile: failed to get the number of samples");
return hr;
}
//
// the number of samples directly corresponds the number of events we will
// be waiting on later. WaitForMultipleObjects has a limit of
// MAXIMUM_WAIT_OBJECTS events.
//
if (nNumberOfSamples > MAXIMUM_WAIT_OBJECTS)
{
LogError("WriteStreamToFile: the number of samples [%ld] "
"exceeds the number allowed by the design of this "
"application [%ld]",
nNumberOfSamples, MAXIMUM_WAIT_OBJECTS);
return E_FAIL;
}
//
// allocate events that will be signaled when each sample is ready to be
// saved to a file
//
HANDLE *pSampleReadyEvents = NULL;
pSampleReadyEvents = AllocateEvents(nNumberOfSamples);
if (NULL == pSampleReadyEvents)
{
LogError("WriteStreamToFile: Failed to allocate sample ready events.");
return E_OUTOFMEMORY;
}
//
// allocate array of stream samples
//
IStreamSample **ppStreamSamples = NULL;
ppStreamSamples = AllocateStreamSamples(pTerminalMediaStream,
nNumberOfSamples);
if (NULL == ppStreamSamples)
{
LogError("WriteStreamToFile: Failed to allocate stream sample array");
//
// release events we have allocated
//
ReleaseEvents(pSampleReadyEvents, nNumberOfSamples);
pSampleReadyEvents = NULL;
return E_FAIL;
}
//
// we have the samples, we have the events.
// associate events with samples so events get signaled when the
// corresponding samples are ready to be written to a file
//
hr = AssociateEventsWithSamples(pSampleReadyEvents,
ppStreamSamples,
nNumberOfSamples);
if (FAILED(hr))
{
LogError("WriteStreamToFile: Failed to associate events with samples");
//
// release events and samples we have allocated
//
ReleaseEvents(pSampleReadyEvents, nNumberOfSamples);
pSampleReadyEvents = NULL;
ReleaseSamples(ppStreamSamples, nNumberOfSamples);
ppStreamSamples = NULL;
return E_FAIL;
}
//
// get the format of the data delivered by media streaming terminal
//
WAVEFORMATEX *pAudioFormat = NULL;
pAudioFormat = GetAudioFormat(pTerminalMediaStream);
if (NULL == pAudioFormat)
{
LogError("WriteStreamToFile: Failed to get audio format");
//
// release events and samples we have allocated
//
ReleaseEvents(pSampleReadyEvents, nNumberOfSamples);
pSampleReadyEvents = NULL;
ReleaseSamples(ppStreamSamples, nNumberOfSamples);
ppStreamSamples = NULL;
return E_FAIL;
}
//
// create a file with the required name and format.
//
CAVIFileWriter FileWriter;
hr = FileWriter.Initialize(SZ_OUTPUTFILENAME, *pAudioFormat);
//
// no longer need audio format
//
FreeMemory(pAudioFormat);
pAudioFormat = NULL;
if (FAILED(hr))
{
LogError("WriteStreamToFile: open file");
//
// release events and samples we have allocated
//
ReleaseEvents(pSampleReadyEvents, nNumberOfSamples);
pSampleReadyEvents = NULL;
ReleaseSamples(ppStreamSamples, nNumberOfSamples);
ppStreamSamples = NULL;
return hr;
}
//
// just for logging, count the number of samples we have recorded
//
ULONG nStreamSamplesRecorded = 0;
while(TRUE)
{
//
// wait for the events associated with the samples
// when a samples has data, the corresponding event will be
// signaled
//
DWORD nWaitCode = WaitForMultipleObjects(nNumberOfSamples,
pSampleReadyEvents,
FALSE,
INFINITE);
//
// get the id of the sample that was signaled. fail if Wait returned
// error
//
DWORD nSampleID = 0;
hr = GetSampleID(nWaitCode, nNumberOfSamples, &nSampleID);
if (FAILED(hr))
{
LogError("WriteStreamToFile: wait failed");
break;
}
//
// we filtered out all invalid error codes. so nSampleID has no
// choice but be a valid sample index.
//
_ASSERTE(nSampleID < nNumberOfSamples);
//
// make sure the sample is ready to be read
//
hr = ppStreamSamples[nSampleID]->CompletionStatus(COMPSTAT_WAIT, 0);
//
// check against S_OK explicitly -- not all success codes mean the
// sample is ready to be used (MS_S_ENDOFSTREAM, etc)
//
if (S_OK != hr)
{
if (E_ABORT == hr)
{
//
// recording was aborted, probably because
// the call was disconnected
//
LogMessage("WriteStreamToFile: recording aborted");
}
else
{
LogMessage("WriteStreamToFile: sample is not completed. "
"hr = 0x%lx", hr);
}
break;
}
//
// we have the sample that was signaled and which is now ready to be
// saved to a file. Record the sample.
//
hr = WriteSampleToFile(ppStreamSamples[nSampleID], &FileWriter);
if (FAILED(hr))
{
LogError("WriteStreamToFile: failed to write sample to file");
break;
}
//
// one more sample was recorded. update the count.
//
nStreamSamplesRecorded++;
//
// we are done with this sample. return it to the source stream
// to be refilled with data
//
hr = ppStreamSamples[nSampleID]->Update(0,
pSampleReadyEvents[nSampleID],
NULL,
0);
if (FAILED(hr))
{
LogError("WriteStreamToFile: "
"Failed to Update the sample recorded. "
"hr = 0x%lx", hr);
break;
}
} // sample-writing loop
LogMessage("WriteStreamToFile: wrote the total of %lu samples",
nStreamSamplesRecorded);
//
// release samples and events
//
ReleaseSamples(ppStreamSamples, nNumberOfSamples);
ppStreamSamples = NULL;
ReleaseEvents(pSampleReadyEvents, nNumberOfSamples);
pSampleReadyEvents = NULL;
//
// deallocated samples and events. safe to exit.
//
LogMessage("WriteStreamToFile: completed, hr = 0x%lx", hr);
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
// RecordMessage
//
// record the terminal's stream into a file
//
///////////////////////////////////////////////////////////////////////////////
HRESULT RecordMessage(IN ITTerminal *pRecordTerm)
{
LogMessage("RecordMessage: started");
HRESULT hr = E_FAIL;
//
// get IMediaStream interface on the terminal
//
IMediaStream *pTerminalMediaStream = NULL;
hr = pRecordTerm->QueryInterface(IID_IMediaStream,
(void**)&pTerminalMediaStream);
if (FAILED(hr))
{
LogError("RecordMessage: Failed to qi terminal for IMediaStream.");
return hr;
}
//
// write terminal stream data to a file
//
hr = WriteStreamToFile(pTerminalMediaStream);
//
// done with the terminal stream, release.
//
pTerminalMediaStream->Release();
pTerminalMediaStream = NULL;
LogMessage("RecordMessage: finished");
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
// ProcessCallNotificationEvent
//
// processing for TE_CALLNOTIFICATION event
//
///////////////////////////////////////////////////////////////////////////////
HRESULT ProcessCallNotificationEvent(IDispatch *pEvent)
{
HRESULT hr = E_FAIL;
//
// we are being notified of a new call
//
// if we own the call and there is not other active call
// consider this to be the active call
//
// wait for CS_OFFERING message before answering the call
//
ITCallNotificationEvent *pCallNotificationEvent = NULL;
hr = pEvent->QueryInterface( IID_ITCallNotificationEvent,
(void **)&pCallNotificationEvent);
if (FAILED(hr))
{
LogError("ProcessCallNotificationEvent: "
"Failed to QI event for ITCallNotificationEvent");
return hr;
}
//
// get the call from notification event
//
ITCallInfo *pCall = NULL;
hr = pCallNotificationEvent->get_Call(&pCall);
//
// release the ITCallNotificationEvent interface
//
pCallNotificationEvent->Release();
pCallNotificationEvent = NULL;
if (FAILED(hr))
{
LogError("ProcessCallNotificationEvent: "
"Failed to get call from Call notification event");
return hr;
}
//
// if we already have an active call, reject the new incoming call
//
EnterCriticalSection(&g_CurrentCallCritSection);
if (NULL != g_pCurrentCall)
{
LeaveCriticalSection(&g_CurrentCallCritSection);
LogMessage("ProcessCallNotificationEvent: "
"incoming call while another call in progress");
ITBasicCallControl *pSecondCall = NULL;
hr = pCall->QueryInterface(IID_ITBasicCallControl,
(void**)&pSecondCall);
pCall->Release();
pCall = NULL;
if (FAILED(hr))
{
LogError("ProcessCallNotificationEvent: failed to qi incoming call "
"for ITBasicCallConrtrol");
return hr;
}
//
// reject the incoming call
//
LogMessage("ProcessCallNotificationEvent: rejecting the incoming call");
hr = pSecondCall->Disconnect(DC_REJECTED);
pSecondCall->Release();
pSecondCall = NULL;
return E_FAIL;
}
//
// check to see if we own the call
//
CALL_PRIVILEGE cp;
hr = pCall->get_Privilege( &cp );
if ( FAILED(hr) )
{
LogError("ProcessCallNotificationEvent: Failed to get call owner info");
pCall->Release();
pCall = NULL;
LeaveCriticalSection(&g_CurrentCallCritSection);
return hr;
}
if ( CP_OWNER != cp )
{
//
// we don't own the call. ignore it.
//
LogMessage("ProcessCallNotificationEvent: We don't own the call.");
pCall->Release();
pCall = NULL;
LeaveCriticalSection(&g_CurrentCallCritSection);
return E_FAIL;
}
else
{
LogMessage("ProcessCallNotificationEvent: Incoming call.");
}
//
// keep the call for future use
//
hr = pCall->QueryInterface(IID_ITBasicCallControl,
(void**)&g_pCurrentCall);
if (FAILED(hr))
{
LogError("ProcessCallNotificationEvent: failed to qi incoming call for"
"ITBasicCallControl.");
g_pCurrentCall = NULL;
}
LeaveCriticalSection(&g_CurrentCallCritSection);
pCall->Release();
pCall = NULL;
return hr;
} // ProcessCallNotificationEvent
///////////////////////////////////////////////////////////////////////////////
//
// ProcessCallMediaEvent
//
// processing for TE_CALLMEDIA event. if stream is active, record the
// incoming data
//
///////////////////////////////////////////////////////////////////////////////
HRESULT ProcessCallMediaEvent(IDispatch *pEvent)
{
//
// Get ITCallMediaEvent interface from the event
//
ITCallMediaEvent *pCallMediaEvent = NULL;
HRESULT hr = pEvent->QueryInterface( IID_ITCallMediaEvent,
(void **)&pCallMediaEvent );
if (FAILED(hr))
{
//
// the event does not have the interface we want
//
LogError("ProcessCallMediaEvent: TE_CALLMEDIA. "
"Failed to QI event for ITCallMediaEvent");
return hr;
}
//
// get the CALL_MEDIA_EVENT that we are being notified of.
//
CALL_MEDIA_EVENT CallMediaEvent;
hr = pCallMediaEvent->get_Event(&CallMediaEvent);
if ( FAILED(hr) )
{
//
// failed to get call media event
//
LogError("ProcessCallMediaEvent: TE_CALLMEDIA. "
"Failed to get call media event hr = 0x%lx", hr);
pCallMediaEvent->Release();
pCallMediaEvent = NULL;
return hr;
}
LogMessage("ProcessCallMediaEvent: processing call media event");
switch (CallMediaEvent)
{
case CME_STREAM_INACTIVE:
{
LogMessage("ProcessCallMediaEvent: CME_STREAM_INACTIVE");
break;
}
case CME_STREAM_NOT_USED:
LogMessage("ProcessCallMediaEvent: CME_STREAM_NOT_USED");
break;
case CME_NEW_STREAM:
LogMessage("ProcessCallMediaEvent: CME_NEW_STREAM received");
break;
case CME_STREAM_FAIL:
LogError("ProcessCallMediaEvent: CME_STREAM_FAIL received");
break;
case CME_TERMINAL_FAIL:
LogError("ProcessCallMediaEvent: CME_STREAM_FAIL received");
break;
case CME_STREAM_ACTIVE:
{
LogError("ProcessCallMediaEvent: CME_STREAM_ACTIVE received");
//
// Get the terminal on the active stream
//
ITTerminal *pRecordStreamTerminal = NULL;
hr = GetTerminalFromMediaEvent(pCallMediaEvent,
&pRecordStreamTerminal);
if ( FAILED(hr) )
{
//
// the stream has no terminals associated with it
//
LogError("ProcessCallMediaEvent: "
"failed to get terminal on the active stream");
break;
}
//
// make sure the direction is right -- we are recording, so the
// terminal should be TD_RENDER
//
TERMINAL_DIRECTION td;
hr = pRecordStreamTerminal->get_Direction( &td);
if ( FAILED(hr) )
{
LogError("ProcessCallMediaEvent: "
"failed to get record terminal's direction.");
pRecordStreamTerminal->Release();
pRecordStreamTerminal = NULL;
break;
}
//
// double check that the terminal is rendering terminal
// since we are the recording side
//
if ( TD_RENDER != td )
{
//
// this should never ever happen
//
LogError("ProcessCallMediaEvent: bad terminal direction");
pRecordStreamTerminal->Release();
pRecordStreamTerminal = NULL;
hr = E_FAIL;
break;
}
//
// Now do the actual streaming.
//
//
// this will block until:
//
// the call is disconnected, or
// the user chooses to close the app, or
// there is an error
//
// Since we are in the message processing thread,
// the application will not be able to process messages
// (the messages will still be queued) until this call
// returns.
//
// If it is important that messages are processed while
// file is being recorded, recording should be done on
// a different thread.
//
RecordMessage(pRecordStreamTerminal);
pRecordStreamTerminal->Release();
pRecordStreamTerminal = NULL;
break;
}
default:
break;
} // switch (call media event)
//
// We no longer need the event interface.
//
pCallMediaEvent->Release();
pCallMediaEvent = NULL;
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//
// ProcessCallStateEvent
//
// processing for TE_CALLSTATE. if CS_OFFERING, creates and selects MST,
// answers the call . Release call if disconnected.
//
// also verifies that the event is for the current call
//
///////////////////////////////////////////////////////////////////////////////
HRESULT ProcessCallStateEvent(IDispatch *pEvent)
{
HRESULT hr = S_OK;
//
// TE_CALLSTATE is a call state event.
// pEvent is an ITCallStateEvent
//
ITCallStateEvent *pCallStateEvent = NULL;
//
// Get the interface
//
hr = pEvent->QueryInterface(IID_ITCallStateEvent,
(void **)&pCallStateEvent);
if ( FAILED(hr) )
{
LogError("ProcessCallStateEvent: "
"Failed to QI event for ITCallStateEvent");
return hr;
}
//
// make sure the message is for the active call!
//
EnterCriticalSection(&g_CurrentCallCritSection);
if (!IsMessageForActiveCall(pCallStateEvent))
{
LogMessage("ProcessCallStateEvent: received TE_CALLSTATE message "
"for a different call. ignoring.");
pCallStateEvent->Release();
pCallStateEvent = NULL;
LeaveCriticalSection(&g_CurrentCallCritSection);
return E_FAIL;
}
//
// get the CallState that we are being notified of.
//
CALL_STATE CallState;
hr = pCallStateEvent->get_State(&CallState);
//
// no longer need the event
//
pCallStateEvent->Release();
pCallStateEvent = NULL;
if (FAILED(hr))
{
LogError("ProcessCallStateEvent: "
"failed to get state from call state event.");
LeaveCriticalSection(&g_CurrentCallCritSection);
return hr;
}
//
// log the new call state
//
if (CS_OFFERING == CallState)
{
LogMessage("ProcessCallStateEvent: call state is CS_OFFERING");
//
// try to create and select media streaming terminal on one of
// the call's incoming audio streams
//
hr = CreateAndSelectMST();
if (S_OK == hr)
{
//
// we have selected a terminal on one of the streams
// answer the call
//
LogMessage("ProcessCallStateEvent: answering the call");
hr = g_pCurrentCall->Answer();
if (FAILED(hr))
{
LogError("ProcessCallStateEvent: Failed to answer the call");
}
}
else
{
//
// we could not create mst on any of the streams of
// the incoming call. reject the call.
//
LogMessage("ProcessCallStateEvent: rejecting the call");
HRESULT hr2 = g_pCurrentCall->Disconnect(DC_REJECTED);
if (FAILED(hr2))
{
LogError("ProcessCallStateEvent: Failed to reject the call");
}
}
} // CS_OFFERING
else if (CS_DISCONNECTED == CallState)
{
LogMessage("ProcessCallStateEvent: call state is CS_DISCONNECTED. "
"Releasing the call.");
//
// release the call -- no longer need it!
//
g_pCurrentCall->Release();
g_pCurrentCall = NULL;
//
// signal the main thread that it can exit if it is time to exit
//
LogMessage("ProcessCallStateEvent: signaling main thread.");
SetEvent(g_hExitEvent);
} // CS_DISCONNECTED
else if (CS_CONNECTED == CallState)
{
LogMessage("ProcessCallStateEvent: call state is CS_CONNECTED");
} // CS_CONNECTED
//
// no longer need to protect current call
//
LeaveCriticalSection(&g_CurrentCallCritSection);
return hr;
}
/////////////////////////////////////////////////////////////////////////////
//
// OnTapiEvent
//
// handler for tapi events. called on a thread that provides asychronous
// processing of tapi messages
//
/////////////////////////////////////////////////////////////////////////////
HRESULT OnTapiEvent(TAPI_EVENT TapiEvent, IDispatch *pEvent)
{
LogMessage("OnTapiEvent: message received");
HRESULT hr = S_OK;
switch ( TapiEvent )
{
case TE_CALLNOTIFICATION:
{
LogMessage("OnTapiEvent: received TE_CALLNOTIFICATION");
hr = ProcessCallNotificationEvent(pEvent);
break;
} // TE_CALLNOTIFICATION
case TE_CALLSTATE:
{
LogMessage("OnTapiEvent: received TE_CALLSTATE");
hr = ProcessCallStateEvent(pEvent);
break;
} // TE_CALLSTATE
case TE_CALLMEDIA:
{
LogMessage("OnTapiEvent: received TE_CALLMEDIA");
hr = ProcessCallMediaEvent(pEvent);
break;
} // case TE_CALLMEDIA
default:
LogMessage("OnTapiEvent: received message %d. not handled.", TapiEvent);
break;
}
//
// the event was AddRef()'ed when it was posted for asynchronous processing
// no longer need the event, release it.
//
pEvent->Release();
pEvent = NULL;
LogMessage("OnTapiEvent: exiting.");
return hr;
}
| 22.762858
| 89
| 0.50919
|
windows-development
|
b90d71ff73fe564644ad817975cdc885fc3f1562
| 12,961
|
cpp
|
C++
|
test/libfilsc_test/c_codegen_tests.cpp
|
GuillermoHernan/fil-s
|
33d2a8e1c0eb3a9fddd9e6e2dc02780a13fd2302
|
[
"MIT"
] | null | null | null |
test/libfilsc_test/c_codegen_tests.cpp
|
GuillermoHernan/fil-s
|
33d2a8e1c0eb3a9fddd9e6e2dc02780a13fd2302
|
[
"MIT"
] | null | null | null |
test/libfilsc_test/c_codegen_tests.cpp
|
GuillermoHernan/fil-s
|
33d2a8e1c0eb3a9fddd9e6e2dc02780a13fd2302
|
[
"MIT"
] | null | null | null |
/// <summary>
/// Tests for 'C' code generator
/// </summary>
#include "libfilsc_test_pch.h"
#include "c_codeGenerator_internal.h"
#include "codeGeneratorState.h"
#include "semanticAnalysis.h"
#include "utils.h"
//#include <time.h>
using namespace std;
/// <summary>
/// Fixture for code generation tests.
/// </summary>
class C_CodegenTests : public ::testing::Test {
protected:
string m_resultsDir;
/// <summary>Test initialization</summary>
virtual void SetUp()override
{
m_resultsDir = makeResultsDir();
}
/// <summary>
/// Compiles (both FIL-S and 'C') and executes a test script.
/// </summary>
/// <param name="name"></param>
/// <param name="code"></param>
/// <returns></returns>
int runTest(const char* name, const char* code)
{
//clock_t t0 = clock();
auto parseRes = testParse(code);
if (!parseRes.ok())
throw parseRes.errorDesc;
writeAST(parseRes.result, name);
auto semanticRes = semanticAnalysis(parseRes.result);
if (!semanticRes.ok())
throw semanticRes.errors[0]; //Just the first error, as it is not the tested subsystem.
writeAST(semanticRes.result, name);
string Ccode = generateCode(semanticRes.result, configureCodeGenerator());
writeCcode(Ccode, name);
_flushall(); //To ensure all generated files are written to the disk.
//clock_t t1 = clock();
//cout << "FIL-S compile time: " << double(t1 - t0)*1000 / CLOCKS_PER_SEC << " msegs.\n";
//t0 = t1;
compileC(name);
//t1 = clock();
//cout << "'C' compile time: " << double(t1 - t0)*1000 / CLOCKS_PER_SEC << " msegs.\n";
//t0 = t1;
int result = executeProgram(name);
//t1 = clock();
//cout << "execution time: " << double(t1 - t0)*1000 / CLOCKS_PER_SEC << " msegs.\n";
return result;
}
private:
/// <summary>
/// Creates the directory for test results, if it does not exist.
/// </summary>
/// <returns></returns>
static std::string makeResultsDir()
{
auto testInfo = ::testing::UnitTest::GetInstance()->current_test_info();
string path = string("results/") + testInfo->test_case_name() + "." + testInfo->name();
if (!createDirIfNotExist(path))
{
string message = "Cannot create directory: " + path;
throw exception(message.c_str());
}
return path;
}
/// <summary>
/// Writes the AST to a file in the test directory;
/// </summary>
/// <param name="node"></param>
/// <param name="testName"></param>
void writeAST(Ref<AstNode> node, const char* testName)
{
string path = buildOutputFilePath(testName, ".result");
string content = printAST(node);
if (!writeTextFile(path, content))
{
string message = "Cannot write file: " + path;
throw exception(message.c_str());
}
}
/// <summary>
/// Creates the code genrator configuration structure.
/// </summary>
/// <returns></returns>
CodeGeneratorConfig configureCodeGenerator()
{
static const char * prolog =
"#include <stdio.h>\n"
"//************ Prolog\n"
"\n"
"typedef unsigned char bool;\n"
"static const bool true = 1;\n"
"static const bool false = 0;\n"
"\n";
static const char * epilog =
"\n//************ Epilog\n"
"int main()\n"
"{\n"
" int result = test();\n"
" printf (\"%d\\n\", result);\n"
" \n"
" return result;\n"
"}\n";
//static const char * epilogActor =
// "\n//************ Epilog\n"
// "\n"
// "Test mainActor;\n"
// "\n"
// "int main()\n"
// "{\n"
CodeGeneratorConfig result;
result.prolog = prolog;
result.epilog = epilog;
result.predefNames["test"] = "test";
return result;
}
/// <summary>
/// Writes the 'C' code to a file in the test directory;
/// </summary>
/// <param name="code"></param>
/// <param name="testName"></param>
void writeCcode(const std::string& code, const char* testName)
{
string path = buildOutputFilePath(testName, ".c");
if (!writeTextFile(path, code))
{
string message = "Cannot write file: " + path;
throw exception(message.c_str());
}
}
/// <summary>
/// Compiles the resulting 'C' file with an external compiler.
/// </summary>
/// <param name="testName"></param>
int executeProgram(const char* testName)
{
//TODO: The executable extension is also system-dependent.
string path = buildOutputFilePath(testName, ".exe");
path = normalizePath(path);
string command = "cmd /C \"" + path + "\" >\"" + path + ".out\"";
return system(command.c_str());
}
void compileC(const char* testName)
{
string scriptPath = createCompileScript(testName);
string command = "cmd /C \"" + scriptPath + "\" >NUL";
_flushall();
int result = system(command.c_str());
if (result != 0)
{
string message = string("Error compiling 'C' code (") + testName + ".c)";
throw exception(message.c_str());
}
}
std::string buildOutputFilePath(const string& testName, const string& extension)
{
return m_resultsDir + "/" + testName + extension;
}
string createCompileScript(const char* testName)
{
//TODO: This function is very system dependent.
static const char* base =
"call \"H:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat\"\n"
"cd \"%s\"\n"
"%s\n"
"cl %s.c -nologo /FAs /Ox >%s.compiler.out\n";
char buffer[4096];
string absPath = joinPaths(getCurrentDirectory(), m_resultsDir);
string drive = absPath.substr(0, 2);
string scriptPath = buildOutputFilePath(testName, ".compile.bat");
absPath = normalizePath(absPath);
scriptPath = normalizePath(scriptPath);
sprintf_s(buffer, base, absPath.c_str(), drive.c_str(), testName, testName);
if (!writeTextFile(scriptPath, buffer))
{
string message = "Cannot write file: " + scriptPath;
throw exception(message.c_str());
}
return scriptPath;
}
}; //class C_CodegenTests
#define EXPECT_RUN_OK(n,x) EXPECT_EQ(0, runTest((n),(x)))
/// <summary>
/// Tests 'generateCode' function.
/// </summary>
TEST_F(C_CodegenTests, generateCode)
{
int res = runTest("generate1", "function test ():int {0}");
ASSERT_EQ(0, res);
}
/// <summary>
/// Test code generation for function definition nodes.
/// Also tests 'genFunctionHeader' function.
/// </summary>
TEST_F(C_CodegenTests, functionCodegen)
{
//Function with a scalar return value.
EXPECT_RUN_OK("function1",
"function add (a:int, b: int):int {\n"
" a+b\n"
"}\n"
"function test ():int {\n"
" if (add(3,7) == 10) 0 else 1\n"
"}"
);
//Function with no return value
EXPECT_RUN_OK("function2",
"function t2 (a:int, b: int):() {\n"
" a+b\n"
"}\n"
"function test ():int {\n"
" t2(3,1);\n"
" 0\n"
"}"
);
//Function with a tuple return value.
EXPECT_RUN_OK("function3",
"function stats (a:int, b: int, c: int):(sum: int, mean:int) {\n"
" const sum = a+b+c\n"
" (sum, sum/3)"
"}\n"
"function test ():int {\n"
" const result = stats (7,5,6);"
" if ((result.sum == 18) && (result.mean == 6))\n"
" 0 else 1\n"
"}"
);
}
/// <summary>
/// Test code generation for block nodes.
/// </summary>
TEST_F(C_CodegenTests, blockCodegen)
{
EXPECT_RUN_OK("block1",
"function ppc(p:int, p':int) {\n"
" const alpha = (p * p) - 8\n"
" const bravo = p' + {12}\n"
" {}\n"
" alpha % bravo\n"
"}\n"
"function test ():int {\n"
" if (ppc(9,5) == 5) 0 else 1\n"
"}\n"
);
}
/// <summary>
/// Test code generation for Tuples.
/// </summary>
TEST_F(C_CodegenTests, tupleCodegen)
{
EXPECT_RUN_OK("tuple1",
"function divide(a:int, b:int) {\n"
" (a/b, a%b)\n"
"}\n"
"function doNothing() {\n"
" ()\n"
"}\n"
"function test ():int {\n"
" var x:(q:int, r:int)\n"
" doNothing()\n"
" x = divide (23, 7)\n"
" if ( (x.q == 3) && (x.r == 2)) 0 else 1\n"
"}\n"
);
}
/// <summary>
/// Test code generation for return statements.
/// </summary>
TEST_F(C_CodegenTests, returnCodegen)
{
EXPECT_RUN_OK("return1",
"function divide(a:int, b:int) {\n"
" return (a/b, a%b)\n"
"}\n"
"function divide'(a:int, b:int):(r:int, q:int) {\n"
" return (a/b, a%b)\n"
"}\n"
"function doNothing() {\n"
" return;\n"
"}\n"
"function test ():int {\n"
" var x:(q:int, r:int)\n"
" doNothing()\n"
" x = divide (23, 7)\n"
" if ( (x.q != 3) || (x.r != 2)) return 1\n"
" if ( divide'(14,2).r != 7) return 2\n"
" if ( divide'(31,7).q != 3) return 3\n"
"\n"
" return 0"
"}\n"
);
}
/// <summary>
/// Test code generation for return assignment expressions.
/// </summary>
TEST_F(C_CodegenTests, assignmentCodegen)
{
EXPECT_RUN_OK("assign1",
"function test ():int {\n"
" var x:int\n"
" var y:int\n"
" x = y = 5\n"
" if ((x*y) != 25) return 1\n"
" \n"
" var t:(var a:int, var b:int)\n"
" t.a = 7;\n"
" if (t.a != 7) return 2\n"
" \n"
" t.a = x = t.b = 8;\n"
" const p = x * t.a * t.b;\n"
" if (p != 512) return 3\n"
" \n"
" return 0\n"
"}\n"
);
}
/// <summary>
/// Test code generation for function call nodes.
/// </summary>
TEST_F(C_CodegenTests, callCodegen)
{
EXPECT_RUN_OK("call1",
"function double(a:int):int {\n"
" a * 2\n"
"}\n"
"function doNothing() {\n"
" return;\n"
"}\n"
"function divide(a:int, b:int):(q:int, r:int) {\n"
" (a/b, a%b)\n"
"}\n"
"function test ():int {\n"
" doNothing()\n"
" if (double(4) != 8) return 1\n"
" if (divide(17, 5).q != 3) return 2\n"
" if (divide(30, 5).r != 0) return 3\n"
" \n"
" return 0\n"
"}\n"
);
}
/// <summary>
/// Test code generation for literal expressions.
/// Also tests 'varAccessCodegen'
/// </summary>
TEST_F(C_CodegenTests, literalCodegen)
{
EXPECT_RUN_OK("literal1",
"function test ():int {\n"
" var x:int\n"
" x = 3\n"
" 7\n"
" x\n"
" if (x!=3) return 1\n"
" 0\n"
"}\n"
);
}
/// <summary>
/// Test code generation for prefix operators.
/// </summary>
TEST_F(C_CodegenTests, prefixOpCodegen)
{
EXPECT_RUN_OK("prefix1",
"function test ():int {\n"
" var x:int\n"
" var y:int\n"
" x = 3\n"
" y = -x\n"
" if ((x+y) != 0) return 1001\n"
" if (!((x+y) == 0)) return 1002\n"
" y = ++x\n"
" if (y != 4) return 1003\n"
" if (x != y) return 1031\n"
" x = --y\n"
" if ((x != 3) || (x != y)) return 1004\n"
" \n"
" ++y;\n"
" if (y != 4) return 1005\n"
" 0\n"
"}\n"
);
}
/// <summary>
/// Test code generation for postfix operators.
/// </summary>
TEST_F(C_CodegenTests, postfixOpCodegen)
{
EXPECT_RUN_OK("postfix1",
"function test ():int {\n"
" var x:int = 5\n"
" var y:int\n"
" y = x++\n"
" if (y != 5) return 1010\n"
" if (x != 6) return 1020\n"
" \n"
" x = y--\n"
" if (y != 4) return 1030\n"
" if (x != 5) return 1040\n"
" \n"
" ++y;\n"
" if (y != 5) return 1050\n"
" 0\n"
"}\n"
);
}
/// <summary>
/// Test actor code generation
/// </summary>
TEST_F(C_CodegenTests, DISABLED_actors)
{
//TODO: This test is disabled because code generation tests lack the infrastructure
//to run actors. Decide to create suck infrastructure, or test actor code generation
//with external tests.
EXPECT_RUN_OK("actors1",
"actor Test {\n"
" output o1(int)\n"
" input i1(a: int) {o1(a * 2)}\n"
"}\n"
);
}
| 26.559426
| 126
| 0.505671
|
GuillermoHernan
|
b90f7ecd38578fe8fd5de93ffdebca63eb03daa9
| 1,542
|
cpp
|
C++
|
leetcode/Algorithms/available-captures-for-rook.cpp
|
Doarakko/competitive-programming
|
5ae78c501664af08a3f16c81dbd54c68310adec8
|
[
"MIT"
] | 1
|
2017-07-11T16:47:29.000Z
|
2017-07-11T16:47:29.000Z
|
leetcode/Algorithms/available-captures-for-rook.cpp
|
Doarakko/Competitive-Programming
|
10642a4bd7266c828dd2fc6e311284e86bdf2968
|
[
"MIT"
] | 1
|
2021-02-07T09:10:26.000Z
|
2021-02-07T09:10:26.000Z
|
leetcode/Algorithms/available-captures-for-rook.cpp
|
Doarakko/Competitive-Programming
|
10642a4bd7266c828dd2fc6e311284e86bdf2968
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int numRookCaptures(vector<vector<char>>& board) {
// search rook
int x, y;
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[0].size(); j++){
if(board[i][j] == 'R'){
x = j;
y = i;
}
}
}
int cnt = 0;
// top
for(int i = y - 1; i >= 0; i--){
if(board[i][x] == 'p'){
cnt++;
break;
}else if(board[i][x] == '.'){
continue;
}else{
break;
}
}
// bottom
for(int i = y + 1; i < board.size(); i++){
if(board[i][x] == 'p'){
cnt++;
break;
}else if(board[i][x] == '.'){
continue;
}else{
break;
}
}
// left
for(int i = x - 1; i >= 0; i--){
if(board[y][i] == 'p'){
cnt++;
break;
}else if(board[y][i] == '.'){
continue;
}else{
break;
}
}
// right
for(int i = x + 1; i < board[0].size(); i++){
if(board[y][i] == 'p'){
cnt++;
break;
}else if(board[y][i] == '.'){
continue;
}else{
break;
}
}
return cnt;
}
};
| 24.870968
| 54
| 0.270428
|
Doarakko
|
b9114f53a4edef347073818413904c0a12028c20
| 2,005
|
cpp
|
C++
|
src/ripple/protocol/impl/Issue.cpp
|
yinchengtsinghua/RippleCPPChinese
|
a32a38a374547bdc5eb0fddcd657f45048aaad6a
|
[
"BSL-1.0"
] | 5
|
2019-01-23T04:36:03.000Z
|
2020-02-04T07:10:39.000Z
|
src/ripple/protocol/impl/Issue.cpp
|
yinchengtsinghua/RippleCPPChinese
|
a32a38a374547bdc5eb0fddcd657f45048aaad6a
|
[
"BSL-1.0"
] | null | null | null |
src/ripple/protocol/impl/Issue.cpp
|
yinchengtsinghua/RippleCPPChinese
|
a32a38a374547bdc5eb0fddcd657f45048aaad6a
|
[
"BSL-1.0"
] | 2
|
2019-05-14T07:26:59.000Z
|
2020-06-15T07:25:01.000Z
|
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/*
此文件是Rippled的一部分:https://github.com/ripple/rippled
版权所有(c)2012,2013 Ripple Labs Inc.
使用、复制、修改和/或分发本软件的权限
特此授予免费或不收费的目的,前提是
版权声明和本许可声明出现在所有副本中。
本软件按“原样”提供,作者不作任何保证。
关于本软件,包括
适销性和适用性。在任何情况下,作者都不对
任何特殊、直接、间接或后果性损害或任何损害
因使用、数据或利润损失而导致的任何情况,无论是在
合同行为、疏忽或其他侵权行为
或与本软件的使用或性能有关。
**/
//==============================================================
#include <ripple/protocol/Issue.h>
namespace ripple {
bool
isConsistent (Issue const& ac)
{
return isXRP (ac.currency) == isXRP (ac.account);
}
std::string
to_string (Issue const& ac)
{
if (isXRP (ac.account))
return to_string (ac.currency);
return to_string(ac.account) + "/" + to_string(ac.currency);
}
std::ostream&
operator<< (std::ostream& os, Issue const& x)
{
os << to_string (x);
return os;
}
/*有序比较。
资产先按货币订购,然后按账户订购。
如果货币不是XRP。
**/
int
compare (Issue const& lhs, Issue const& rhs)
{
int diff = compare (lhs.currency, rhs.currency);
if (diff != 0)
return diff;
if (isXRP (lhs.currency))
return 0;
return compare (lhs.account, rhs.account);
}
/*平等比较。*/
/*@ {*/
bool
operator== (Issue const& lhs, Issue const& rhs)
{
return compare (lhs, rhs) == 0;
}
bool
operator!= (Issue const& lhs, Issue const& rhs)
{
return ! (lhs == rhs);
}
/*@ }*/
/*严格的弱排序。*/
/*@ {*/
bool
operator< (Issue const& lhs, Issue const& rhs)
{
return compare (lhs, rhs) < 0;
}
bool
operator> (Issue const& lhs, Issue const& rhs)
{
return rhs < lhs;
}
bool
operator>= (Issue const& lhs, Issue const& rhs)
{
return ! (lhs < rhs);
}
bool
operator<= (Issue const& lhs, Issue const& rhs)
{
return ! (rhs < lhs);
}
} //涟漪
| 17.743363
| 114
| 0.583541
|
yinchengtsinghua
|
b918d115b957255720f7138fa9c2839a7c379849
| 10,057
|
cpp
|
C++
|
sdbq_parser/sdbq_parser/sdbq_parser.cpp
|
w1n5t0n99/SdbqParser
|
d92f21bebbaaf02028b40b73f052198eb2c11858
|
[
"MIT"
] | null | null | null |
sdbq_parser/sdbq_parser/sdbq_parser.cpp
|
w1n5t0n99/SdbqParser
|
d92f21bebbaaf02028b40b73f052198eb2c11858
|
[
"MIT"
] | null | null | null |
sdbq_parser/sdbq_parser/sdbq_parser.cpp
|
w1n5t0n99/SdbqParser
|
d92f21bebbaaf02028b40b73f052198eb2c11858
|
[
"MIT"
] | null | null | null |
#include "sdbq_parser.h"
#include <algorithm>
#include <iostream>
#include <unordered_set>
#include <map>
#include "csv.h"
namespace sdbq
{
struct QuestionDescriptorHasher
{
size_t operator() (const Question& val) const { return std::hash<std::string>()(val.descriptor+val.difficulty); }
};
struct QuestionDescriptorComparer
{
bool operator() (const Question& lhs, const Question& rhs) const { return (lhs.descriptor == rhs.descriptor) & (lhs.difficulty == rhs.difficulty); };
};
struct QuestionTestHasher
{
size_t operator() (const Question& val) const { return std::hash<std::string>()(val.test_name); }
};
struct QuestionTestComparer
{
bool operator() (const Question& lhs, const Question& rhs) const { return lhs.test_name == rhs.test_name; };
};
struct QuestionGradeHasher
{
size_t operator() (const Question& val) const { return std::hash<std::string>()(val.grade); }
};
struct QuestionGradeComparer
{
bool operator() (const Question& lhs, const Question& rhs) const { return lhs.grade == rhs.grade; };
};
std::optional<std::vector<Question>> ParseSdbq(std::string file_name, int count_estimate)
{
std::vector<Question> questions;
questions.reserve(count_estimate);
try
{
io::CSVReader<12, typename io::trim_chars<' ', '\t'>, typename io::double_quote_escape<',', '\"'> > in(file_name);
in.read_header(io::ignore_extra_column,
"Last Name",
"First Name",
"MI",
"Grade",
"Div Name",
"Sch Name",
"Group Name",
"Test",
"Retest",
"Item Descriptor",
"Item Difficulty",
"Response");
//child
std::string last_name = {};
std::string first_name = {};
std::string middle_initial = {};
// question
std::string item_descriptor = {};
item_descriptor.reserve(100);
std::string response = {};
std::string difficulty = {};
// location
std::string division_name = {};
std::string school_name = {};
std::string grade_str = {};
std::string test_name = {};
std::string retest = {};
std::string group_name = {};
while (in.read_row(
last_name,
first_name,
middle_initial,
grade_str,
division_name,
school_name,
group_name,
test_name,
retest,
item_descriptor,
difficulty,
response))
{
// append quotes on descriptor
item_descriptor.push_back('\"');
item_descriptor.insert(0, 1, '\"');
questions.push_back({grade_str, test_name, retest, group_name, response,
difficulty,item_descriptor,last_name,first_name,
middle_initial, division_name, school_name });
}
}
catch (io::error::can_not_open_file& err)
{
return {};
}
return questions;
}
std::optional<std::vector<ResultStats>> ParseResults(std::string file_name, int count_estimate)
{
std::vector<ResultStats> stats;
stats.reserve(count_estimate);
try
{
io::CSVReader<6, typename io::trim_chars<' ', '\t'>, typename io::double_quote_escape<',', '\"'> > in(file_name);
in.read_header(io::ignore_extra_column,
"descriptor",
"difficulty",
"total correct",
"total incorrect",
"unique correct",
"unique incorrect");
std::string descriptor = {};
descriptor.reserve(100);
std::string difficulty = {};
int total_correct = {};
int total_incorrect = {};
int unique_correct = {};
int unique_incorrect = {};
while (in.read_row(
descriptor,
difficulty,
total_correct,
total_incorrect,
unique_correct,
unique_incorrect))
{
// append quotes on descriptor
descriptor.push_back('\"');
descriptor.insert(0, 1, '\"');
stats.push_back({ difficulty, descriptor, total_correct, total_incorrect, unique_correct, unique_incorrect });
}
}
catch (io::error::can_not_open_file& err)
{
return {};
}
return stats;
}
std::vector<std::string> GetUniqueGrades(const std::vector<Question>& questions)
{
std::unordered_set<Question, QuestionGradeHasher, QuestionGradeComparer> unq_questions;
for (const auto& q : questions)
unq_questions.insert(q);
std::vector<std::string> unq_questions_vec;
unq_questions_vec.reserve(unq_questions.size());
std::for_each(unq_questions.begin(), unq_questions.end(), [&](const auto& q) {unq_questions_vec.push_back(q.grade); });
return unq_questions_vec;
}
std::vector<std::string> GetUniqueTests(const std::vector<Question>& questions)
{
std::unordered_set<Question, QuestionTestHasher, QuestionTestComparer> unq_questions;
for (const auto& q : questions)
unq_questions.insert(q);
std::vector<std::string> unq_questions_vec;
unq_questions_vec.reserve(unq_questions.size());
std::for_each(unq_questions.begin(), unq_questions.end(), [&](const auto& q) {unq_questions_vec.push_back(q.test_name); });
return unq_questions_vec;
}
std::vector<std::pair<std::string, std::vector<Question>>> GetUniqueTestsAndQuestions(const std::vector<Question>& questions)
{
std::map<std::string, std::vector<Question>> tests_map;
for (const auto& q : questions)
tests_map[q.test_name].push_back(q);
std::vector<std::pair<std::string, std::vector<Question>>> tests;
for (auto& t : tests_map)
tests.push_back(std::make_pair(std::move(t.first), std::move(t.second)));
return tests;
}
std::vector<std::string> GetUniqueDescriptors(const std::vector<Question>& questions)
{
std::unordered_set<Question, QuestionDescriptorHasher, QuestionDescriptorComparer> unq_questions;
for (const auto& q : questions)
unq_questions.insert(q);
std::vector<std::string> unq_questions_vec;
unq_questions_vec.reserve(unq_questions.size());
std::for_each(unq_questions.begin(), unq_questions.end(), [&](const auto& q) {unq_questions_vec.push_back(q.descriptor); });
return unq_questions_vec;
}
std::vector<Question> GetGradeQuestions(const std::vector<Question>& questions, std::string_view grade)
{
std::vector<Question> grade_questions;
auto it = questions.begin();
auto end = questions.end();
while (it != end)
{
it = std::find_if(it, end, [&](const auto& val) { return val.grade == grade; });
if (it != end)
{
grade_questions.push_back(*it);
it++;
}
}
return grade_questions;
}
std::vector<Question> GetTestQuestions(const std::vector<Question>& questions, std::string_view test_name)
{
std::vector<Question> test_questions;
auto it = questions.begin();
auto end = questions.end();
while (it != end)
{
it = std::find_if(it, end, [&](const auto& val) { return val.test_name == test_name; });
if (it != end)
{
test_questions.push_back(*it);
it++;
}
}
return test_questions;
}
std::vector<QuestionStats> GetQuestionStats(const std::vector<Question>& questions)
{
std::vector<QuestionStats> question_stats;
// map the descriptor and difficulty to students
std::map<std::pair<std::string, std::string>, std::vector<Question>> descriptors;
for (const auto& q : questions)
{
descriptors[{q.descriptor, q.difficulty}].push_back(q);
}
for (const auto& [d, qs] : descriptors)
{
QuestionStats stats;
stats.descriptor = d.first;
stats.difficulty = d.second;
std::map<Student, std::string> unique_students;
for (const auto& q : qs)
{
const auto& res = q.response;
Student student = { q.first_name, q.last_name };
if (res == "COR")
{
stats.total_correct.push_back(student);
// we want to update an existing key to correct
unique_students[student] = res;
}
else
{
stats.total_incorrect.push_back(student);
// we dont want to change an existing key to incorrect
unique_students.insert({ student, res });
}
}
for (const auto& s : unique_students)
{
if(s.second == "COR")
stats.unique_correct.push_back(s.first);
else
stats.unique_incorrect.push_back(s.first);
}
//std::replace(stats.descriptor.begin(), stats.descriptor.end(), ',', ';');
question_stats.push_back(stats);
}
return question_stats;
}
std::vector<QuestionStats> MergeQuestionStats(const std::vector<QuestionStats>& stats0, const std::vector<QuestionStats>& stats1)
{
std::vector<QuestionStats> merged_questions;
std::map<std::pair<std::string, std::string>, QuestionStats> question_map;
for (const auto& q : stats0)
question_map.insert({ {q.descriptor, q.difficulty}, q });
for (const auto& q : stats1)
{
auto& [it, success] = question_map.insert({ { q.descriptor, q.difficulty }, q });
if (!success)
{
auto& merged_total_correct = it->second.total_correct;
merged_total_correct.insert(merged_total_correct.end(), q.total_correct.begin(), q.total_correct.end());
auto& merged_total_incorrect = it->second.total_incorrect;
merged_total_incorrect.insert(merged_total_incorrect.end(), q.total_incorrect.begin(), q.total_incorrect.end());
auto& merged_unique_correct = it->second.unique_correct;
merged_unique_correct.insert(merged_unique_correct.end(), q.unique_correct.begin(), q.unique_correct.end());
auto& merged_unique_incorrect = it->second.unique_incorrect;
merged_unique_incorrect.insert(merged_unique_incorrect.end(), q.unique_incorrect.begin(), q.unique_incorrect.end());
}
}
for (auto& s : question_map)
merged_questions.push_back(std::move(s.second));
return merged_questions;
}
void MergeResults(std::vector<ResultStats>& total_stats, const std::vector<ResultStats>& stats)
{
std::map<std::pair<std::string, std::string>, ResultStats> result_map;
for (const auto& s : total_stats)
result_map.insert({ { s.descriptor, s.difficulty }, s });
for (const auto& s : stats)
{
auto&[it, success] = result_map.insert({ {s.descriptor, s.difficulty}, s });
if (!success)
{
it->second.total_correct += s.total_correct;
it->second.total_incorrect += s.total_incorrect;
it->second.unique_correct += s.unique_correct;
it->second.unique_incorrect += s.unique_incorrect;
}
}
total_stats.clear();
for (auto& r : result_map)
total_stats.push_back(std::move(r.second));
}
}
| 26.60582
| 151
| 0.68062
|
w1n5t0n99
|
2c6e45870f582585cab579c82f1d9d0d79fcf9f5
| 3,387
|
cpp
|
C++
|
Nesis/Nesis/src/NesisBrowser.cpp
|
jpoirier/x-gauges
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
[
"BSD-3-Clause"
] | 3
|
2015-11-08T07:17:46.000Z
|
2019-04-05T17:08:05.000Z
|
Nesis/Nesis/src/NesisBrowser.cpp
|
jpoirier/x-gauges
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
[
"BSD-3-Clause"
] | null | null | null |
Nesis/Nesis/src/NesisBrowser.cpp
|
jpoirier/x-gauges
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
[
"BSD-3-Clause"
] | null | null | null |
/***************************************************************************
* *
* Copyright (C) 2007 by Kanardia d.o.o. [see www.kanardia.eu] *
* Writen by: *
* Ales Krajnc [ales.krajnc@kanardia.eu] *
* *
* Status: Open Source *
* *
* License: GPL - GNU General Public License *
* See 'COPYING.html' for more details about the license. *
* *
***************************************************************************/
#include <QtDebug>
#include <QtGui>
#include "NesisBrowser.h"
// -----------------------------------------------------------------------
NesisBrowser::NesisBrowser(QWidget *pParent)
: QTextBrowser(pParent)
{
}
// -----------------------------------------------------------------------
NesisBrowser::~NesisBrowser()
{
}
// -----------------------------------------------------------------------
bool NesisBrowser::HandleNesisInputEvent(PanelButton ePB)
{
switch(ePB) {
// Back button
case pbBtn1: backward(); break;
// Forward button
case pbBtn2: forward(); break;
// Page Down button
case pbBtn3:
qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_PageDown, Qt::NoModifier));
break;
// Page Up button
case pbBtn4:
qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_PageUp, Qt::NoModifier));
break;
// Go to next link Knob CW = clockwise
case pbKnobCW:
qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier));
break;
// Knob CCW = counterclockwise
case pbKnobCCW:
qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Tab, Qt::ShiftModifier));
break;
// OK button was pressed
case pbOk:
qApp->postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier));
break;
// Cancel button was pressed
case pbCancel:
emit NesisCancel();
break;
// Not handled here - forward this to interested objects.
default:
emit NesisButton(ePB-pbBtn1);
break;
}
return true;
}
// -----------------------------------------------------------------------
QStringList NesisBrowser::GetButtonLabels() const
{
QStringList sl;
sl << tr("Back");
sl << tr("Forward");
sl << tr("Pg Down");
sl << tr("Pg Up");
return sl;
}
// -----------------------------------------------------------------------
void NesisBrowser::focusInEvent(QFocusEvent* pEvent)
{
// Call base class handler.
QTextBrowser::focusInEvent(pEvent);
ShowButtons(true);
}
// -----------------------------------------------------------------------
void NesisBrowser::focusOutEvent(QFocusEvent* pEvent)
{
if(pEvent->reason() == Qt::TabFocusReason || pEvent->reason() == Qt::BacktabFocusReason) {
// FIXME The following line may be causing problems.
setFocus(Qt::OtherFocusReason);
return;
}
QTextBrowser::focusOutEvent(pEvent);
HideButtons();
}
// -----------------------------------------------------------------------
| 29.710526
| 92
| 0.446118
|
jpoirier
|
2c6e46b7e07f7e232d9c0143b0f11f767452969a
| 447
|
hpp
|
C++
|
include/Sprite/Wall.hpp
|
VisualGMQ/Chaos_Dungeon
|
95f9b23934ee16573bf9289b9171958f750ffc93
|
[
"MIT"
] | 2
|
2020-05-05T13:31:55.000Z
|
2022-01-16T15:38:00.000Z
|
include/Sprite/Wall.hpp
|
VisualGMQ/Chaos_Dungeon
|
95f9b23934ee16573bf9289b9171958f750ffc93
|
[
"MIT"
] | null | null | null |
include/Sprite/Wall.hpp
|
VisualGMQ/Chaos_Dungeon
|
95f9b23934ee16573bf9289b9171958f750ffc93
|
[
"MIT"
] | 1
|
2021-11-27T02:32:24.000Z
|
2021-11-27T02:32:24.000Z
|
#ifndef WALL_HPP
#define WALL_HPP
#include "Sprite.hpp"
#include "Collision.hpp"
#include "Colliable.hpp"
#include "ColliSystem.hpp"
#include "Texture.hpp"
class Wall : public ColliableSprite{
public:
static Wall* Create();
void Init() override;
int Width() const;
int Height() const;
~Wall();
private:
Wall();
Vec topleft() const;
void update() override;
void draw() override;
Texture texture;
};
#endif
| 17.88
| 36
| 0.666667
|
VisualGMQ
|
2c6e74a9e357f3bf89c4ce9ba98b700eeb860dce
| 992
|
hpp
|
C++
|
src/micromamba/info.hpp
|
pbauwens-kbc/mamba
|
243bf801e99fc2215f88fd87c66574aeb85a52e9
|
[
"BSD-3-Clause"
] | null | null | null |
src/micromamba/info.hpp
|
pbauwens-kbc/mamba
|
243bf801e99fc2215f88fd87c66574aeb85a52e9
|
[
"BSD-3-Clause"
] | null | null | null |
src/micromamba/info.hpp
|
pbauwens-kbc/mamba
|
243bf801e99fc2215f88fd87c66574aeb85a52e9
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2019, QuantStack and Mamba Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#ifndef UMAMBA_INFO_HPP
#define UMAMBA_INFO_HPP
#include "mamba/context.hpp"
#ifdef VENDORED_CLI11
#include "mamba/CLI.hpp"
#else
#include <CLI/CLI.hpp>
#endif
#include <string>
#include <tuple>
#include <vector>
const char banner[] = R"MAMBARAW(
__
__ ______ ___ ____ _____ ___ / /_ ____ _
/ / / / __ `__ \/ __ `/ __ `__ \/ __ \/ __ `/
/ /_/ / / / / / / /_/ / / / / / / /_/ / /_/ /
/ .___/_/ /_/ /_/\__,_/_/ /_/ /_/_.___/\__,_/
/_/
)MAMBARAW";
void
init_info_parser(CLI::App* subcom);
void
set_info_command(CLI::App* subcom);
void
load_info_options(mamba::Context& ctx);
void
info_pretty_print(std::vector<std::tuple<std::string, std::vector<std::string>>> map);
std::string
version();
#endif
| 20.666667
| 86
| 0.607863
|
pbauwens-kbc
|
2c70e4268ed74f579b99de7c886ecc0d7b0d8723
| 2,003
|
cpp
|
C++
|
Algorithms/0088.MergeSortedArray/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
Algorithms/0088.MergeSortedArray/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
Algorithms/0088.MergeSortedArray/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
#include <queue>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
void merge(std::vector<int>& nums1, int m, std::vector<int> const &nums2, int n)
{
const size_t size1 = m;
const size_t size2 = n;
std::queue<int> nums1Queue;
size_t index2 = 0;
// merge from nums1, nums2 and nums1Queue into [0, m - 1] range
for (size_t index1 = 0; index1 < size1; ++index1)
{
if (index2 < size2 && nums2[index2] < nums1[index1] && (nums1Queue.empty() || nums2[index2] < nums1Queue.front()))
{
nums1Queue.push(nums1[index1]);
nums1[index1] = nums2[index2++];
}
else if (!nums1Queue.empty())
{
nums1Queue.push(nums1[index1]);
nums1[index1] = nums1Queue.front();
nums1Queue.pop();
}
}
// merge from nums2 and nums1Queue into [m, m + n - 1] range
for (size_t index1 = m; index1 < size1 + size2; ++index1)
{
if (nums1Queue.empty() || (index2 < size2 && nums2[index2] < nums1Queue.front()))
nums1[index1] = nums2[index2++];
else
{
nums1[index1] = nums1Queue.front();
nums1Queue.pop();
}
}
}
};
}
namespace
{
void checkMerge(std::vector<int> &&nums1, int m, std::vector<int> const &nums2, int n, std::vector<int> const &expectedResult)
{
std::vector<int> data(nums1);
Solution solution;
solution.merge(data, m, nums2, n);
ASSERT_EQ(expectedResult, data);
}
}
namespace MergeSortedArrayTask
{
TEST(MergeSortedArrayTaskTests, Examples)
{
checkMerge({1, 2, 3, 0, 0, 0}, 3, {2, 5, 6}, 3, {1, 2, 2, 3, 5, 6});
}
TEST(MergeSortedArrayTaskTests, FromWrongAnswers)
{
checkMerge({1}, 1, {}, 0, {1});
checkMerge({2, 0}, 1, {1}, 1, {1, 2});
checkMerge({1, 2, 4, 5, 6, 0}, 5, {3}, 1, {1, 2, 3, 4, 5, 6});
}
}
| 26.012987
| 126
| 0.529206
|
stdstring
|
2c7234a4936f1166cc531c5961dc59e848b59b0a
| 2,657
|
cc
|
C++
|
cartographer_ros/cartographer_ros/node_options.cc
|
athtest800/cartographer
|
566899786d21f11ceeb8b4d51d6a53eca73c4058
|
[
"Apache-2.0"
] | null | null | null |
cartographer_ros/cartographer_ros/node_options.cc
|
athtest800/cartographer
|
566899786d21f11ceeb8b4d51d6a53eca73c4058
|
[
"Apache-2.0"
] | null | null | null |
cartographer_ros/cartographer_ros/node_options.cc
|
athtest800/cartographer
|
566899786d21f11ceeb8b4d51d6a53eca73c4058
|
[
"Apache-2.0"
] | 1
|
2019-07-11T01:12:15.000Z
|
2019-07-11T01:12:15.000Z
|
/*
* Copyright 2016 The Cartographer 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 "cartographer_ros/node_options.h"
#include "glog/logging.h"
namespace cartographer_ros {
NodeOptions CreateNodeOptions(
::cartographer::common::LuaParameterDictionary* const
lua_parameter_dictionary) {
NodeOptions options;
options.map_builder_options =
::cartographer::mapping::CreateMapBuilderOptions(
lua_parameter_dictionary->GetDictionary("map_builder").get());
options.map_frame = lua_parameter_dictionary->GetString("map_frame");
options.tracking_frame =
lua_parameter_dictionary->GetString("tracking_frame");
options.published_frame =
lua_parameter_dictionary->GetString("published_frame");
options.odom_frame = lua_parameter_dictionary->GetString("odom_frame");
options.provide_odom_frame =
lua_parameter_dictionary->GetBool("provide_odom_frame");
options.use_odometry = lua_parameter_dictionary->GetBool("use_odometry");
options.use_laser_scan = lua_parameter_dictionary->GetBool("use_laser_scan");
options.use_multi_echo_laser_scan =
lua_parameter_dictionary->GetBool("use_multi_echo_laser_scan");
options.num_point_clouds =
lua_parameter_dictionary->GetNonNegativeInt("num_point_clouds");
options.lookup_transform_timeout_sec =
lua_parameter_dictionary->GetDouble("lookup_transform_timeout_sec");
options.submap_publish_period_sec =
lua_parameter_dictionary->GetDouble("submap_publish_period_sec");
options.pose_publish_period_sec =
lua_parameter_dictionary->GetDouble("pose_publish_period_sec");
CHECK_EQ(options.use_laser_scan + options.use_multi_echo_laser_scan +
(options.num_point_clouds > 0),
1)
<< "Configuration error: 'use_laser_scan', "
"'use_multi_echo_laser_scan' and 'num_point_clouds' are "
"mutually exclusive, but one is required.";
if (options.map_builder_options.use_trajectory_builder_2d()) {
// Using point clouds is only supported in 3D.
CHECK_EQ(options.num_point_clouds, 0);
}
return options;
}
} // namespace cartographer_ros
| 40.257576
| 79
| 0.75988
|
athtest800
|
2c73d6ed1bffe930c21c219d4bb3ac91bc8dbbd9
| 905
|
cpp
|
C++
|
006/main.cpp
|
Ponz-Tofu-N/ModernCppChallengePractice
|
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
|
[
"MIT"
] | null | null | null |
006/main.cpp
|
Ponz-Tofu-N/ModernCppChallengePractice
|
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
|
[
"MIT"
] | null | null | null |
006/main.cpp
|
Ponz-Tofu-N/ModernCppChallengePractice
|
c2003fc180fc28448a3ff5b3e0f0c2788154af8c
|
[
"MIT"
] | null | null | null |
// 6. Abundant Numbers
// Usage: Enter max number
#include <iostream>
#include <cmath>
#include <string>
int main(int argc, char const *argv[])
{
std::cout << "input max number: ";
unsigned int max; std::cin >> max;
/*pick a num*/
/*sum divisors*/
/*print if abundant num and its abundance*/
for (size_t i = max; i > 1; i--)
{
unsigned int sum = 0;
const unsigned int limit = static_cast<unsigned int>(std::sqrt(i));
for (size_t j = 1; j <= limit; j++)
{
if(i % j == 0){
sum += j;
}
}
if (sum > i)
{
std::cout << "AbundantNum: "
<< i << " "
<< "Abundant: "
<< sum - i * 2
<< "\n";
}
}
return 0;
}
| 22.073171
| 76
| 0.390055
|
Ponz-Tofu-N
|
2c74542b046b20d23af5c42548f57bc40a88334f
| 5,842
|
cc
|
C++
|
Engine/foundation/io/memoryreader.cc
|
BikkyS/DreamEngine
|
47da4e22c65188c72f44591f6a96505d8ba5f5f3
|
[
"MIT"
] | 26
|
2015-01-15T12:57:40.000Z
|
2022-02-16T10:07:12.000Z
|
Engine/foundation/io/memoryreader.cc
|
BikkyS/DreamEngine
|
47da4e22c65188c72f44591f6a96505d8ba5f5f3
|
[
"MIT"
] | null | null | null |
Engine/foundation/io/memoryreader.cc
|
BikkyS/DreamEngine
|
47da4e22c65188c72f44591f6a96505d8ba5f5f3
|
[
"MIT"
] | 17
|
2015-02-18T07:51:31.000Z
|
2020-06-01T01:10:12.000Z
|
/****************************************************************************
Copyright (c) 2006, Radon Labs GmbH
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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 "stdneb.h"
#include "io/memoryreader.h"
#include "math/scalar.h"
namespace IO
{
__ImplementClass(IO::MemoryReader, 'MMRD', IO::Stream);
//------------------------------------------------------------------------------
/**
*/
MemoryReader::MemoryReader() :
capacity(0),
size(0),
position(0),
buffer(NULL)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
MemoryReader::~MemoryReader()
{
// close the stream if still open
if (this->IsOpen())
{
this->Close();
}
// release memory buffer if allocated
if ( NULL != this->buffer)
this->buffer = NULL;
}
//------------------------------------------------------------------------------
Stream::Size
MemoryReader::GetSize() const
{
return this->size;
}
//------------------------------------------------------------------------------
Stream::Position
MemoryReader::GetPosition() const
{
return this->position;
}
//------------------------------------------------------------------------------
bool MemoryReader::Open()
{
n_assert(!this->IsOpen());
// nothing to do here, allocation happens in the first Write() call
// if necessary, all we do is reset the read/write position to the
// beginning of the stream
if (Stream::Open())
{
this->position = 0;
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
Close the stream. The contents of the stream will remain intact until
destruction of the object, so that the same data may be accessed
or modified during a later session.
*/
void
MemoryReader::Close()
{
n_assert(this->IsOpen());
Stream::Close();
}
//------------------------------------------------------------------------------
/**
*/
void
MemoryReader::Write(const void* ptr, Size numBytes)
{
n_assert(this->IsOpen());
n_assert(ReadWriteAccess == this->accessMode);
n_assert((this->position >= 0) && (this->position <= this->size));
buffer = (unsigned char*)ptr;
size = numBytes;
capacity = numBytes;
this->position += numBytes;
if (this->position > this->size)
{
this->size = this->position;
}
}
//------------------------------------------------------------------------------
/**
*/
Stream::Size
MemoryReader::Read(void* ptr, Size numBytes)
{
n_assert(this->IsOpen());
n_assert((ReadWriteAccess == this->accessMode))
n_assert((this->position >= 0) && (this->position <= this->size));
// check if end-of-stream is near
Size readBytes = numBytes <= this->size - this->position ? numBytes : this->size - this->position;
n_assert((this->position + readBytes) <= this->size);
if (readBytes > 0)
{
Memory::Copy(this->buffer + this->position, ptr, readBytes);
this->position += readBytes;
}
return readBytes;
}
//------------------------------------------------------------------------------
/**
*/
void
MemoryReader::Seek(Offset offset, SeekOrigin origin)
{
n_assert(this->IsOpen());
n_assert(!this->IsMapped());
n_assert((this->position >= 0) && (this->position <= this->size));
switch (origin)
{
case Begin:
this->position = offset;
break;
case Current:
this->position += offset;
break;
case End:
this->position = this->size + offset;
break;
}
// make sure read/write position doesn't become invalid
this->position = Math::n_iclamp(this->position, 0, this->size);
}
//------------------------------------------------------------------------------
/**
*/
bool
MemoryReader::Eof() const
{
n_assert(this->IsOpen());
n_assert((this->position >= 0) && (this->position <= this->size));
return (this->position == this->size);
}
//------------------------------------------------------------------------------
/**
*/
bool
MemoryReader::HasRoom(Size numBytes) const
{
return ((this->position + numBytes) <= this->capacity);
}
//------------------------------------------------------------------------------
/**
Get a direct pointer to the raw data. This is a convenience method
and only works for memory streams.
NOTE: writing new data to the stream may/will result in an invalid
pointer, don't keep the returned pointer around between writes!
*/
void*
MemoryReader::GetRawPointer() const
{
n_assert( NULL != this->buffer );
return this->buffer;
}
} // namespace IO
| 28.778325
| 102
| 0.534235
|
BikkyS
|
2c77a65f0d36f156d472f93c2e9c568c65111e61
| 6,757
|
tcc
|
C++
|
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/array.tcc
|
Maastro-CDS-Imaging-Group/SQLite4Radiomics
|
e3a7afc181eec0fe04c18da00edc3772064e6758
|
[
"Apache-2.0"
] | null | null | null |
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/array.tcc
|
Maastro-CDS-Imaging-Group/SQLite4Radiomics
|
e3a7afc181eec0fe04c18da00edc3772064e6758
|
[
"Apache-2.0"
] | 6
|
2021-06-09T19:39:27.000Z
|
2021-09-30T16:41:40.000Z
|
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/array.tcc
|
Maastro-CDS-Imaging-Group/SQLite4Radiomics
|
e3a7afc181eec0fe04c18da00edc3772064e6758
|
[
"Apache-2.0"
] | null | null | null |
/*
20050125 ljz Added 'ReplaceAt()' to the 'Array' class
20100619 bcb Fix gcc4 warnings and improve speed.
20130429 lsp Corrected (unused) printf format string
20130812 mvh Removed non-thread safe caching of last value
Does not seem to affect speed, throughput remains
at 320 MB/s receive with 3 senders and receivers
in same dgate on 8-core machine
20131016 mvh Merged
*/
/****************************************************************************
Copyright (C) 1995, University of California, Davis
THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
THE SOFTWARE IS WITH THE USER.
Copyright of the software and supporting documentation is
owned by the University of California, and free access
is hereby granted as a license to use this software, copy this
software and prepare derivative works based upon this software.
However, any distribution of this software source code or
supporting documentation or derivative works (source code and
supporting documentation) must include this copyright notice.
****************************************************************************/
/***************************************************************************
*
* University of California, Davis
* UCDMC DICOM Network Transport Libraries
* Version 0.1 Beta
*
* Technical Contact: mhoskin@ucdavis.edu
*
***************************************************************************/
/*
template <class DATATYPE>
Array<DATATYPE> :: Array ()
{
ArraySize = 0;
first = NULL;
last = NULL;
ClearType = 1;
}
*/
template <class DATATYPE>
Array<DATATYPE> :: Array (UINT CT)
#ifdef __GNUC__ //Faster with member initialization.
:first(NULL),
last(NULL),
//LastAccess(NULL),
//LastAccessNumber(0),
ArraySize(0),
ClearType(CT) {}
#else
{
ArraySize = 0;
first = NULL;
last = NULL;
//LastAccess = NULL;
//LastAccessNumber = 0;
ClearType = CT;
}
#endif
template <class DATATYPE>
Array<DATATYPE> :: ~Array()
{
if(ClearType == 1)
{
while(ArraySize)
RemoveAt(0);
}
}
template <class DATATYPE>
DATATYPE & Array<DATATYPE> :: Add(DATATYPE &Value)
{
// record current end-of-chain element
DataLink<DATATYPE> *dl = last;
// chain on new element at tail of chain
last = new DataLink<DATATYPE>;
last->Data = Value;
// set new element's backward pointer to point to former
// end-of-chain element
last->prev = dl;
// set former end-of-chain's next pointer to point to new element
if(dl)
{
dl->next = last;
}
else
{
// there was previously no "last" element so the one just
// allocated must be the first
first = last;
}
++ArraySize;
return ( Value );
}
template <class DATATYPE>
DATATYPE & Array<DATATYPE> :: Get(unsigned int Index)
{
DataLink<DATATYPE> *dl;
unsigned int rIndex = Index;
if ( Index >= ArraySize )
{
//fprintf(stderr, "Returning NULL Data\n");
//return ( NullData );
dl = NULL;
return ( (DATATYPE &) *dl ); // Invoke a seg fault
}
/*if ( LastAccess )
{
if ((LastAccessNumber + 1) == Index )
{
LastAccess = LastAccess->next;
++LastAccessNumber;
return ( LastAccess->Data );
}
}
*/
// locate requested element by following pointer chain
// decide which is faster -- scan from head or scan from tail
if(Index < ArraySize / 2)
{
// requested element closer to head -- scan forward
dl = first;
++Index;
while(--Index > 0)
{
dl = dl->next;
}
}
else
{
// requested element closer to tail -- scan backwards
dl = last;
Index = (ArraySize - Index);
while(--Index > 0)
{
dl = dl->prev;
}
}
//LastAccess = dl;
//LastAccessNumber = rIndex;
return ( dl->Data );
}
template <class DATATYPE>
DATATYPE & Array<DATATYPE> :: ReplaceAt(DATATYPE &Value, unsigned int Index)
{
DataLink<DATATYPE> *dl;
unsigned int rIndex = Index;
if ( Index >= ArraySize )
{
//fprintf(stderr, "Returning NULL Data\n");
//return ( NullData );
dl = NULL;
return ( (DATATYPE &) *dl ); // Invoke a seg fault
}
/*if ( LastAccess )
{
if ((LastAccessNumber + 1) == Index )
{
LastAccess = LastAccess->next;
++LastAccessNumber;
LastAccess->Data = Value;
return ( LastAccess->Data );
}
}
*/
// locate requested element by following pointer chain
// decide which is faster -- scan from head or scan from tail
if(Index < ArraySize / 2)
{
// requested element closer to head -- scan forward
dl = first;
++Index;
while(--Index > 0)
{
dl = dl->next;
}
}
else
{
// requested element closer to tail -- scan backwards
dl = last;
Index = (ArraySize - Index);
while(--Index > 0)
{
dl = dl->prev;
}
}
//LastAccess = dl;
//LastAccessNumber = rIndex;
dl->Data = Value;
return ( dl->Data );
}
template <class DATATYPE>
BOOL Array<DATATYPE> :: RemoveAt(unsigned int Index)
{
DataLink<DATATYPE> *dl;
//LastAccess = NULL;
//LastAccessNumber = 0;
if( Index >= ArraySize )
{
//fprintf(stderr, "Attempting to remove non-existance node\n");
//return ( NullData );
return( FALSE );
}
// follow pointer chain from head or tail to requested element
// depending upon which chain is shorter
if(Index < ArraySize / 2)
{
// element closer to head => follow chain forward from first
dl = first;
++Index;
while(--Index > 0)
{
dl = dl->next;
}
}
else
{
// element closer to tail => follow chain backward from last
dl = last;
Index = (ArraySize - Index);
while(--Index > 0)
{
dl = dl->prev;
}
}
// relink chain around element to be deleted
// fix first or last pointer if element to delete is first or last
if(dl->prev)
dl->prev->next = dl->next;
else
first = dl->next;
if(dl->next)
dl->next->prev = dl->prev;
else
last = dl->prev;
delete dl;
--ArraySize;
return ( TRUE );
}
/****************************************************************
* Test Functions
*
*
****************************************************************/
# ifdef BUILD_TEST_UNITS
int
testfunc()
{
unsigned int Index;
Array<int> AInt;
Index = 0;
while(Index < 10)
{
AInt.Add(Index * 2);
++Index;
}
Index = 0;
while(Index < 10)
{
printf("Val: %d : %d\n", Index, AInt.RemoveAt(0));
++Index;
}
return ( 0 );
}
int
main()
{
testfunc();
fprintf(stderr, "Display Should be like 'Val: x: 2*x' with x[0..9]\n");
}
# endif
| 20.537994
| 77
| 0.597159
|
Maastro-CDS-Imaging-Group
|
2c7b28cd370a850ec77649e471db05f1398aaa2e
| 138
|
hpp
|
C++
|
source/framework/algorithm/include/lue/framework/algorithm/definition/greater_than.hpp
|
computationalgeography/lue
|
71993169bae67a9863d7bd7646d207405dc6f767
|
[
"MIT"
] | 2
|
2021-02-26T22:45:56.000Z
|
2021-05-02T10:28:48.000Z
|
source/framework/algorithm/include/lue/framework/algorithm/definition/greater_than.hpp
|
pcraster/lue
|
e64c18f78a8b6d8a602b7578a2572e9740969202
|
[
"MIT"
] | 262
|
2016-08-11T10:12:02.000Z
|
2020-10-13T18:09:16.000Z
|
source/framework/algorithm/include/lue/framework/algorithm/definition/greater_than.hpp
|
computationalgeography/lue
|
71993169bae67a9863d7bd7646d207405dc6f767
|
[
"MIT"
] | 1
|
2020-03-11T09:49:41.000Z
|
2020-03-11T09:49:41.000Z
|
#pragma once
#include "lue/framework/algorithm/greater_than.hpp"
#include "lue/framework/algorithm/definition/binary_local_operation.hpp"
| 34.5
| 72
| 0.84058
|
computationalgeography
|
2c7eccb92b8799dde7d139354e501a01f7145075
| 13,600
|
cc
|
C++
|
src/common/time.cc
|
sergeyfilip/objectstore
|
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
|
[
"MIT"
] | null | null | null |
src/common/time.cc
|
sergeyfilip/objectstore
|
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
|
[
"MIT"
] | null | null | null |
src/common/time.cc
|
sergeyfilip/objectstore
|
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
|
[
"MIT"
] | null | null | null |
//
//! \file common/time.cc
//
//! Implementation of our time routines
//
// $Id: time.cc,v 1.17 2013/05/23 08:54:57 joe Exp $
//
#include "time.hh"
#include "error.hh"
#include "string.hh"
#include <vector>
#include <iomanip>
#include <istream>
#include <ostream>
#include <math.h>
#include <time.h>
#include <string.h>
#if defined(__unix__) || defined(__APPLE__)
# include <sys/time.h>
#endif
Time Time::now()
{
#if defined(__unix__) || defined(__APPLE__)
timeval tv;
if (gettimeofday(&tv,0))
throw syserror("gettimeofday", "retrieval of now");
return Time(tv.tv_sec,tv.tv_usec * 1000);
#endif
#if defined(_WIN32)
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME ft;
if (SystemTimeToFileTime(&st,&ft) == 0) {
std::cerr << "(TIME) Error getting system time " << std::endl;
std::cerr << "(TIME) This may cause inaccurate measurements "
<< std::endl;
};
/* tf holds a 64 bit time in it's 2 fields
the number represents 100-nanosecs. since jan. 1 1601
*/
uint64_t sec,nsec;
uint64_t offset = uint64_t(10000000)
* ((1970 - 1601) * 365 + 89) * 24 * 60 * 60;
uint64_t file_time = (uint64_t(ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
file_time -= offset;
sec = file_time / 10000000;
nsec = (file_time % 10000000) * 100;
return Time(sec, nsec);
#endif
}
#ifdef _WIN32
Time::Time(const FILETIME &ft)
: tim(0,0)
{
uint64_t offset = uint64_t(10000000)
* ((1970 - 1601) * 365 + 89) * 24 * 60 * 60;
uint64_t file_time = (uint64_t(ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
file_time -= offset;
tim.sec = file_time / 10000000;
tim.nsec = (file_time % 10000000) * 100;
}
FILETIME Time::toFileTime() const
{
FILETIME file_time;
uint64_t offset = uint64_t(10000000)
* ((1970 - 1601) * 365 + 89) * 24 * 60 * 60;
uint64_t nano_secs = uint64_t(tim.sec) * 10000000 + uint64_t(tim.nsec) + offset;
file_time.dwLowDateTime = DWORD(nano_secs);
file_time.dwHighDateTime = nano_secs >> 32;
return file_time;
}
#endif
#ifdef __unix__
struct timespec Time::toTimespec() const
{
struct timespec ret;
ret.tv_sec = tim.sec;
ret.tv_nsec = tim.nsec;
return ret;
}
#endif
double Time::to_double() const
{
return tim.sec + tim.nsec / 1E9;
}
//
// Utility stuff for the ISO8601 parser
//
namespace {
// Reads exactly d characters from stream and parses unsigned
// integer
unsigned readDigits(std::istream &i, size_t d)
{
std::vector<char> buf(d);
i.read(&buf[0], d);
if (i.eof())
throw error("ISO8601: Premature end of data while reading digits");
// Fine, now parse as integer
return string2Any<unsigned>(std::string(buf.begin(), buf.end()));
}
// Reads a single character and returns it
char getChar(std::istream &i)
{
if (i.eof())
throw error("ISO8601: End of stream before get");
char tmp;
i.get(tmp);
if (i.gcount() != 1)
throw error("ISO8601: Premature end of data while getting character");
return tmp;
}
// Reads a character and sees if it matches the test character. If
// it does, the function returns true. If it does not, it puts back
// the character onto the stream and returns false.
bool testChar(std::istream &i, char test)
{
char t = getChar(i);
if (t == test) return true;
i.putback(t);
return false;
}
// Reads a single character and expects it to match given character
void skipKnown(std::istream &i, char known)
{
char tmp;
i.get(tmp);
if (i.gcount() != 1)
throw error("ISO8601: Premature end of data while skipping character");
if (tmp != known)
throw error("ISO8601: Unexpected character while parsing");
}
// Reads a ISO8601 possibly-fractional number from the stream
double readFractional(std::istream &i)
{
// Read digits and accept both '.' and ',' as fraction
bool gotsome = false;
double res = 0;
size_t divider = 0;
while (true) {
char c = getChar(i);
if (c >= '0' && c <= '9') {
if (divider) {
res += (c - '0') / double(divider);
divider *= 10;
} else {
res *= 10;
res += c - '0';
}
gotsome = true;
continue;
}
if (!divider && (c == '.' || c == ',')) {
divider = 10;
gotsome = true;
continue;
}
// Ok, not a digit and not (first) fractional
i.putback(c);
break;
}
if (!gotsome)
throw error("ISO8601: Not a fractional");
return res;
}
}
#if defined(__sun__)
// Solaris doesn't have the GNU specific timegm function, so we
// implement it here using mktime() and gmtime(). Would be nice to
// have it static, but mktime_utc_test uses this function as well.
time_t timegm(struct tm* t)
{
time_t tl, tb;
struct tm* tg;
tl = mktime(t);
if (tl == -1)
return -1;
tg = gmtime(&tl);
if (!tg)
return -1;
tb = mktime(tg);
if (tb == -1)
return -1;
return (tl - (tb - tl));
}
#endif
std::istream &operator>>(std::istream &i, Time &o)
{
struct tm t;
memset(&t, 0, sizeof t);
// YYYY-MM-DD
t.tm_year = readDigits(i, 4) - 1900;
skipKnown(i, '-');
t.tm_mon = readDigits(i, 2) - 1;
skipKnown(i, '-');
t.tm_mday = readDigits(i, 2);
// T or space
{ char sep = getChar(i);
if (sep != 'T' && sep != ' ')
throw error("Unexpected separator between date and time");
}
// hh:mm:ss
t.tm_hour = readDigits(i, 2);
skipKnown(i, ':');
t.tm_min = readDigits(i, 2);
skipKnown(i, ':');
t.tm_sec = readDigits(i, 2);
// Optionally we have fractional seconds - ISO 8601 specifies that
// both ',' and '.' can be used to designate the fraction
char trailer = getChar(i);
do {
if (trailer != '.' && trailer != ',')
break;
// Good, we have fractional seconds... Fetch them and throw them
// away
do {
trailer = getChar(i);
} while (trailer >= '0' && trailer <= '9');
} while (false);
// Assume Zulu time - either 'Z' or '+00'
do {
if (trailer == 'Z') break;
if (trailer != '+')
throw error("Expected Z or +00");
skipKnown(i, '0');
skipKnown(i, '0');
} while (false);
// Just peek at the next character - this has the effect of
// setting eof if we are really at the eof.
i.peek();
// Fine, now convert
#if defined (__unix__) || defined(__APPLE__)
o = Time(timegm(&t));
#endif
#if defined(_WIN32)
o = Time(_mkgmtime(&t));
#endif
return i;
}
std::ostream &operator<<(std::ostream &s, const Time &ts)
{
struct tm t;
#if defined(__unix__) || defined(__APPLE__)
const time_t ut(ts.to_timet());
if (!gmtime_r(&ut, &t))
throw error("Cannot output time");
#endif
#if defined(_WIN32)
const time_t in(ts.to_timet());
if (gmtime_s(&t, &in))
throw error("Cannot output time");
#endif
s << std::setw(4) << std::setfill('0') << (t.tm_year + 1900)
<< "-"
<< std::setw(2) << std::setfill('0') << (t.tm_mon + 1)
<< "-"
<< std::setw(2) << std::setfill('0') << t.tm_mday
<< "T"
<< std::setw(2) << std::setfill('0') << t.tm_hour
<< ":"
<< std::setw(2) << std::setfill('0') << t.tm_min
<< ":"
<< std::setw(2) << std::setfill('0') << t.tm_sec
<< "Z";
return s;
}
const DiffTime Time::operator-(const Time& p2 ) const {
// This calculation will never overflow, as Time contains only
// positive values, whereas DiffTime allows the full signed scale.
time_internal::time_rec res(tim);
res.sec -= p2.tim.sec;
res.nsec -= p2.tim.nsec;
if (res.nsec < 0) {
res.sec--;
res.nsec += 1000000000;
}
if (res.nsec < 0)
throw error("Time difference subtraction gave negative nsec");
return res;
}
const Time Time::operator-(const DiffTime& p2 ) const
{
return Time(*this) -= p2.tim;
}
const Time Time::operator+(const DiffTime& p2 ) const
{
return Time(*this) += p2.tim;
}
Time& Time::operator+=(const DiffTime& p2 )
{
time_internal::time_rec res(tim);
res.sec += p2.tim.sec;
res.nsec += p2.tim.nsec;
if (res.nsec >= 1000000000) {
res.sec++;
res.nsec -= 1000000000;
}
if (res.nsec >= 1000000000)
throw error("Addition between non-normalized time and time difference");
// Check for overflows
if (p2.tim.sec >= 0) {
// Adding a positive value, res must have increased
if (res.sec < tim.sec) {
// sec has wrapped, clamp at END_OF_TIME
*this = END_OF_TIME;
}
} else {
// Adding a negative value, res must have decreased
if (res.sec > tim.sec) {
// sec has wrapped, clamp at BEGINNING_OF_TIME
*this = BEGINNING_OF_TIME;
}
}
tim = res;
return *this;
}
const Time Time::BEGINNING_OF_TIME(0, 0);
const Time Time::END_OF_TIME(0x7FFFFFFFFFFFFFFFLL, 0);
//
// Implementation of class DiffTime
//
DiffTime::DiffTime(const double& dt)
: tim(int64_t(floor(dt)), int64_t((dt - floor(dt)) * 1E9))
{
}
DiffTime::DiffTime(time_t dt)
: tim(dt, 0)
{
}
DiffTime::DiffTime(int64_t sec, int64_t nsec)
: tim(sec, nsec)
{
// If too many microseconds specified, add whole seconds to sec
// and let usec contain the microseconds.
if (tim.nsec >= 1000000000) {
const lldiv_t res = lldiv(tim.nsec, 1000000000);
tim.sec += res.quot;
tim.nsec = res.rem;
}
if (tim.nsec < 0)
throw error("Cannot normalize negative nanoseconds");
}
double DiffTime::to_double() const
{
return tim.sec + tim.nsec / 1E9;
}
void DiffTime::zeroIfNegative()
{
if (*this < DiffTime(0,0))
*this = DiffTime(0,0);
}
std::string DiffTime::toFormattedString() const
{
std::ostringstream out;
if (int64_t days = tim.sec / 60 / 60 / 24)
out << days << " days ";
if (int64_t hours = tim.sec / 60 / 60 % 24)
out << hours << " hours ";
if (int64_t minutes = tim.sec / 60 % 60)
out << minutes << " minutes ";
if (int64_t seconds = tim.sec % 60)
out << seconds << " seconds ";
return out.str();
}
const DiffTime DiffTime::operator-() const
{
if (tim.nsec) {
return DiffTime(-tim.sec - 1, 1000000000 - tim.nsec);
} else {
return DiffTime(-tim.sec, 0);
}
}
const DiffTime DiffTime::operator-(const DiffTime& p2 ) const
{
return DiffTime(*this) -= p2.tim;
}
const DiffTime DiffTime::operator+(const DiffTime& p2 ) const
{
return DiffTime(*this) += p2.tim;
}
DiffTime& DiffTime::operator-=(const DiffTime& p2 )
{
return *this += -p2;
}
DiffTime& DiffTime::operator+=(const DiffTime& p2 )
{
time_internal::time_rec res(tim);
res.sec += p2.tim.sec;
res.nsec += p2.tim.nsec;
if (res.nsec >= 1000000000) {
res.sec++;
res.nsec -= 1000000000;
}
if (res.nsec >= 1000000000)
throw error("Sum of non-normalized difftimes - nsec too big");
// Check for overflows
if (p2.tim.sec >= 0) {
// Adding a positive value, res must have increased
if (res.sec < tim.sec) {
// sec has wrapped, clamp at END_OF_TIME
*this = ENDLESS;
}
} else {
// Adding a negative value, res must have decreased
if (res.sec > tim.sec) {
// sec has wrapped, clamp at BEGINNING_OF_TIME
*this = -ENDLESS;
}
}
tim = res;
return *this;
}
DiffTime DiffTime::operator*(double scale) const
{
return DiffTime(this->to_double() * scale);
}
bool DiffTime::operator <(const DiffTime& p2) const {
return to_double() < p2.to_double();
}
bool DiffTime::operator >(const DiffTime& p2) const {
return p2 < *this;
}
bool DiffTime::operator <=(const DiffTime& p2) const {
return !(p2 < *this);
}
bool DiffTime::operator >=(const DiffTime& p2) const {
return !(*this < p2);
}
bool DiffTime::operator==(const DiffTime& p2) const
{
return tim.sec == p2.tim.sec
&& tim.nsec == p2.tim.nsec;
}
DiffTime DiffTime::iso(const std::string &iso)
{
std::istringstream i(iso);
DiffTime tmp;
i >> tmp;
return tmp;
}
const DiffTime DiffTime::SECOND(1, 0);
const DiffTime DiffTime::MSEC(0, 1000000);
const DiffTime DiffTime::USEC(0, 1000);
const DiffTime DiffTime::NSEC(0, 1);
const DiffTime DiffTime::ENDLESS(0x7FFFFFFFFFFFFFFFLL, 0);
std::istream &operator>>(std::istream &i, DiffTime &o)
{
double secs = 0;
bool gotsome = false;
if (getChar(i) != 'P')
throw error("Not a ISO8601 period designator");
// We may run into a 'T' - but until we do, we parse years, months
// and days.
while (true) {
// Read some number
double n;
try { n = readFractional(i); }
catch (error &) { break; }
gotsome = true;
// Get the designator
switch (char c = getChar(i)) {
case 'Y': secs += 365 * 24 * 3600 * n; break;
case 'M': secs += 30 * 24 * 3600 * n; break;
case 'D': secs += 24 * 3600 * n; break;
default:
throw error("Unexpected designator '"
+ std::string(1, c) + "' in left side of ISO 8601 period");
}
}
if (testChar(i, 'T')) {
// Fine, we got our T (or we failed reading the next
// fractional). Now read hours, minutes and seconds.
while (true) {
// Read some number
double n;
try { n = readFractional(i); }
catch (error &) { break; }
gotsome = true;
// Get the designator
switch (char c = getChar(i)) {
case 'H': secs += 60 * 60 * n; break;
case 'M': secs += 60 * n; break;
case 'S': secs += n; break;
default:
throw error("Unexpected designator '"
+ std::string(1, c) + "' in right side of ISO 8601 period");
}
}
}
if (!gotsome)
throw error("No ISO8601 period data after period designator");
o = DiffTime(secs);
return i;
}
std::ostream &operator<<(std::ostream &s, const DiffTime &ts)
{
s << "PT" << ts.to_double() << "S";
return s;
}
| 23.776224
| 82
| 0.606691
|
sergeyfilip
|
2c8168440ba85f8160a3e3f7b75cfc16885e6fa2
| 1,957
|
cpp
|
C++
|
foe4.cpp
|
Loretac/ohlavache
|
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
|
[
"MIT"
] | null | null | null |
foe4.cpp
|
Loretac/ohlavache
|
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
|
[
"MIT"
] | null | null | null |
foe4.cpp
|
Loretac/ohlavache
|
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
|
[
"MIT"
] | null | null | null |
#include "foe4.h"
#include "game.h"
#include "bulletdirected.h"
#include "bulletminesmall.h"
#include <QTimer>
extern Game *game;
/*********************************************************************
**
*********************************************************************/
Foe4::Foe4()
{
setStartingHealth(2);
// setDimensions(100,53,10,-10);
// setEnemyPix(QPixmap(":/images/images/ufo.png"));
setDimensions(80,58,0,-10);
setEnemyPix(QPixmap(":/images/images/fabian.png"));
setHealthPix(QPixmap(":/images/images/Shb2.png"));
setSize("S");
addToGroup(getEnemyPix());
addToGroup(getHealthPix());
positionHealth();
setPos(rand()% (800-getWidth()),-getHeight());
setMotion();
startShooting();
}
void Foe4::move()
{
if(game->isPaused() == false){
setPos(x(),y()+1);
checkStatus();
if(isDead()){
deleteLater();
}
}
}
void Foe4::shoot()
{
if(game->isPaused() == false){
BulletMineSmall *Bullet = new BulletMineSmall();
Bullet->setSpeed(5);
// coordinates of origin of bullet
int xSource = x() + getWidth()/2 - Bullet->getWidth()/2;
int ySource = y() + getHeight()/2 - Bullet->getHeight()/2;
// coordinates of center of player (offset for center of bullet)
int xPlayer = game->getPlayerXPos() + game->getPlayerWidth()/2 - Bullet->getWidth()/2;
int yPlayer = game->getPlayerYPos() + game->getPlayerHeight()/2 - Bullet->getHeight()/2;
// set the trajectory of the bullet
Bullet->setXTrajectory(xPlayer-xSource);
Bullet->setYTrajectory(yPlayer-ySource);
// bullet starts at source
Bullet->setPos(xSource,ySource);
game->addToScene(Bullet);
}
}
void Foe4::startShooting()
{
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),
this,SLOT(shoot()));
timer->start(1500);
}
| 20.385417
| 96
| 0.552376
|
Loretac
|
2c844a4d5b4b4f7aaf9c25dc955654683e53893b
| 1,519
|
hh
|
C++
|
src/image/image.hh
|
kofuk/pixel-terrain
|
f39e2a0120aab5a11311f57cfd1ab46efa65fddd
|
[
"MIT"
] | 2
|
2020-10-16T08:46:45.000Z
|
2020-11-04T02:19:19.000Z
|
src/image/image.hh
|
kofuk/minecraft-image-generator
|
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
|
[
"MIT"
] | null | null | null |
src/image/image.hh
|
kofuk/minecraft-image-generator
|
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
|
[
"MIT"
] | null | null | null |
// SPDX-License-Identifier: MIT
#ifndef IMAGE_HH
#define IMAGE_HH
#include <filesystem>
#include "image/containers.hh"
#include "image/worker.hh"
#include "logger/logger.hh"
#include "nbt/chunk.hh"
#include "nbt/region.hh"
#include "utils/path_hack.hh"
#include "utils/threaded_worker.hh"
namespace pixel_terrain::image {
class image_generator {
image::worker *worker_;
threaded_worker<region_container *> *thread_pool_;
auto fetch() -> region_container *;
void write_range_file(int start_x, int start_z, int end_x, int end_z,
options const &options);
public:
image_generator(options const &options) {
worker_ = new image::worker;
thread_pool_ = new threaded_worker<region_container *>(
options.n_jobs(), [this](region_container *item) {
this->worker_->generate_region(item);
logger::progress_bar_process_one();
delete item;
});
}
~image_generator() {
delete thread_pool_;
delete worker_;
}
void start();
void queue(region_container *item);
void queue_region(std::filesystem::path const ®ion_file,
options const &options);
void queue_all_in_dir(std::filesystem::path const &dir,
options const &options);
void finish();
};
} // namespace pixel_terrain::image
#endif
| 29.211538
| 77
| 0.593153
|
kofuk
|
2c8cac1b9c33c8497d87479093a357bebbfa92f4
| 2,459
|
cc
|
C++
|
src/simplesat/parsers/dimacs_parser.cc
|
evmaus/ClusterSAT
|
d26ff539fe9789611e9ecd8ef5c14a19e150105b
|
[
"Apache-2.0"
] | null | null | null |
src/simplesat/parsers/dimacs_parser.cc
|
evmaus/ClusterSAT
|
d26ff539fe9789611e9ecd8ef5c14a19e150105b
|
[
"Apache-2.0"
] | null | null | null |
src/simplesat/parsers/dimacs_parser.cc
|
evmaus/ClusterSAT
|
d26ff539fe9789611e9ecd8ef5c14a19e150105b
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/simplesat/parsers/dimacs_parser.h"
#include <vector>
#include <string>
#include <iostream>
#include "absl/strings/str_split.h"
#include <glog/logging.h>
#include "src/simplesat/cnf/cnf_and_op.h"
#include "src/simplesat/cnf/cnf_or_op.h"
#include "src/simplesat/cnf/cnf_variable.h"
namespace simplesat {
cnf::Or ParseLine(std::string line) {
std::vector<std::string> line_contents = absl::StrSplit(line, ' ', absl::SkipEmpty());
std::vector<cnf::Variable> variables;
for (int j = 0; j < line_contents.size(); j++) {
if (line_contents[j] == "0") {
break;
} else {
int32_t var_index = stoi(line_contents[j]);
if (var_index > 0){
cnf::Variable f(var_index);
variables.push_back(f);
} else {
cnf::Variable f(-var_index, true);
variables.push_back(f);
}
}
}
cnf::Or expr(variables);
return expr;
}
cnf::And DiMacsParser::ParseCnf(std::istream& input) {
std::string line;
while ( getline (input,line) && line[0] == 'c') {
LOG(INFO) << "Skipping line " << line;
}
LOG(INFO) << "Found starting line: " << line;
// Parse first line: p cnf nvar nclause
std::vector<std::string> line_contents = absl::StrSplit(line, ' ', absl::SkipEmpty());
// Expectation: line is in the form 'p cnf nvar nclause'
LOG(INFO) << "nvar " << line_contents[2];
//uint32_t num_terms = std::stoi(line_contents[2]);
LOG(INFO) << "nclause " << line_contents[3];
uint32_t num_clauses = std::stoi(line_contents[3]);
std::list<cnf::Or> terms;
for(int i = 0; i < num_clauses; i++) {
if(!getline(input, line)){
// TODO error
}
LOG(INFO) << "Parsing line: " << line;
auto term = ParseLine(line);
terms.push_back(term);
LOG(INFO) << "Parsed: " << term.to_string();
}
cnf::And expr(terms);
return expr;
}
} // namespace simplesat
| 30.7375
| 88
| 0.651891
|
evmaus
|
2c979c8325291c6061e2735370baa586ab05be42
| 234
|
cpp
|
C++
|
display/source/DisplayConstants.cpp
|
sidav/shadow-of-the-wyrm
|
747afdeebed885b1a4f7ab42f04f9f756afd3e52
|
[
"MIT"
] | null | null | null |
display/source/DisplayConstants.cpp
|
sidav/shadow-of-the-wyrm
|
747afdeebed885b1a4f7ab42f04f9f756afd3e52
|
[
"MIT"
] | null | null | null |
display/source/DisplayConstants.cpp
|
sidav/shadow-of-the-wyrm
|
747afdeebed885b1a4f7ab42f04f9f756afd3e52
|
[
"MIT"
] | null | null | null |
#include "DisplayConstants.hpp"
using namespace std;
const string DisplayIdentifier::DISPLAY_IDENTIFIER_CURSES = "curses";
const string DisplayIdentifier::DISPLAY_IDENTIFIER_SDL = "sdl";
DisplayIdentifier::DisplayIdentifier()
{
}
| 19.5
| 69
| 0.807692
|
sidav
|
2ca15fdd61c0a58f78d82d0e92b823c8ba841b67
| 285
|
cpp
|
C++
|
src/kitti/common.cpp
|
dzyswy/kitti_player
|
77f9d6266a05639da4ba9b943338a9f2304b9f5e
|
[
"MIT"
] | null | null | null |
src/kitti/common.cpp
|
dzyswy/kitti_player
|
77f9d6266a05639da4ba9b943338a9f2304b9f5e
|
[
"MIT"
] | null | null | null |
src/kitti/common.cpp
|
dzyswy/kitti_player
|
77f9d6266a05639da4ba9b943338a9f2304b9f5e
|
[
"MIT"
] | null | null | null |
#include "kitti/common.h"
namespace kitti {
void GlobalInit(int* pargc, char*** pargv)
{
// Google logging.
::google::InitGoogleLogging(*(pargv)[0]);
// Provide a backtrace on segfault.
::google::InstallFailureSignalHandler();
}
}//namespace kitti
| 8.142857
| 43
| 0.631579
|
dzyswy
|
2ca2106ecd6bed73ee0215738d606f2a216e6f64
| 3,062
|
cpp
|
C++
|
src/Tools/ProjectBuilder/XmlToBinDecoder.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 39
|
2016-04-21T03:25:26.000Z
|
2022-01-19T14:16:38.000Z
|
src/Tools/ProjectBuilder/XmlToBinDecoder.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 23
|
2016-06-28T13:03:17.000Z
|
2022-02-02T10:11:54.000Z
|
src/Tools/ProjectBuilder/XmlToBinDecoder.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 14
|
2016-06-22T20:45:37.000Z
|
2021-07-05T12:25:19.000Z
|
#include "XmlToBinDecoder.h"
#include "Interface/ServiceInterface.h"
#include "Interface/StringizeServiceInterface.h"
#include "Interface/ArchivatorInterface.h"
#include "Interface/LoggerInterface.h"
#include "Interface/CodecInterface.h"
#include "Interface/ConverterInterface.h"
#include "Interface/FileServiceInterface.h"
#include "Interface/PluginInterface.h"
#include "Interface/UnicodeSystemInterface.h"
#include "Interface/CodecServiceInterface.h"
#include "Plugins/XmlToBinPlugin/XmlToBinInterface.h"
#include "Kernel/Logger.h"
#include "Kernel/Document.h"
#include "Kernel/ConstStringHelper.h"
#include "Kernel/FilePathHelper.h"
#include "Kernel/UnicodeHelper.h"
#include "Xml2Metabuf.hpp"
#include "Xml2Metacode.hpp"
#include "Metacode/Metacode.h"
#include "Config/Typedef.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
static bool s_writeBin( const WString & _protocolPath, const WString & _xmlPath, const WString & _binPath )
{
String utf8_protocolPath;
Helper::unicodeToUtf8( _protocolPath, &utf8_protocolPath );
String utf8_xmlPath;
Helper::unicodeToUtf8( _xmlPath, &utf8_xmlPath );
String utf8_binPath;
Helper::unicodeToUtf8( _binPath, &utf8_binPath );
XmlDecoderInterfacePtr decoder = CODEC_SERVICE()
->createDecoder( STRINGIZE_STRING_LOCAL( "xml2bin" ), MENGINE_DOCUMENT_FUNCTION );
if( decoder == nullptr )
{
LOGGER_ERROR( "writeBin invalid create decoder xml2bin for %s"
, utf8_xmlPath.c_str()
);
return false;
}
if( decoder->prepareData( nullptr ) == false )
{
LOGGER_ERROR( "writeBin invalid initialize decoder xml2bin for %s"
, utf8_xmlPath.c_str()
);
return false;
}
XmlDecoderData data;
data.pathProtocol = Helper::stringizeFilePath( utf8_protocolPath );
data.pathXml = Helper::stringizeFilePath( utf8_xmlPath );
data.pathBin = Helper::stringizeFilePath( utf8_binPath );
data.useProtocolVersion = Metacode::get_metacode_protocol_version();
data.useProtocolCrc32 = Metacode::get_metacode_protocol_crc32();
if( decoder->decode( &data ) == 0 )
{
LOGGER_ERROR( "writeBin invalid decode %s"
, utf8_xmlPath.c_str()
);
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
PyObject * writeBin( pybind::kernel_interface * _kernel, const wchar_t * protocolPath, const wchar_t * xmlPath, const wchar_t * binPath )
{
if( s_writeBin( protocolPath, xmlPath, binPath ) == false )
{
LOGGER_ERROR( "writeBin: error write bin"
);
return nullptr;
}
return _kernel->ret_none();
}
}
| 30.929293
| 142
| 0.599282
|
irov
|
2ca6a079c413fb203abe0b963e59036bf389350c
| 17,757
|
hpp
|
C++
|
Datastructures/Tree.hpp
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | 2
|
2021-06-09T00:38:46.000Z
|
2021-09-04T21:55:33.000Z
|
Datastructures/Tree.hpp
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | null | null | null |
Datastructures/Tree.hpp
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | 1
|
2021-08-30T00:46:12.000Z
|
2021-08-30T00:46:12.000Z
|
//
// Created by phoenixflower on 9/26/21.
//
#ifndef LANDESSDEVCORE_TREE_HPP
#define LANDESSDEVCORE_TREE_HPP
//
// Tree.h
// Foundation
//
// Created by James Landess on 1/6/14.
// Copyright (c) 2014 LandessDev. All rights reserved.
//
#ifndef Foundation_Tree_h
#define Foundation_Tree_h
/*-----------------------------------------------------------------------------
tree.h
STL-like tree
-----------------------------------------------------------------------------*/
#ifndef _TREE_H
#define _TREE_H
#include <memory>
#include <iterator>
#include <cassert>
//-----------------------------------------------------------------------------
namespace gems
{
//-----------------------------------------------------------------------------
template <class T, class Alloc = std::allocator<T> >
class tree
{
public:
typedef tree<T, Alloc> TreeT;
typedef TreeT value_type;
typedef TreeT* pointer;
typedef const TreeT* const_pointer;
typedef TreeT& reference;
typedef const TreeT& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
// provide special handling for non-standard VC6 allocators
#if _MSC_VER < 1300
typedef Alloc allocator_type;
#else
typedef typename Alloc::template rebind<TreeT>::other allocator_type;
#endif
class iterator;
class const_iterator;
class child_iterator;
class const_child_iterator;
tree() { init(); }
tree(const T& t) : value(t) { init(); }
tree(const TreeT& copy) : value(copy.value)
{
init();
copy_children(copy);
}
~tree() { clear(); }
const tree& operator=(const TreeT& rhs)
{
TreeT temp(rhs);
swap(temp);
return *this;
}
// iterators
class iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void>
{
public:
iterator() : _ptr(0), _root(0) {}
TreeT& operator*() const {return *_ptr;}
TreeT* operator->() const {return _ptr;}
bool operator==(const iterator& rhs) const {return _ptr == rhs._ptr;}
bool operator!=(const iterator& rhs) const {return _ptr != rhs._ptr;}
iterator& operator++() {_ptr = _ptr->_next; return *this;}
iterator& operator--() {_ptr = (_ptr ? _ptr->prev() : _root->_last_descendant); return *this;}
iterator operator++(int i) { iterator temp = *this; ++*this; return temp; }
iterator operator--(int i) { iterator temp = *this; --*this; return temp; }
// advance past current subtree
friend void skip(iterator& it) { it._ptr = it._ptr->next_sibling(); }
protected:
TreeT* _ptr;
TreeT* _root;
iterator(TreeT* ptr, TreeT* root) : _ptr(ptr), _root(root) {}
friend class tree<T, Alloc>;
friend class const_iterator;
friend class child_iterator;
friend class const_child_iterator;
};
class const_iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void>
{
public:
const_iterator() : _ptr(0), _root(0) {}
const_iterator(const iterator& it) : _ptr(it._ptr), _root(it._root) {}
const TreeT& operator*() const {return *_ptr;}
const TreeT* operator->() const {return _ptr;}
bool operator==(const const_iterator& rhs) const {return _ptr == rhs._ptr;}
bool operator!=(const const_iterator& rhs) const {return _ptr != rhs._ptr;}
const_iterator& operator++() {_ptr = _ptr->_next; return *this;}
const_iterator& operator--() {_ptr = (_ptr ? _ptr->prev() : _root->_last_descendant); return *this;}
const_iterator operator++(int i) { const_iterator temp = *this; ++*this; return temp; }
const_iterator operator--(int i) { const_iterator temp = *this; --*this; return temp; }
protected:
const TreeT* _ptr;
const TreeT* _root;
const_iterator(const TreeT* ptr, const TreeT* root) : _ptr(ptr), _root(root) {}
friend class tree<T, Alloc>;
friend class const_child_iterator;
};
class child_iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void>
{
public:
child_iterator() : _ptr(0), _root(0) {}
child_iterator(const iterator& it) : _ptr(it._ptr), _root(it._root) {}
operator iterator() const { return iterator(_ptr, _root); }
TreeT& operator*() const {return *_ptr;}
TreeT* operator->() const {return _ptr;}
bool operator==(const child_iterator& rhs) const {return _ptr == rhs._ptr;}
bool operator!=(const child_iterator& rhs) const {return _ptr != rhs._ptr;}
child_iterator& operator++() {_ptr = _ptr->next_sibling(); return *this;}
child_iterator& operator--() {_ptr = (_ptr ? _ptr->prev_sibling() : _root->last_child()); return *this;}
child_iterator operator++(int i) { child_iterator temp = *this; ++*this; return temp; }
child_iterator operator--(int i) { child_iterator temp = *this; --*this; return temp; }
protected:
TreeT* _ptr;
TreeT* _root;
child_iterator(TreeT* ptr, TreeT* root) : _ptr(ptr), _root(root) {}
friend class tree<T, Alloc>;
friend class const_child_iterator;
};
class const_child_iterator : public std::iterator<std::bidirectional_iterator_tag, value_type, void>
{
public:
const_child_iterator() : _ptr(0), _root(0) {}
const_child_iterator(const child_iterator& it) : _ptr(it._ptr), _root(it._root) {}
const_child_iterator(const iterator& it) : _ptr(it._ptr), _root(it._root) {}
const_child_iterator(const const_iterator& it) : _ptr(it._ptr), _root(it._root) {}
operator const_iterator() const { return iterator(_ptr, _root); }
const TreeT& operator*() const {return *_ptr;}
const TreeT* operator->() const {return _ptr;}
bool operator==(const const_child_iterator& rhs) const {return _ptr == rhs._ptr;}
bool operator!=(const const_child_iterator& rhs) const {return _ptr != rhs._ptr;}
const_child_iterator& operator++() {_ptr = _ptr->next_sibling(); return *this;}
const_child_iterator& operator--() {_ptr = (_ptr ? _ptr->prev_sibling() : _root->last_child()); return *this;}
const_child_iterator operator++(int i) { const_child_iterator temp = *this; ++*this; return temp; }
const_child_iterator operator--(int i) { const_child_iterator temp = *this; --*this; return temp; }
protected:
const TreeT* _ptr;
const TreeT* _root;
const_child_iterator(const TreeT* ptr, const TreeT* root) : _ptr(ptr), _root(root) {}
friend class tree<T, Alloc>;
};
//typedef std::is_bidirectional_iterator<iterator,
//value_type, reference, pointer, difference_type>
//reverse_iterator;
//typedef std::is_bidirectional_iterator<const_iterator,
// value_type, const_reference, const_pointer, difference_type>
//const_reverse_iterator;
// typedef std::is_bidirectional_iterator<child_iterator,
// value_type, reference, pointer, difference_type>
//reverse_child_iterator;
// typedef std::is_bidirectional_iterator<const_child_iterator,
//value_type, const_reference, const_pointer, difference_type>
//const_reverse_child_iterator;
const_iterator begin() const {return const_iterator(this, this);}
const_iterator end() const {return const_iterator(0, this);}
iterator begin() {return iterator(this, this);}
iterator end() {return iterator(0, this);}
void push_back(const TreeT& subtree)
{
TreeT* child = create_subtree(subtree);
insert_subtree(*child, 0);
}
void push_front(const TreeT& subtree)
{
TreeT* child = create_subtree(subtree);
TreeT* next = first_child();
insert_subtree(*child, next);
}
void pop_back()
{
TreeT* last = last_child();
assert(last);
erase(iterator(last, this));
}
void pop_front()
{
TreeT* first = first_child();
assert(first);
erase(iterator(first, this));
}
void clear() { destroy_descendants(); }
TreeT& front() {return *first_child();}
const TreeT& front() const {return *first_child();}
TreeT& back() {return *last_child();}
const TreeT& back() const {return *last_child();}
iterator insert(const TreeT& subtree, iterator it)
{
TreeT* child = create_subtree(subtree);
insert_subtree(*child, &*it); // if end(), append to this
return iterator(child, this);
}
iterator erase(iterator it)
{
TreeT* child = &*it;
assert(child);
TreeT* parent = child->parent();
assert(parent);
TreeT* next = child->next_sibling();
parent->remove_subtree(*child);
child->destroy();
return iterator(next, this);
}
void splice(iterator it, child_iterator first, child_iterator last)
{
while (first != last)
{
TreeT* parent = first->parent();
child_iterator next = first;
++next;
if (parent)
{
parent->remove_subtree(*first);
insert_subtree(*first, &*it); // if it == end(), append to this; that's why this fn can't be static
}
first = next;
}
}
friend bool operator==(const TreeT& lhs, const TreeT& rhs)
{
const TreeT* lChild = lhs.first_child();
const TreeT* rChild = rhs.first_child();
while (lChild && rChild && (*lChild == *rChild))
{
lChild = lChild->next_sibling();
rChild = rChild->next_sibling();
}
return (!lChild && !rChild && (lhs.value == rhs.value));
}
friend bool operator!=(const TreeT& lhs, const TreeT& rhs) { return !(lhs == rhs); }
bool is_root() const { return _parent == 0; }
bool is_leaf() const { return _last_descendant == this; }
bool is_descendant_of(const TreeT& ancestor)
{
TreeT * t;
for (t = this; t; t = t->_parent)
if (t == &ancestor)
break;
return (t != 0);
}
size_type size() const // number of descendants
{
size_type n = 1;
for (const TreeT* t = this; t != _last_descendant; t = t->_next)
n++;
return n;
}
size_type degree() const // number of children
{
size_type n = 0;
for (const TreeT* t = first_child(); t; t = t->next_sibling())
n++;
return n;
}
size_type level() const // depth in tree
{
size_type l = 0;
for (const TreeT* t = _parent; t; t = t->_parent)
l++;
return l;
}
TreeT* parent() const { return _parent; }
TreeT* first_child() const
{
TreeT* child = 0;
if (_next && (_next->_parent == this))
child = _next;
return child;
}
TreeT* last_child() const
{
TreeT* child = first_child();
if (child)
child = child->_prev_sibling;
return child;
}
TreeT* next_sibling() const
{
TreeT* sib = _last_descendant->_next;
if (sib && (sib->_parent != _parent))
sib = 0;
return sib;
}
TreeT* prev_sibling() const
{
TreeT* sib = 0;
if (_parent && (_parent->_next != this))
sib = _prev_sibling;
return sib;
}
TreeT* last_descendant() const { return _last_descendant; }
void swap(TreeT& other)
{
child_iterator it = other.begin_child();
//other.splice(it, begin_child(), end_child());
//splice(begin_child(), it, other.end_child());
std::swap(value, other.value);
}
Alloc get_allocator() const { return _alloc; }
size_type max_size() const { return (_alloc.max_size()); }
public:
T value;
private:
TreeT* _parent;
TreeT* _prev_sibling;
TreeT* _next;
TreeT* _last_descendant;
static allocator_type _alloc;
friend iterator;
friend const_iterator;
friend child_iterator;
friend const_child_iterator;
void init()
{
_parent = _next = 0;
_prev_sibling = _last_descendant = this;
}
static TreeT* create_subtree(const TreeT& copy)
{
#if defined(__APPLE__)
std::auto_ptr<TreeT> a((TreeT*)_alloc.allocate(1));
TreeT* t = a.get();
_alloc.construct(t, copy);
#elif _MSC_VER < 1300
auto_ptr<TreeT> a((TreeT*)_alloc._Charalloc(sizeof(TreeT)));
TreeT* t = a.get();
_alloc.construct(&t->value, copy.value);
t->init();
t->copy_children(copy);
#else
auto_ptr<TreeT> a((TreeT*)_alloc.allocate(1));
TreeT* t = a.get();
_alloc.construct(t, copy);
#endif
return a.release();
}
void copy_children(const TreeT& other)
{
for (TreeT* child = other.first_child(); child; child = child->next_sibling())
insert_subtree(*create_subtree(*child), 0);
}
void destroy()
{
#if _MSC_VER < 1300
destroy_descendants();
_alloc.destroy(&value);
_alloc.deallocate((T*)this, 1);
#else
_alloc.destroy(this);
_alloc.deallocate(this, 1);
#endif
}
void destroy_descendants()
{
TreeT* descendant = first_child();
TreeT* end = last_descendant()->next();
while (descendant)
{
TreeT* next = descendant->next_sibling();
descendant->destroy();
descendant = next;
}
_next = end;
_last_descendant = this;
}
void insert_subtree(TreeT& child, TreeT* next)
{
if (next == 0)
{
// append as last child
child._parent = this;
child._last_descendant->_next = _last_descendant->_next;
_last_descendant->_next = &child;
child._prev_sibling = last_child();
if (is_leaf())
_next = &child;
first_child()->_prev_sibling = &child;
change_last_descendant(child._last_descendant);
}
else
{
TreeT* parent = next->_parent;
child._parent = parent;
child._prev_sibling = next->_prev_sibling;
child._last_descendant->_next = next;
if (parent->_next == next) // inserting before first child?
parent->_next = &child;
else
next->_prev_sibling->_last_descendant->_next = &child;
next->_prev_sibling = &child;
}
}
void remove_subtree(TreeT& child)
{
TreeT* sib = child.next_sibling();
if (sib)
sib->_prev_sibling = child._prev_sibling;
else
first_child()->_prev_sibling = child._prev_sibling;
if (_last_descendant == child._last_descendant)
change_last_descendant(child.prev());
if (_next == &child) // deleting first child?
_next = child._last_descendant->_next;
else
child._prev_sibling->_last_descendant->_next = child._last_descendant->_next;
}
void change_last_descendant(TreeT* newLast)
{
TreeT* oldLast = _last_descendant;
TreeT* ancestor = this;
do
{
ancestor->_last_descendant = newLast;
ancestor = ancestor->_parent;
}
while (ancestor && (ancestor->_last_descendant == oldLast));
}
TreeT* next() const { return _next; }
TreeT* prev() const
{
TreeT* prev = 0;
if (_parent)
{
if (_parent->_next == this)
prev = _parent;
else
prev = _prev_sibling->_last_descendant;
}
return prev;
}
}; // class tree<T, Alloc>
template <class T, class Alloc>
typename tree<T, Alloc>::allocator_type tree<T, Alloc>::_alloc;
//-----------------------------------------------------------------------------
} // namespace gems
#endif // _TREE_H
#endif
#endif //LANDESSDEVCORE_TREE_HPP
| 31.822581
| 122
| 0.525933
|
jlandess
|
2ca7b5bd693fd0599d411fb3c96a2b6adfc57565
| 2,000
|
hpp
|
C++
|
engine/include/io/logger.hpp
|
ValtoForks/Terminus-Engine
|
0c7381af84736ec7b029977843590453cde64b1d
|
[
"MIT"
] | 44
|
2017-01-25T05:57:21.000Z
|
2021-09-21T13:36:49.000Z
|
engine/include/io/logger.hpp
|
ValtoForks/Terminus-Engine
|
0c7381af84736ec7b029977843590453cde64b1d
|
[
"MIT"
] | 1
|
2017-04-05T01:50:18.000Z
|
2017-04-05T01:50:18.000Z
|
engine/include/io/logger.hpp
|
ValtoForks/Terminus-Engine
|
0c7381af84736ec7b029977843590453cde64b1d
|
[
"MIT"
] | 3
|
2017-09-28T08:11:00.000Z
|
2019-03-27T03:38:47.000Z
|
#pragma once
#include <core/terminus_macros.hpp>
#include <string>
// Macros for quick access. File and line are added through the respective macros.
#define TE_LOG_INFO(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_INFO)
#define TE_LOG_WARNING(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_WARNING)
#define TE_LOG_ERROR(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_ERR)
#define TE_LOG_FATAL(x) te::logger::log(x, std::string(__FILE__), __LINE__, te::logger::LEVEL_FATAL)
TE_BEGIN_TERMINUS_NAMESPACE
namespace logger
{
enum LogLevel
{
LEVEL_INFO = 0,
LEVEL_WARNING = 1,
LEVEL_ERR = 2,
LEVEL_FATAL = 3
};
enum LogVerbosity
{
VERBOSITY_BASIC = 0x00,
VERBOSITY_TIMESTAMP = 0x01,
VERBOSITY_LEVEL = 0x02,
VERBOSITY_FILE = 0x04,
VERBOSITY_LINE = 0x08,
VERBOSITY_ALL = 0x0f
};
// Custom stream callback type. Use to implement your own logging stream such as through a network etc.
typedef void(*CustomStreamCallback)(std::string, LogLevel);
extern void initialize();
extern void set_verbosity(int flags);
// Open streams.
extern void open_file_stream();
extern void open_console_stream();
extern void open_custom_stream(CustomStreamCallback callback);
// Close streams.
extern void close_file_stream();
extern void close_console_stream();
extern void close_custom_stream();
// Debug mode. These will flush the stream immediately after each log.
extern void enable_debug_mode();
extern void disable_debug_mode();
// Main log method. File, line and level are required in addition to log message.
extern void log(std::string text, std::string file, int line, LogLevel level);
// Simplified API.
extern void log_info(std::string text);
extern void log_error(std::string text);
extern void log_warning(std::string text);
extern void log_fatal(std::string text);
// Explicitly flush all streams.
extern void flush();
} // namespace logger
TE_END_TERMINUS_NAMESPACE
| 29.411765
| 104
| 0.751
|
ValtoForks
|
2caa60a850f9f796a4bb0bf8d40e9537f2e24d5f
| 424
|
cpp
|
C++
|
ieee_sep/RateComponentListLink.cpp
|
Tylores/ieee_sep
|
1928bed8076f4bfe702d34e436c6a85f197b0832
|
[
"BSD-2-Clause"
] | null | null | null |
ieee_sep/RateComponentListLink.cpp
|
Tylores/ieee_sep
|
1928bed8076f4bfe702d34e436c6a85f197b0832
|
[
"BSD-2-Clause"
] | null | null | null |
ieee_sep/RateComponentListLink.cpp
|
Tylores/ieee_sep
|
1928bed8076f4bfe702d34e436c6a85f197b0832
|
[
"BSD-2-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////
// RateComponentListLink.cpp
// Implementation of the Class RateComponentListLink
// Created on: 13-Apr-2020 2:51:38 PM
// Original author: svanausdall
///////////////////////////////////////////////////////////
#include "RateComponentListLink.h"
RateComponentListLink::RateComponentListLink(){
}
RateComponentListLink::~RateComponentListLink(){
}
| 22.315789
| 59
| 0.54717
|
Tylores
|
2caae092e04eda8fe3c4320d39f468ae13e0f99f
| 3,705
|
cpp
|
C++
|
arduino/pcc2arduino.cpp
|
ncchandler42/pcc2arduino
|
ff67796d93760b1c2dd3dc9e9a02319d71ef6d7e
|
[
"MIT"
] | null | null | null |
arduino/pcc2arduino.cpp
|
ncchandler42/pcc2arduino
|
ff67796d93760b1c2dd3dc9e9a02319d71ef6d7e
|
[
"MIT"
] | null | null | null |
arduino/pcc2arduino.cpp
|
ncchandler42/pcc2arduino
|
ff67796d93760b1c2dd3dc9e9a02319d71ef6d7e
|
[
"MIT"
] | null | null | null |
#include "pcc2arduino.h"
///////////////////////
// reads in bytes from serial
// returns true when the controller state is ready
///////////////////////
bool PCController::update()
{
if (!ser || !ser->available())
return false;
//find the start of a valid parsel
while (ser->peek() != '<')
{
byte b = ser->read();
if (b == -1)
return false;
}
byte parsel[10];
ser->readBytes(parsel, 10);
if (parsel[0] == '<' && parsel[9] == '>')
{
//copies the data part of the parsel into the input, to be parsed
memcpy(inp, parsel + 1, 8);
parseButtons();
parseAxes();
ser->write('*');
return true;
}
return false;
}
bool PCController::updateInc()
{
static int i = 0;
static bool reading = false;
if(!ser)
return false;
//Notify the system
ser->write('*');
byte b;
//wait for response
while(!ser->available());
b = ser->read();
if (i == 0 && b == '<')
{
reading = true;
return false;
}
if (reading && i >= 0 && i < 8)
{
inp[i] = b;
i++;
return false;
}
if (reading && i == 8 && b == '>')
{
reading = false;
i = 0;
parseButtons();
parseAxes();
return true;
}
return false;
}
/////////////////////////////////////////////////
// Parses 2 bytes into 16 buttons (bools)
/////////////////////////////////////////////////
void PCController::parseButtons()
{
dpad_up = inp[0] & 1;
dpad_down = inp[0] & 2;
dpad_left = inp[0] & 4;
dpad_right = inp[0] & 8;
a = inp[0] & 16;
b = inp[0] & 32;
x = inp[0] & 64;
y = inp[0] & 128;
lb = inp[1] & 1;
rb = inp[1] & 2;
lt = inp[1] & 4;
rt = inp[1] & 8;
select = inp[1] & 16;
start = inp[1] & 32;
ls_press = inp[1] & 64;
rs_press = inp[1] & 128;
}
////////////////////////////////////////////////
// Parses 12 bytes into 6 axes, 2 bytes per axis
// Serial architecture is "little-endian"
// UPDATE: axis values are now 0-255, one byte
// ... makes conversion a lot simpler
////////////////////////////////////////////////
void PCController::parseAxes()
{
x_axis = inp[2];
y_axis = inp[3];
z_axis = inp[4];
r_axis = inp[5];
u_axis = inp[6];
v_axis = inp[7];
}
void PCController::displayButtons()
{
if (ser)
{
ser->print("up: ");
ser->print(dpad_up);
ser->println();
ser->print("down: ");
ser->print(dpad_down);
ser->println();
ser->print("left: ");
ser->print(dpad_left);
ser->println();
ser->print("right: ");
ser->print(dpad_right);
ser->println();
ser->print("a: ");
ser->print(a);
ser->println();
ser->print("b: ");
ser->print(b);
ser->println();
ser->print("x: ");
ser->print(x);
ser->println();
ser->print("y: ");
ser->print(y);
ser->println();
ser->print("lb: ");
ser->print(lb);
ser->println();
ser->print("rb: ");
ser->print(rb);
ser->println();
ser->print("lt: ");
ser->print(lt);
ser->println();
ser->print("rt: ");
ser->print(rt);
ser->println();
ser->print("select: ");
ser->print(select);
ser->println();
ser->print("start: ");
ser->print(start);
ser->println();
ser->print("LS press: ");
ser->print(ls_press);
ser->println();
ser->print("RS press: ");
ser->print(rs_press);
ser->println();
ser->println();
}
}
void PCController::displayAxes()
{
if (ser)
{
ser->print("X axis: ");
ser->print(x_axis);
ser->println();
ser->print("Y axis: ");
ser->print(y_axis);
ser->println();
ser->print("Z axis: ");
ser->print(z_axis);
ser->println();
ser->print("R axis: ");
ser->print(r_axis);
ser->println();
ser->print("U axis: ");
ser->print(u_axis);
ser->println();
ser->print("V axis: ");
ser->print(v_axis);
ser->println();
ser->println();
}
}
| 16.764706
| 67
| 0.516059
|
ncchandler42
|
2caffe97249eed511b7f5a9ee7f0aa9e296ee893
| 6,582
|
cpp
|
C++
|
Ouroboros/Source/oGUI/menu.cpp
|
igHunterKiller/ouroboros
|
5e2cde7e6365341da297da10d8927b091ecf5559
|
[
"MIT"
] | null | null | null |
Ouroboros/Source/oGUI/menu.cpp
|
igHunterKiller/ouroboros
|
5e2cde7e6365341da297da10d8927b091ecf5559
|
[
"MIT"
] | null | null | null |
Ouroboros/Source/oGUI/menu.cpp
|
igHunterKiller/ouroboros
|
5e2cde7e6365341da297da10d8927b091ecf5559
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2016 Antony Arciuolo. See License.txt regarding use.
#include <oGUI/menu.h>
#include <oCore/assert.h>
#include <oSystem/windows/win_error.h>
namespace ouro { namespace gui { namespace menu {
#if 0
// not in use (yet?)
static int find_position(menu_handle parent, int item)
{
const int n = num_items(parent);
for (int i = 0; i < n; i++)
{
int ID = GetMenuItemID(parent, i);
if (ID == item)
return i;
}
return invalid;
}
#endif
static int find_position(menu_handle parent, menu_handle submenu)
{
const int n = GetMenuItemCount((HMENU)parent);
for (int i = 0; i < n; i++)
{
menu_handle hSubmenu = (menu_handle)GetSubMenu((HMENU)parent, i);
if (hSubmenu == submenu)
return i;
}
return -1;
}
#if oHAS_oASSERT
// Returns true if the specified menu contains all IDs [first,last]
static bool contains_range(menu_handle m, int item_range_first, int item_range_last)
{
MENUITEMINFO mii;
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_ID;
int nFound = 0;
const int n = num_items(m);
for (int i = 0; i < n; i++)
{
UINT uID = GetMenuItemID((HMENU)m, i);
if (uID == ~0u)
return false;
int ID = (int)uID;
if (ID >= item_range_first && ID <= item_range_last)
nFound++;
}
return nFound == (item_range_last - item_range_first + 1);
}
#endif
char* get_text_by_position(char* out_text, size_t out_text_size, menu_handle m, int item_position)
{
if (!GetMenuStringA((HMENU)m, item_position, out_text, (int)out_text_size, MF_BYPOSITION))
return nullptr;
return out_text;
}
menu_handle make_menu(bool top_level)
{
return (menu_handle)(top_level ? CreateMenu() : CreatePopupMenu());
}
void unmake_menu(menu_handle m)
{
if (IsMenu((HMENU)m))
oVB(DestroyMenu((HMENU)m));
}
void attach(window_handle _hWindow, menu_handle m)
{
oVB(SetMenu((HWND)_hWindow, (HMENU)m));
}
int num_items(menu_handle m)
{
return GetMenuItemCount((HMENU)m);
}
void append_submenu(menu_handle parent, menu_handle submenu, const char* text)
{
oVB(AppendMenu((HMENU)parent, MF_STRING|MF_POPUP, (UINT_PTR)submenu, text));
}
void remove_submenu(menu_handle parent, menu_handle submenu)
{
int p = find_position(parent, submenu);
if (p != -1 && !RemoveMenu((HMENU)parent, p, MF_BYPOSITION))
{
DWORD hr = GetLastError();
if (GetLastError() != ERROR_RESOURCE_TYPE_NOT_FOUND)
oV(hr);
}
}
void replace_item_with_submenu(menu_handle parent, int item, menu_handle submenu)
{
mstring text;
if (!get_text(text, parent, item))
oThrow(std::errc::invalid_argument, "");
oVB(RemoveMenu((HMENU)parent, item, MF_BYCOMMAND));
oVB(InsertMenu((HMENU)parent, item, MF_STRING|MF_POPUP, (UINT_PTR)submenu, text));
}
void replace_submenu_with_item(menu_handle parent, menu_handle submenu, int item, bool enabled)
{
int p = find_position(parent, submenu);
oAssert(p != -1, "the specified submenu is not under the specified parent menu");
mstring text;
if (!get_text_by_position(text, text.capacity(), parent, p))
oThrow(std::errc::invalid_argument, "");
oVB(DeleteMenu((HMENU)parent, p, MF_BYPOSITION));
UINT uFlags = MF_BYPOSITION|MF_STRING;
if (!enabled)
uFlags |= MF_GRAYED;
oVB(InsertMenu((HMENU)parent, p, uFlags, (UINT_PTR)item, text.c_str()));
}
void append_item(menu_handle parent, int item, const char* text)
{
oVB(AppendMenu((HMENU)parent, MF_STRING, (UINT_PTR)item, text));
}
void remove_item(menu_handle parent, int item)
{
if (!RemoveMenu((HMENU)parent, item, MF_BYCOMMAND))
{
DWORD hr = GetLastError();
if (GetLastError() != ERROR_RESOURCE_TYPE_NOT_FOUND)
oV(hr);
}
}
void remove_all(menu_handle m)
{
int n = GetMenuItemCount((HMENU)m);
while (n)
{
DeleteMenu((HMENU)m, n-1, MF_BYPOSITION);
n = GetMenuItemCount((HMENU)m);
}
}
void append_separator(menu_handle parent)
{
oVB(AppendMenu((HMENU)parent, MF_SEPARATOR, 0, nullptr));
}
void check(menu_handle m, int item, bool checked)
{
oAssert(item >= 0, "");
if (-1 == CheckMenuItem((HMENU)m, static_cast<unsigned int>(item), MF_BYCOMMAND | (checked ? MF_CHECKED : MF_UNCHECKED)))
oAssert(false, "MenuItemID not found in the specified menu");
}
bool checked(menu_handle m, int item)
{
MENUITEMINFO mii;
ZeroMemory(&mii, sizeof(mii));
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_STATE;
oAssert(item >= 0, "");
if (!GetMenuItemInfo((HMENU)m, static_cast<unsigned int>(item), FALSE, &mii))
return false;
if (mii.fState & MFS_CHECKED)
return true;
return false;
}
void check_radio(menu_handle m, int item_range_first, int item_range_last, int check_item)
{
// CheckMenuRadioItem returns false if the menu is wrong, but doesn't set a
// useful last error (S_OK is returned when I ran into this) so add our own
// check here.
oAssert(num_items(m) >= (item_range_last-item_range_first+1), "A radio range was specified that is larger than the number of elements in the list (menu count=%d, range implies %d items)", num_items(m), (item_range_last-item_range_first+1));
oAssert(contains_range(m, item_range_first, item_range_last), "The specified menu 0x%p does not include the specified range [%d,%d] with selected %d. Most API works with an ancestor menu but this requires the immediate parent, so if the ranges look correct check the specified m.", m, item_range_first, item_range_last, check_item);
oVB(CheckMenuRadioItem((HMENU)m, item_range_first, item_range_last, check_item, MF_BYCOMMAND));
}
int checked_radio(menu_handle m, int item_range_first, int item_range_last)
{
for (int i = item_range_first; i <= item_range_last; i++)
if (checked(m, i))
return i;
return -1;
}
void enable(menu_handle m, int item, bool enabled)
{
oAssert(item >= 0, "");
if (-1 == EnableMenuItem((HMENU)m, static_cast<unsigned int>(item), MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED)))
oAssert(false, "MenuItemID not found in the specified menu");
}
bool enabled(menu_handle m, int item)
{
MENUITEMINFO mii;
ZeroMemory(&mii, sizeof(mii));
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_STATE;
oAssert(item >= 0, "");
oVB(GetMenuItemInfo((HMENU)m, static_cast<unsigned int>(item), FALSE, &mii));
if (mii.fState & (MF_GRAYED|MF_DISABLED))
return false;
return true;
}
char* get_text(char* out_text, size_t out_text_size, menu_handle m, int item)
{
if (!GetMenuStringA((HMENU)m, item, out_text, (int)out_text_size, MF_BYCOMMAND))
return nullptr;
return out_text;
}
char* get_text(char* out_text, size_t out_text_size, menu_handle parent, menu_handle submenu)
{
int pos = find_position(parent, submenu);
if (pos == -1)
return nullptr;
return get_text_by_position(out_text, out_text_size, parent, pos);
}
}}}
| 27.655462
| 333
| 0.721513
|
igHunterKiller
|
2cba4a9acdf0794ca520d5900be289868bff8ea8
| 5,192
|
hpp
|
C++
|
vlite/strided_ref_vector.hpp
|
verri/vlite
|
c4677dad17070b8fb0cbabd06018b3bcbb162860
|
[
"Zlib"
] | null | null | null |
vlite/strided_ref_vector.hpp
|
verri/vlite
|
c4677dad17070b8fb0cbabd06018b3bcbb162860
|
[
"Zlib"
] | null | null | null |
vlite/strided_ref_vector.hpp
|
verri/vlite
|
c4677dad17070b8fb0cbabd06018b3bcbb162860
|
[
"Zlib"
] | null | null | null |
#ifndef VLITE_STRIDED_REF_VECTOR_HPP_INCLUDED
#define VLITE_STRIDED_REF_VECTOR_HPP_INCLUDED
#include <vlite/common_vector_base.hpp>
#include <vlite/slice.hpp>
#include <vlite/strided_iterator.hpp>
namespace vlite
{
template <typename T>
class strided_ref_vector : public common_vector_base<strided_ref_vector<T>>
{
template <typename> friend class strided_ref_vector;
public:
using value_type = T;
using iterator = strided_iterator<T>;
using const_iterator = strided_iterator<const T>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
strided_ref_vector(value_type* data, std::size_t size, std::size_t stride)
: data_{data}
, size_{size}
, stride_{stride}
{
}
~strided_ref_vector() = default;
template <typename Vector>
auto operator=(const common_vector_base<Vector>& source) -> strided_ref_vector&
{
static_assert(std::is_assignable_v<value_type&, const typename Vector::value_type&>,
"incompatible assignment");
if (source.size() != this->size())
throw std::runtime_error{"sizes mismatch"};
std::copy(source.begin(), source.end(), begin());
return *this;
}
template <typename U, typename = meta::fallback<CommonVector<U>>>
auto operator=(const U& source) -> strided_ref_vector&
{
static_assert(std::is_assignable<value_type&, U>::value, "incompatible assignment");
std::fill(begin(), end(), source);
for (auto& elem : *this)
elem = source;
return *this;
}
auto operator=(const strided_ref_vector& source) -> strided_ref_vector&
{
if (source.size() != size())
throw std::runtime_error{"sizes mismatch"};
std::copy(source.begin(), source.end(), this->begin());
return *this;
}
operator strided_ref_vector<const value_type>() const
{
return {data(), size(), stride()};
}
auto operator[](size_type i) -> value_type&
{
assert(i < size());
return data()[i * stride()];
}
auto operator[](size_type i) const -> const value_type&
{
assert(i < size());
return data()[i * stride()];
}
auto operator[](every_index) -> strided_ref_vector<value_type> { return *this; }
auto operator[](every_index) const -> strided_ref_vector<const value_type>
{
return *this;
}
auto operator[](slice s) -> strided_ref_vector<value_type>
{
assert(s.start < size());
assert(s.start + s.size <= size());
return {data() + s.start * stride_, s.size, stride_};
}
auto operator[](slice s) const -> strided_ref_vector<const value_type>
{
assert(s.start < size());
assert(s.start + s.size <= size());
return {data() + s.start * stride_, s.size, stride_};
}
auto operator[](strided_slice s) -> strided_ref_vector<value_type>
{
assert(s.start < size());
assert(s.start + s.stride * s.size <= size());
return {data() + s.start * stride_, s.size, s.stride * stride_};
}
auto operator[](strided_slice s) const -> strided_ref_vector<const value_type>
{
assert(s.start < size());
assert(s.start + s.stride * s.size <= size());
return {data() + s.start * stride_, s.size, s.stride * stride_};
}
auto operator[](bounded_slice s) -> strided_ref_vector<value_type>
{
assert(s.start < size());
return {data() + s.start * stride_, s.size(size() - s.start), stride_};
}
auto operator[](bounded_slice s) const -> strided_ref_vector<const value_type>
{
assert(s.start < size());
return {data() + s.start * stride_, s.size(size() - s.start), stride_};
}
auto operator[](strided_bounded_slice s) -> strided_ref_vector<value_type>
{
assert(s.start < size());
auto maximum_size = size() - s.start;
maximum_size += maximum_size % s.stride == 0u ? 0u : 1u;
maximum_size /= s.stride;
return {data() + s.start * stride_, s.size(maximum_size), s.stride * stride_};
}
auto operator[](strided_bounded_slice s) const -> strided_ref_vector<const value_type>
{
assert(s.start < size());
auto maximum_size = size() - s.start;
maximum_size += maximum_size % s.stride == 0u ? 0u : 1u;
maximum_size /= s.stride;
return {data() + s.start * stride_, s.size(maximum_size), s.stride * stride_};
}
auto begin() noexcept -> iterator { return {data(), stride()}; }
auto end() noexcept -> iterator { return {data() + stride() * size(), stride()}; }
auto begin() const noexcept -> const_iterator { return cbegin(); }
auto end() const noexcept -> const_iterator { return cend(); }
auto cbegin() const noexcept -> const_iterator { return {data(), stride()}; }
auto cend() const noexcept -> const_iterator
{
return {data() + stride() * size(), stride()};
}
auto size() const noexcept { return size_; }
protected:
auto data() -> value_type* { return data_; }
auto data() const -> const value_type* { return data_; }
auto stride() const -> std::size_t { return stride_; }
strided_ref_vector(const strided_ref_vector& source) = default;
strided_ref_vector(strided_ref_vector&& source) noexcept = default;
value_type* data_;
std::size_t size_;
std::size_t stride_;
};
} // namespace vlite
#endif // VLITE_STRIDED_REF_VECTOR_HPP_INCLUDED
| 27.764706
| 88
| 0.658128
|
verri
|
2cc40324de4e9508a348c23e4b8157b91237050a
| 6,558
|
cpp
|
C++
|
eagleye_core/navigation/src/smoothing.cpp
|
shjzhang/eagleye
|
e4e105d3a5438cf5ee36f1cc525ff87313923fc5
|
[
"BSD-3-Clause"
] | 1
|
2020-07-16T15:31:59.000Z
|
2020-07-16T15:31:59.000Z
|
eagleye_core/navigation/src/smoothing.cpp
|
shjzhang/eagleye
|
e4e105d3a5438cf5ee36f1cc525ff87313923fc5
|
[
"BSD-3-Clause"
] | null | null | null |
eagleye_core/navigation/src/smoothing.cpp
|
shjzhang/eagleye
|
e4e105d3a5438cf5ee36f1cc525ff87313923fc5
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2019, Map IV, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the Map IV, Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER 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.
/*
* smoothing.cpp
* Author MapIV Takanose
*/
#include "coordinate.hpp"
#include "navigation.hpp"
void smoothing_estimate(rtklib_msgs::RtklibNav rtklib_nav, eagleye_msgs::VelocityScaleFactor velocity_scale_factor,SmoothingParameter smoothing_parameter, SmoothingStatus* smoothing_status,eagleye_msgs::Position* gnss_smooth_pos_enu)
{
double ecef_pos[3];
double ecef_base_pos[3];
double enu_pos[3];
std::size_t index_length;
std::size_t time_buffer_length;
std::size_t velocity_index_length;
if(gnss_smooth_pos_enu->ecef_base_pos.x == 0 && gnss_smooth_pos_enu->ecef_base_pos.y == 0 && gnss_smooth_pos_enu->ecef_base_pos.z == 0)
{
gnss_smooth_pos_enu->ecef_base_pos.x = rtklib_nav.ecef_pos.x;
gnss_smooth_pos_enu->ecef_base_pos.y = rtklib_nav.ecef_pos.y;
gnss_smooth_pos_enu->ecef_base_pos.z = rtklib_nav.ecef_pos.z;
if(smoothing_parameter.ecef_base_pos_x != 0 && smoothing_parameter.ecef_base_pos_y != 0 && smoothing_parameter.ecef_base_pos_z != 0){
gnss_smooth_pos_enu->ecef_base_pos.x = smoothing_parameter.ecef_base_pos_x;
gnss_smooth_pos_enu->ecef_base_pos.y = smoothing_parameter.ecef_base_pos_y;
gnss_smooth_pos_enu->ecef_base_pos.z = smoothing_parameter.ecef_base_pos_z;
}
}
ecef_pos[0] = rtklib_nav.ecef_pos.x;
ecef_pos[1] = rtklib_nav.ecef_pos.y;
ecef_pos[2] = rtklib_nav.ecef_pos.z;
ecef_base_pos[0] = gnss_smooth_pos_enu->ecef_base_pos.x;
ecef_base_pos[1] = gnss_smooth_pos_enu->ecef_base_pos.y;
ecef_base_pos[2] = gnss_smooth_pos_enu->ecef_base_pos.z;
xyz2enu(ecef_pos, ecef_base_pos, enu_pos);
smoothing_status->time_buffer.push_back(rtklib_nav.header.stamp.toSec());
smoothing_status->enu_pos_x_buffer.push_back(enu_pos[0]);
smoothing_status->enu_pos_y_buffer.push_back(enu_pos[1]);
smoothing_status->enu_pos_z_buffer.push_back(enu_pos[2]);
smoothing_status->correction_velocity_buffer.push_back(velocity_scale_factor.correction_velocity.linear.x);
time_buffer_length = std::distance(smoothing_status->time_buffer.begin(), smoothing_status->time_buffer.end());
if (time_buffer_length > smoothing_parameter.estimated_number_max)
{
smoothing_status->time_buffer.erase(smoothing_status->time_buffer.begin());
smoothing_status->enu_pos_x_buffer.erase(smoothing_status->enu_pos_x_buffer.begin());
smoothing_status->enu_pos_y_buffer.erase(smoothing_status->enu_pos_y_buffer.begin());
smoothing_status->enu_pos_z_buffer.erase(smoothing_status->enu_pos_z_buffer.begin());
smoothing_status->correction_velocity_buffer.erase(smoothing_status->correction_velocity_buffer.begin());
}
if (smoothing_status->estimated_number < smoothing_parameter.estimated_number_max)
{
++smoothing_status->estimated_number;
gnss_smooth_pos_enu->status.enabled_status = false;
}
else
{
smoothing_status->estimated_number = smoothing_parameter.estimated_number_max;
gnss_smooth_pos_enu->status.enabled_status = true;
}
std::vector<int> velocity_index;
std::vector<int> index;
int i;
double gnss_smooth_pos[3] = {0};
double sum_gnss_pos[3] = {0};
if (smoothing_status->estimated_number == smoothing_parameter.estimated_number_max)
{
for (i = 0; i < smoothing_status->estimated_number; i++)
{
index.push_back(i);
if (smoothing_status->correction_velocity_buffer[i] > smoothing_parameter.estimated_velocity_threshold)
{
velocity_index.push_back(i);
}
}
index_length = std::distance(index.begin(), index.end());
velocity_index_length = std::distance(velocity_index.begin(), velocity_index.end());
for (i = 0; i < velocity_index_length; i++)
{
sum_gnss_pos[0] = sum_gnss_pos[0] + smoothing_status->enu_pos_x_buffer[velocity_index[i]];
sum_gnss_pos[1] = sum_gnss_pos[1] + smoothing_status->enu_pos_y_buffer[velocity_index[i]];
sum_gnss_pos[2] = sum_gnss_pos[2] + smoothing_status->enu_pos_z_buffer[velocity_index[i]];
}
if (velocity_index_length > index_length * smoothing_parameter.estimated_threshold)
{
gnss_smooth_pos[0] = sum_gnss_pos[0]/velocity_index_length;
gnss_smooth_pos[1] = sum_gnss_pos[1]/velocity_index_length;
gnss_smooth_pos[2] = sum_gnss_pos[2]/velocity_index_length;
gnss_smooth_pos_enu->status.estimate_status = true;
}
else
{
gnss_smooth_pos[0] = smoothing_status->last_pos[0];
gnss_smooth_pos[1] = smoothing_status->last_pos[1];
gnss_smooth_pos[2] = smoothing_status->last_pos[2];
gnss_smooth_pos_enu->status.estimate_status = false;
}
smoothing_status->last_pos[0] = gnss_smooth_pos[0];
smoothing_status->last_pos[1] = gnss_smooth_pos[1];
smoothing_status->last_pos[2] = gnss_smooth_pos[2];
}
gnss_smooth_pos_enu->enu_pos.x = gnss_smooth_pos[0];
gnss_smooth_pos_enu->enu_pos.y = gnss_smooth_pos[1];
gnss_smooth_pos_enu->enu_pos.z = gnss_smooth_pos[2];
// gnss_smooth_pos_enu->ecef_base_pos = enu_absolute_pos.ecef_base_pos;
gnss_smooth_pos_enu->header = rtklib_nav.header;
}
| 44.310811
| 233
| 0.76319
|
shjzhang
|
2cc564d474ea0a6388fb3bc8a018f3293f77c791
| 291
|
cpp
|
C++
|
src/Client/MainClient.cpp
|
Marukyu/NecroEdit
|
4b2380cc3417c6578476a213e05f4cbc846e5a77
|
[
"MIT",
"Unlicense"
] | 13
|
2016-04-02T14:21:49.000Z
|
2021-01-10T17:32:43.000Z
|
src/Client/MainClient.cpp
|
Marukyu/NecroEdit
|
4b2380cc3417c6578476a213e05f4cbc846e5a77
|
[
"MIT",
"Unlicense"
] | 24
|
2016-04-02T12:08:39.000Z
|
2021-01-27T01:21:58.000Z
|
src/Client/MainClient.cpp
|
Marukyu/NecroEdit
|
4b2380cc3417c6578476a213e05f4cbc846e5a77
|
[
"MIT",
"Unlicense"
] | 6
|
2016-04-02T12:05:28.000Z
|
2017-05-10T14:13:39.000Z
|
/**
* NecroEdit v1.0
*/
#include <Client/System/NEApplication.hpp>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
// put arguments into vector.
std::vector<std::string> args(argv, argv+argc);
// run client.
NEApplication client;
return client.run(args);
}
| 16.166667
| 48
| 0.680412
|
Marukyu
|
2ccd42cb5391a7f47e2769fe6befd68a23307375
| 2,348
|
cpp
|
C++
|
src/saveload/animated_tile_sl.cpp
|
trademarks/OpenTTD
|
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
|
[
"Unlicense"
] | 8
|
2016-10-21T09:01:43.000Z
|
2021-05-31T06:32:14.000Z
|
src/saveload/animated_tile_sl.cpp
|
blackberry/OpenTTD
|
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
|
[
"Unlicense"
] | null | null | null |
src/saveload/animated_tile_sl.cpp
|
blackberry/OpenTTD
|
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
|
[
"Unlicense"
] | 4
|
2017-05-16T00:15:58.000Z
|
2020-08-06T01:46:31.000Z
|
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file animated_tile_sl.cpp Code handling saving and loading of animated tiles */
#include "../stdafx.h"
#include "../tile_type.h"
#include "../core/alloc_func.hpp"
#include "saveload.h"
extern TileIndex *_animated_tile_list;
extern uint _animated_tile_count;
extern uint _animated_tile_allocated;
/**
* Save the ANIT chunk.
*/
static void Save_ANIT()
{
SlSetLength(_animated_tile_count * sizeof(*_animated_tile_list));
SlArray(_animated_tile_list, _animated_tile_count, SLE_UINT32);
}
/**
* Load the ANIT chunk; the chunk containing the animated tiles.
*/
static void Load_ANIT()
{
/* Before version 80 we did NOT have a variable length animated tile table */
if (IsSavegameVersionBefore(80)) {
/* In pre version 6, we has 16bit per tile, now we have 32bit per tile, convert it ;) */
SlArray(_animated_tile_list, 256, IsSavegameVersionBefore(6) ? (SLE_FILE_U16 | SLE_VAR_U32) : SLE_UINT32);
for (_animated_tile_count = 0; _animated_tile_count < 256; _animated_tile_count++) {
if (_animated_tile_list[_animated_tile_count] == 0) break;
}
return;
}
_animated_tile_count = (uint)SlGetFieldLength() / sizeof(*_animated_tile_list);
/* Determine a nice rounded size for the amount of allocated tiles */
_animated_tile_allocated = 256;
while (_animated_tile_allocated < _animated_tile_count) _animated_tile_allocated *= 2;
_animated_tile_list = ReallocT<TileIndex>(_animated_tile_list, _animated_tile_allocated);
SlArray(_animated_tile_list, _animated_tile_count, SLE_UINT32);
}
/**
* "Definition" imported by the saveload code to be able to load and save
* the animated tile table.
*/
extern const ChunkHandler _animated_tile_chunk_handlers[] = {
{ 'ANIT', Save_ANIT, Load_ANIT, NULL, NULL, CH_RIFF | CH_LAST},
};
| 36.6875
| 185
| 0.758518
|
trademarks
|
2cd2c0adfce8b919bd91624d1a48b2a47ef0087e
| 1,031
|
cpp
|
C++
|
alakajam13_states/State.InPlay.Next.cpp
|
playdeezgames/tggd_alakajam13
|
e4433a14d4e74cc4f711c7bb6610c87e2fd9b377
|
[
"MIT"
] | null | null | null |
alakajam13_states/State.InPlay.Next.cpp
|
playdeezgames/tggd_alakajam13
|
e4433a14d4e74cc4f711c7bb6610c87e2fd9b377
|
[
"MIT"
] | null | null | null |
alakajam13_states/State.InPlay.Next.cpp
|
playdeezgames/tggd_alakajam13
|
e4433a14d4e74cc4f711c7bb6610c87e2fd9b377
|
[
"MIT"
] | null | null | null |
#include "UIState.h"
#include "States.h"
#include <Game.Audio.Mux.h>
#include <Application.OnEnter.h>
#include <Application.Update.h>
#include <Application.UIState.h>
#include <Game.Actors.h>
#include <Game.ActorTypes.h>
namespace state::in_play
{
static const ::UIState CURRENT_STATE = ::UIState::IN_PLAY_NEXT;
static void OnEnter()
{
if (game::Actors::IsAnythingAlive())
{
auto actor = game::Actors::GetCurrent();
auto descriptor = game::ActorTypes::Read(actor.actorType);
while (!descriptor.playControlled)
{
game::Actors::Act();
game::Actors::Next();
actor = game::Actors::GetCurrent();
descriptor = game::ActorTypes::Read(actor.actorType);
}
application::UIState::Write(::UIState::IN_PLAY_BOARD);
return;
}
application::UIState::Write(::UIState::GAME_OVER);
}
static void OnUpdate(const unsigned int&)
{
OnEnter();
}
void Next::Start()
{
::application::OnEnter::AddHandler(CURRENT_STATE, OnEnter);
::application::Update::AddHandler(CURRENT_STATE, OnUpdate);
}
}
| 23.976744
| 64
| 0.695441
|
playdeezgames
|
2cdb1d4f07e8ac447b1d5ba529a392cca7b05031
| 3,218
|
cc
|
C++
|
libcef_dll/cpptoc/media_event_callback_cpptoc.cc
|
frogbywyplay/appframeworks_cef
|
12e3a6d32370b4f72707b493ab951a5d8cb3989d
|
[
"BSD-3-Clause"
] | null | null | null |
libcef_dll/cpptoc/media_event_callback_cpptoc.cc
|
frogbywyplay/appframeworks_cef
|
12e3a6d32370b4f72707b493ab951a5d8cb3989d
|
[
"BSD-3-Clause"
] | null | null | null |
libcef_dll/cpptoc/media_event_callback_cpptoc.cc
|
frogbywyplay/appframeworks_cef
|
12e3a6d32370b4f72707b493ab951a5d8cb3989d
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/media_event_callback_cpptoc.h"
namespace {
// MEMBER FUNCTIONS - Body may be edited by hand.
void CEF_CALLBACK media_event_callback_end_of_stream(
struct _cef_media_event_callback_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->EndOfStream();
}
void CEF_CALLBACK media_event_callback_resolution_changed(
struct _cef_media_event_callback_t* self, int width, int height) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->ResolutionChanged(
width,
height);
}
void CEF_CALLBACK media_event_callback_video_pts(
struct _cef_media_event_callback_t* self, int64 pts) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->VideoPTS(
pts);
}
void CEF_CALLBACK media_event_callback_audio_pts(
struct _cef_media_event_callback_t* self, int64 pts) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->AudioPTS(
pts);
}
void CEF_CALLBACK media_event_callback_have_enough(
struct _cef_media_event_callback_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->HaveEnough();
}
} // namespace
// CONSTRUCTOR - Do not edit by hand.
CefMediaEventCallbackCppToC::CefMediaEventCallbackCppToC() {
GetStruct()->end_of_stream = media_event_callback_end_of_stream;
GetStruct()->resolution_changed = media_event_callback_resolution_changed;
GetStruct()->video_pts = media_event_callback_video_pts;
GetStruct()->audio_pts = media_event_callback_audio_pts;
GetStruct()->have_enough = media_event_callback_have_enough;
}
template<> CefRefPtr<CefMediaEventCallback> CefCppToC<CefMediaEventCallbackCppToC,
CefMediaEventCallback, cef_media_event_callback_t>::UnwrapDerived(
CefWrapperType type, cef_media_event_callback_t* s) {
NOTREACHED() << "Unexpected class type: " << type;
return NULL;
}
#ifndef NDEBUG
template<> base::AtomicRefCount CefCppToC<CefMediaEventCallbackCppToC,
CefMediaEventCallback, cef_media_event_callback_t>::DebugObjCt = 0;
#endif
template<> CefWrapperType CefCppToC<CefMediaEventCallbackCppToC,
CefMediaEventCallback, cef_media_event_callback_t>::kWrapperType =
WT_MEDIA_EVENT_CALLBACK;
| 28.732143
| 82
| 0.745183
|
frogbywyplay
|
2ce05467170d8885f088e2d9166c4194db95a873
| 19,961
|
cpp
|
C++
|
Core/burn/drv/pre90s/d_marineb.cpp
|
atship/FinalBurn-X
|
3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d
|
[
"Apache-2.0"
] | 17
|
2018-05-24T05:20:45.000Z
|
2021-12-24T07:27:22.000Z
|
Core/burn/drv/pre90s/d_marineb.cpp
|
atship/FinalBurn-X
|
3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d
|
[
"Apache-2.0"
] | 6
|
2016-10-20T02:36:07.000Z
|
2017-03-08T15:23:06.000Z
|
Core/burn/drv/pre90s/d_marineb.cpp
|
atship/FinalBurn-X
|
3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d
|
[
"Apache-2.0"
] | 5
|
2019-01-21T00:45:00.000Z
|
2021-07-20T08:34:22.000Z
|
// Based on original MAME driver writen by Zsolt Vasvari
#include "tiles_generic.h"
#include "z80_intf.h"
#include "driver.h"
extern "C" {
#include "ay8910.h"
}
enum { SPRINGER = 0, MARINEB };
static UINT8 *AllMem;
static UINT8 *MemEnd;
static UINT8 *RamStart;
static UINT8 *RamEnd;
static UINT32 *TempPalette;
static UINT32 *DrvPalette;
static UINT8 DrvRecalcPalette;
static UINT8 DrvInputPort0[8];
static UINT8 DrvInputPort1[8];
static UINT8 DrvInputPort2[8];
static UINT8 DrvDip;
static UINT8 DrvInput[3];
static UINT8 DrvReset;
static UINT8 *DrvZ80ROM;
static UINT8 *DrvZ80RAM;
static UINT8 *DrvColPROM;
static UINT8 *DrvVidRAM;
static UINT8 *DrvColRAM;
static UINT8 *DrvSprRAM;
static UINT8 *DrvGfxROM0;
static UINT8 *DrvGfxROM1;
static UINT8 *DrvGfxROM2;
static UINT8 DrvPaletteBank;
static UINT8 DrvColumnScroll;
static UINT8 ActiveLowFlipscreen;
static UINT8 DrvFlipScreenY;
static UINT8 DrvFlipScreenX;
static INT32 DrvInterruptEnable;
static INT32 hardware;
static INT16 *pAY8910Buffer[3];
static struct BurnInputInfo MarinebInputList[] =
{
{"P1 Coin" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" },
{"P1 Start" , BIT_DIGITAL , DrvInputPort2 + 2, "p1 start" },
{"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" },
{"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" },
{"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 left" },
{"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 right" },
{"P1 Fire" , BIT_DIGITAL , DrvInputPort2 + 4, "p1 fire 1" },
{"P2 Start" , BIT_DIGITAL , DrvInputPort2 + 3, "p2 start" },
{"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" },
{"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" },
{"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 left" },
{"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 right" },
{"P2 Fire" , BIT_DIGITAL , DrvInputPort2 + 5, "p2 fire 1" },
{"Reset" , BIT_DIGITAL , &DrvReset , "reset" },
{"Dip" , BIT_DIPSWITCH, &DrvDip , "dip" },
};
STDINPUTINFO(Marineb)
static struct BurnDIPInfo MarinebDIPList[]=
{
{0x0E, 0xFF, 0xFF, 0x40, NULL },
{0 , 0xFE, 0 , 4, "Lives" },
{0x0E, 0x01, 0x03, 0x00, "3" },
{0x0E, 0x01, 0x03, 0x01, "4" },
{0x0E, 0x01, 0x03, 0x02, "5" },
{0x0E, 0x01, 0x03, 0x03, "6" },
{0 , 0xFE, 0 , 2, "Coinage" },
{0x0E, 0x01, 0x1C, 0x00, "1 Coin 1 Credit" },
{0x0E, 0x01, 0x1C, 0x1C, "Free Play" },
{0 , 0xFE, 0 , 2, "Bonus Life" },
{0x0E, 0x01, 0x20, 0x00, "20000 50000" },
{0x0E, 0x01, 0x20, 0x20, "40000 70000" },
{0 , 0xFE, 0 , 2, "Cabinet" },
{0x0E, 0x01, 0x40, 0x40, "Upright" },
{0x0E, 0x01, 0x40, 0x00, "Cocktail" },
};
STDDIPINFO(Marineb)
static INT32 MemIndex()
{
UINT8 *Next; Next = AllMem;
DrvZ80ROM = Next; Next += 0x10000;
DrvColPROM = Next; Next += 0x200;
DrvGfxROM0 = Next; Next += 512 * 8 * 8;
DrvGfxROM1 = Next; Next += 64 * 16 * 16;
DrvGfxROM2 = Next; Next += 64 * 32 * 32;
TempPalette = (UINT32*)Next; Next += 0x100 * sizeof(UINT32); // calculate one time
DrvPalette = (UINT32*)Next; Next += 0x100 * sizeof(UINT32);
pAY8910Buffer[0] = (INT16*)Next; Next += nBurnSoundLen * sizeof(INT16);
pAY8910Buffer[1] = (INT16*)Next; Next += nBurnSoundLen * sizeof(INT16);
pAY8910Buffer[2] = (INT16*)Next; Next += nBurnSoundLen * sizeof(INT16);
RamStart = Next;
DrvZ80RAM = Next; Next += 0x800;
DrvVidRAM = Next; Next += 0x400;
DrvSprRAM = Next; Next += 0x100;
DrvColRAM = Next; Next += 0x400;
RamEnd = Next;
MemEnd = Next;
return 0;
}
static void CleanAndInitStuff()
{
DrvPaletteBank = 0;
DrvColumnScroll = 0;
DrvFlipScreenY = 0;
DrvFlipScreenX = 0;
DrvInterruptEnable = 0;
hardware = 0;
ActiveLowFlipscreen = 0;
memset(DrvInputPort0, 0, 8);
memset(DrvInputPort1, 0, 8);
memset(DrvInputPort2, 0, 8);
memset(DrvInput, 0, 3);
DrvDip = 0;
DrvReset = 0;
}
UINT8 __fastcall marineb_read(UINT16 address)
{
switch (address) {
case 0xa800:
return DrvInput[0];
case 0xa000:
return DrvInput[1];
case 0xb000:
return DrvDip;
case 0xb800:
return DrvInput[2];
}
return 0;
}
void __fastcall marineb_write(UINT16 address, UINT8 data)
{
switch (address) {
case 0x9800:
DrvColumnScroll = data;
return;
case 0x9a00:
DrvPaletteBank = (DrvPaletteBank & 0x02) | (data & 0x01);
return;
case 0x9c00:
DrvPaletteBank = (DrvPaletteBank & 0x01) | ((data & 0x01) << 1);
return;
case 0xa000:
DrvInterruptEnable = data;
return;
case 0xa001:
DrvFlipScreenY = data ^ ActiveLowFlipscreen;
return;
case 0xa002:
DrvFlipScreenX = data ^ ActiveLowFlipscreen;
return;
}
}
void __fastcall marineb_write_port(UINT16 port, UINT8 data)
{
switch (port & 0xFF) {
case 0x08:
case 0x09:
AY8910Write(0, port & 1, data);
break;
}
}
static INT32 DrvDoReset()
{
memset (RamStart, 0, RamEnd - RamStart);
ZetOpen(0);
ZetReset();
ZetClose();
AY8910Reset(0);
DrvPaletteBank = 0;
DrvColumnScroll = 0;
DrvFlipScreenY = 0;
DrvFlipScreenX = 0;
DrvInterruptEnable = 0;
return 0;
}
static void DrvCreatePalette()
{
for (INT32 i = 0; i < 256; i++)
{
INT32 bit0, bit1, bit2, r, g, b;
// Red
bit0 = (DrvColPROM[i] >> 0) & 0x01;
bit1 = (DrvColPROM[i] >> 1) & 0x01;
bit2 = (DrvColPROM[i] >> 2) & 0x01;
r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
// Green
bit0 = (DrvColPROM[i] >> 3) & 0x01;
bit1 = (DrvColPROM[i + 256] >> 0) & 0x01;
bit2 = (DrvColPROM[i + 256] >> 1) & 0x01;
g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
// Blue
bit0 = 0;
bit1 = (DrvColPROM[i + 256] >> 2) & 0x01;
bit2 = (DrvColPROM[i + 256] >> 3) & 0x01;
b = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
TempPalette[i] = (r << 16) | (g << 8) | (b << 0);
}
}
static INT32 MarinebCharPlane[2] = { 0, 4 };
static INT32 MarinebCharXOffs[8] = { 0, 1, 2, 3, 64, 65, 66, 67 };
static INT32 MarinebCharYOffs[8] = { 0, 8, 16, 24, 32, 40, 48, 56 };
static INT32 MarinebSmallSpriteCharPlane[2] = { 0, 65536 };
static INT32 MarinebSmallSpriteXOffs[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71 };
static INT32 MarinebSmallSpriteYOffs[16] = { 0, 8, 16, 24, 32, 40, 48, 56, 128, 136, 144, 152, 160, 168, 176, 184 };
static INT32 MarinebBigSpriteCharPlane[2] = { 0, 65536 };
static INT32 MarinebBigSpriteXOffs[32] = { 0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71, 256, 257, 258, 259, 260, 261, 262, 263, 320, 321, 322, 323, 324, 325, 326, 327 };
static INT32 MarinebBigSpriteYOffs[32] = { 0, 8, 16, 24, 32, 40, 48, 56, 128, 136, 144, 152, 160, 168, 176, 184, 512, 520, 528, 536, 544, 552, 560, 568, 640, 648, 656, 664, 672, 680, 688, 696 };
static INT32 MarinebLoadRoms()
{
// Load roms
// Z80
for (INT32 i = 0; i < 5; i++) {
if (BurnLoadRom(DrvZ80ROM + (i * 0x1000), i, 1)) return 1;
}
UINT8 *tmp = (UINT8*)BurnMalloc(0x4000);
if (tmp == NULL) return 1;
// Chars
memset(tmp, 0, 0x2000);
if (BurnLoadRom(tmp, 5, 1)) return 1;
GfxDecode(0x200, 2, 8, 8, MarinebCharPlane, MarinebCharXOffs, MarinebCharYOffs, 0x80, tmp, DrvGfxROM0);
// Sprites
memset(tmp, 0, 0x4000);
if (BurnLoadRom(tmp, 6, 1)) return 1;
if (BurnLoadRom(tmp + 0x2000, 7, 1)) return 1;
// Small Sprites
GfxDecode(0x40, 2, 16, 16, MarinebSmallSpriteCharPlane, MarinebSmallSpriteXOffs, MarinebSmallSpriteYOffs, 0x100, tmp, DrvGfxROM1);
// Big Sprites
GfxDecode(0x40, 2, 32, 32, MarinebBigSpriteCharPlane, MarinebBigSpriteXOffs, MarinebBigSpriteYOffs, 0x400, tmp, DrvGfxROM2);
BurnFree(tmp);
// ColorRoms
if (BurnLoadRom(DrvColPROM, 8, 1)) return 1;
if (BurnLoadRom(DrvColPROM + 0x100, 9, 1)) return 1;
return 0;
}
static INT32 SpringerLoadRoms()
{
// Load roms
// Z80
for (INT32 i = 0; i < 5; i++) {
if (BurnLoadRom(DrvZ80ROM + (i * 0x1000), i, 1)) return 1;
}
UINT8 *tmp = (UINT8*)BurnMalloc(0x4000);
if (tmp == NULL) return 1;
// Chars
memset(tmp, 0, 0x4000);
if (BurnLoadRom(tmp, 5, 1)) return 1;
if (BurnLoadRom(tmp + 0x1000, 6, 1)) return 1;
GfxDecode(0x200, 2, 8, 8, MarinebCharPlane, MarinebCharXOffs, MarinebCharYOffs, 0x80, tmp, DrvGfxROM0);
memset(tmp, 0, 0x4000);
if (BurnLoadRom(tmp, 7, 1)) return 1;
if (BurnLoadRom(tmp + 0x2000, 8, 1)) return 1;
// Small Sprites
GfxDecode(0x40, 2, 16, 16, MarinebSmallSpriteCharPlane, MarinebSmallSpriteXOffs, MarinebSmallSpriteYOffs, 0x100, tmp, DrvGfxROM1);
// Big Sprites
GfxDecode(0x40, 2, 32, 32, MarinebBigSpriteCharPlane, MarinebBigSpriteXOffs, MarinebBigSpriteYOffs, 0x400, tmp, DrvGfxROM2);
BurnFree(tmp);
// ColorRoms
if (BurnLoadRom(DrvColPROM, 9, 1)) return 1;
if (BurnLoadRom(DrvColPROM + 0x100, 10, 1)) return 1;
return 0;
}
static INT32 DrvInit()
{
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
switch(hardware) {
case MARINEB:
MarinebLoadRoms();
break;
case SPRINGER:
SpringerLoadRoms();
break;
}
DrvCreatePalette();
ZetInit(0);
ZetOpen(0);
ZetMapArea (0x0000, 0x7fff, 0, DrvZ80ROM);
ZetMapArea (0x0000, 0x7fff, 2, DrvZ80ROM);
ZetMapArea (0x8000, 0x87ff, 0, DrvZ80RAM);
ZetMapArea (0x8000, 0x87ff, 1, DrvZ80RAM);
ZetMapArea (0x8000, 0x87ff, 2, DrvZ80RAM);
ZetMapArea (0x8800, 0x8bff, 0, DrvVidRAM);
ZetMapArea (0x8800, 0x8bff, 1, DrvVidRAM);
ZetMapArea (0x8800, 0x8bff, 2, DrvVidRAM);
ZetMapArea (0x8c00, 0x8c3f, 0, DrvSprRAM);
ZetMapArea (0x8c00, 0x8c3f, 1, DrvSprRAM);
ZetMapArea (0x8c00, 0x8c3f, 2, DrvSprRAM);
ZetMapArea (0x9000, 0x93ff, 0, DrvColRAM);
ZetMapArea (0x9000, 0x93ff, 1, DrvColRAM);
ZetMapArea (0x9000, 0x93ff, 2, DrvColRAM);
ZetSetReadHandler(marineb_read);
ZetSetWriteHandler(marineb_write);
ZetSetOutHandler(marineb_write_port);
ZetClose();
AY8910Init(0, 1500000, nBurnSoundRate, NULL, NULL, NULL, NULL);
AY8910SetAllRoutes(0, 0.50, BURN_SND_ROUTE_BOTH);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 DrvExit()
{
GenericTilesExit();
ZetExit();
AY8910Exit(0);
BurnFree (AllMem);
CleanAndInitStuff();
return 0;
}
static void RenderMarinebBg()
{
INT32 TileIndex = 0;
for (INT32 my = 0; my < 32; my++) {
for (INT32 mx = 0; mx < 32; mx++) {
TileIndex = (my * 32) + mx;
INT32 code = DrvVidRAM[TileIndex];
INT32 color = DrvColRAM[TileIndex];
code |= ((color & 0xc0) << 2);
color &= 0x0f;
color |= DrvPaletteBank << 4;
INT32 flipx = (color >> 4) & 0x02;
INT32 flipy = (color >> 4) & 0x01;
INT32 x = mx << 3;
INT32 y = my << 3;
// stuff from 192 to 256 does not scroll
if ((x >> 3) < 24) {
y -= DrvColumnScroll;
if (y < -7) y += 256;
}
y -= 16;
if (flipy) {
if (flipx) {
Render8x8Tile_FlipXY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_FlipY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
} else {
if (flipx) {
Render8x8Tile_FlipX_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
}
}
}
}
static void RenderSpringerBg()
{
INT32 TileIndex = 0;
for (INT32 my = 0; my < 32; my++) {
for (INT32 mx = 0; mx < 32; mx++) {
TileIndex = (my * 32) + mx;
INT32 code = DrvVidRAM[TileIndex];
INT32 color = DrvColRAM[TileIndex];
code |= ((color & 0xc0) << 2);
color &= 0x0f;
color |= DrvPaletteBank << 4;
INT32 flipx = (color >> 4) & 0x02;
INT32 flipy = (color >> 4) & 0x01;
INT32 x = mx << 3;
INT32 y = my << 3;
y -= 16; // remove garbage on left side
if (flipy) {
if (flipx) {
Render8x8Tile_FlipXY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_FlipY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
} else {
if (flipx) {
Render8x8Tile_FlipX_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
}
}
}
}
static void MarinebDrawSprites()
{
// Render Tiles
RenderMarinebBg();
for (INT32 offs = 0x0f; offs >= 0; offs--) {
INT32 gfx, sx, sy, code, color, flipx, flipy, offs2;
if ((offs == 0) || (offs == 2))
continue;
if (offs < 8) {
offs2 = 0x0018 + offs;
} else {
offs2 = 0x03d8 - 8 + offs;
}
code = DrvVidRAM[offs2];
sx = DrvVidRAM[offs2 + 0x20];
sy = DrvColRAM[offs2];
color = (DrvColRAM[offs2 + 0x20] & 0x0f) + 16 * DrvPaletteBank;
flipx = code & 0x02;
flipy = !(code & 0x01);
if (offs < 4) {
gfx = 2;
code = (code >> 4) | ((code & 0x0c) << 2);
} else {
gfx = 1;
code >>= 2;
}
if (!DrvFlipScreenY) {
if (gfx == 1) {
sy = 256 - 16 - sy;
} else {
sy = 256 - 32 - sy;
}
flipy = !flipy;
}
if (DrvFlipScreenX) {
sx++;
}
sy -= 16; // proper alignement
// Small Sprites
if (gfx == 1) {
if (flipy) {
if (flipx) {
Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
} else {
if (flipx) {
Render16x16Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
}
// Big sprites
} else {
if (flipy) {
if (flipx) {
Render32x32Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
} else {
if (flipx) {
Render32x32Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
}
}
}
}
static void SpringerDrawSprites()
{
// Render Tiles
RenderSpringerBg();
for (INT32 offs = 0x0f; offs >= 0; offs--)
{
INT32 gfx, sx, sy, code, color, flipx, flipy, offs2;
if ((offs == 0) || (offs == 2))
continue;
offs2 = 0x0010 + offs;
code = DrvVidRAM[offs2];
sx = 240 - DrvVidRAM[offs2 + 0x20];
sy = DrvColRAM[offs2];
color = (DrvColRAM[offs2 + 0x20] & 0x0f) + 16 * DrvPaletteBank;
flipx = !(code & 0x02);
flipy = !(code & 0x01);
if (offs < 4)
{
sx -= 0x10;
gfx = 2;
code = (code >> 4) | ((code & 0x0c) << 2);
}
else
{
gfx = 1;
code >>= 2;
}
if (!DrvFlipScreenY) {
if (gfx == 1) {
sy = 256 - 16 - sy;
} else {
sy = 256 - 32 - sy;
}
flipy = !flipy;
}
if (!DrvFlipScreenX)
{
sx--;
}
sy -= 16; // proper alignement
// Small Sprites
if (gfx == 1) {
if (flipy) {
if (flipx) {
Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
} else {
if (flipx) {
Render16x16Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
}
// Big Sprites
} else {
if (flipy) {
if (flipx) {
Render32x32Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
} else {
if (flipx) {
Render32x32Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
}
}
}
}
static INT32 DrvDraw()
{
if (DrvRecalcPalette) {
for (INT32 i = 0; i < 256; i++) {
UINT32 tmp = TempPalette[i];
// Recalc Colors
DrvPalette[i] = BurnHighCol((tmp >> 16) & 0xFF, (tmp >> 8) & 0xFF, tmp & 0xFF, 0);
}
DrvRecalcPalette = 0;
}
switch(hardware) {
case MARINEB:
MarinebDrawSprites();
break;
case SPRINGER:
SpringerDrawSprites();
break;
}
BurnTransferCopy(DrvPalette);
return 0;
}
static INT32 DrvFrame()
{
if (DrvReset) {
DrvDoReset();
}
DrvInput[0] = DrvInput[1] = DrvInput[2] = 0;
for (INT32 i = 0; i < 8; i++) {
DrvInput[0] |= (DrvInputPort0[i] & 1) << i;
DrvInput[1] |= (DrvInputPort1[i] & 1) << i;
DrvInput[2] |= (DrvInputPort2[i] & 1) << i;
}
ZetOpen(0);
ZetRun(3072000 / 60);
if (DrvInterruptEnable) ZetNmi();
ZetClose();
if (pBurnSoundOut) {
AY8910Render(&pAY8910Buffer[0], pBurnSoundOut, nBurnSoundLen, 0);
}
if (pBurnDraw) {
DrvDraw();
}
return 0;
}
static INT32 DrvScan(INT32 nAction,INT32 *pnMin)
{
struct BurnArea ba;
if (pnMin) {
*pnMin = 0x029708;
}
if (nAction & ACB_VOLATILE) {
memset(&ba, 0, sizeof(ba));
ba.Data = RamStart;
ba.nLen = RamEnd - RamStart;
ba.szName = "All Ram";
BurnAcb(&ba);
ZetScan(nAction);
AY8910Scan(nAction, pnMin);
}
return 0;
}
static INT32 MarinebInit()
{
CleanAndInitStuff();
hardware = MARINEB;
return DrvInit();
}
static INT32 SpringerInit()
{
CleanAndInitStuff();
ActiveLowFlipscreen = 1;
hardware = SPRINGER;
return DrvInit();
}
// Marine Boy
static struct BurnRomInfo MarinebRomDesc[] = {
{ "marineb.1", 0x1000, 0x661d6540, BRF_ESS | BRF_PRG }, // 0 maincpu
{ "marineb.2", 0x1000, 0x922da17f, BRF_ESS | BRF_PRG }, // 1
{ "marineb.3", 0x1000, 0x820a235b, BRF_ESS | BRF_PRG }, // 2
{ "marineb.4", 0x1000, 0xa157a283, BRF_ESS | BRF_PRG }, // 3
{ "marineb.5", 0x1000, 0x9ffff9c0, BRF_ESS | BRF_PRG }, // 4
{ "marineb.6", 0x2000, 0xee53ec2e, BRF_GRA }, // 5 gfx1
{ "marineb.8", 0x2000, 0xdc8bc46c, BRF_GRA }, // 6 gfx2
{ "marineb.7", 0x2000, 0x9d2e19ab, BRF_GRA }, // 7
{ "marineb.1b", 0x100, 0xf32d9472, BRF_GRA }, // 8 proms
{ "marineb.1c", 0x100, 0x93c69d3e, BRF_GRA }, // 9
};
STD_ROM_PICK(Marineb)
STD_ROM_FN(Marineb)
struct BurnDriver BurnDrvMarineb = {
"marineb", NULL, NULL, NULL, "1982",
"Marine Boy\0", NULL, "Orca", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_MISC_PRE90S, 0, 0,
NULL, MarinebRomInfo, MarinebRomName, NULL, NULL, MarinebInputInfo, MarinebDIPInfo,
MarinebInit, DrvExit, DrvFrame, DrvDraw, DrvScan,
&DrvRecalcPalette, 0x100, 256, 224, 4, 3
};
// Springer
static struct BurnRomInfo SpringerRomDesc[] = {
{ "springer.1", 0x1000, 0x0794103a, BRF_ESS | BRF_PRG }, // 0 maincpu
{ "springer.2", 0x1000, 0xf4aecd9a, BRF_ESS | BRF_PRG }, // 1
{ "springer.3", 0x1000, 0x2f452371, BRF_ESS | BRF_PRG }, // 2
{ "springer.4", 0x1000, 0x859d1bf5, BRF_ESS | BRF_PRG }, // 3
{ "springer.5", 0x1000, 0x72adbbe3, BRF_ESS | BRF_PRG }, // 4
{ "springer.6", 0x1000, 0x6a961833, BRF_GRA }, // 5 gfx1
{ "springer.7", 0x1000, 0x95ab8fc0, BRF_GRA }, // 6
{ "springer.8", 0x1000, 0xa54bafdc, BRF_GRA }, // 7 gfx2
{ "springer.9", 0x1000, 0xfa302775, BRF_GRA }, // 8
{ "1b.vid", 0x100, 0xa2f935aa, BRF_GRA }, // 9 proms
{ "1c.vid", 0x100, 0xb95421f4, BRF_GRA }, // 10
};
STD_ROM_PICK(Springer)
STD_ROM_FN(Springer)
struct BurnDriver BurnDrvSpringer = {
"springer", NULL, NULL, NULL, "1982",
"Springer\0", NULL, "Orca", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 2, HARDWARE_MISC_PRE90S, 0, 0,
NULL, SpringerRomInfo, SpringerRomName, NULL, NULL, MarinebInputInfo, MarinebDIPInfo,
SpringerInit, DrvExit, DrvFrame, DrvDraw, DrvScan,
&DrvRecalcPalette, 0x100, 224, 256, 3, 4
};
| 23.791418
| 194
| 0.612645
|
atship
|
f8ea3449a2b90471a1688f3323dae99fd5cf10cc
| 33,461
|
cc
|
C++
|
src/system/proto/heartbeat.pb.cc
|
yipeiw/pserver
|
2a856ba0cda744e4b8adcd925238dd7d4609bea7
|
[
"Apache-2.0"
] | null | null | null |
src/system/proto/heartbeat.pb.cc
|
yipeiw/pserver
|
2a856ba0cda744e4b8adcd925238dd7d4609bea7
|
[
"Apache-2.0"
] | null | null | null |
src/system/proto/heartbeat.pb.cc
|
yipeiw/pserver
|
2a856ba0cda744e4b8adcd925238dd7d4609bea7
|
[
"Apache-2.0"
] | null | null | null |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: system/proto/heartbeat.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "system/proto/heartbeat.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace PS {
namespace {
const ::google::protobuf::Descriptor* HeartbeatReport_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
HeartbeatReport_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_system_2fproto_2fheartbeat_2eproto() {
protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"system/proto/heartbeat.proto");
GOOGLE_CHECK(file != NULL);
HeartbeatReport_descriptor_ = file->message_type(0);
static const int HeartbeatReport_offsets_[15] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, task_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, hostname_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, seconds_since_epoch_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, total_time_milli_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, busy_time_milli_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, net_in_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, net_out_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, process_cpu_usage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_cpu_usage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, process_rss_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, process_virt_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_in_use_gb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_in_use_percentage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_net_in_bw_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_net_out_bw_),
};
HeartbeatReport_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
HeartbeatReport_descriptor_,
HeartbeatReport::default_instance_,
HeartbeatReport_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(HeartbeatReport));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_system_2fproto_2fheartbeat_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
HeartbeatReport_descriptor_, &HeartbeatReport::default_instance());
}
} // namespace
void protobuf_ShutdownFile_system_2fproto_2fheartbeat_2eproto() {
delete HeartbeatReport::default_instance_;
delete HeartbeatReport_reflection_;
}
void protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\034system/proto/heartbeat.proto\022\002PS\"\373\002\n\017H"
"eartbeatReport\022\022\n\007task_id\030\001 \001(\005:\0010\022\020\n\010ho"
"stname\030\016 \001(\t\022\033\n\023seconds_since_epoch\030\002 \001("
"\r\022\030\n\020total_time_milli\030\r \001(\r\022\027\n\017busy_time"
"_milli\030\003 \001(\r\022\021\n\tnet_in_mb\030\004 \001(\r\022\022\n\nnet_o"
"ut_mb\030\005 \001(\r\022\031\n\021process_cpu_usage\030\006 \001(\r\022\026"
"\n\016host_cpu_usage\030\007 \001(\r\022\026\n\016process_rss_mb"
"\030\010 \001(\r\022\027\n\017process_virt_mb\030\t \001(\r\022\026\n\016host_"
"in_use_gb\030\n \001(\r\022\036\n\026host_in_use_percentag"
"e\030\017 \001(\r\022\026\n\016host_net_in_bw\030\013 \001(\r\022\027\n\017host_"
"net_out_bw\030\014 \001(\r", 416);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"system/proto/heartbeat.proto", &protobuf_RegisterTypes);
HeartbeatReport::default_instance_ = new HeartbeatReport();
HeartbeatReport::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_system_2fproto_2fheartbeat_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_system_2fproto_2fheartbeat_2eproto {
StaticDescriptorInitializer_system_2fproto_2fheartbeat_2eproto() {
protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto();
}
} static_descriptor_initializer_system_2fproto_2fheartbeat_2eproto_;
// ===================================================================
#ifndef _MSC_VER
const int HeartbeatReport::kTaskIdFieldNumber;
const int HeartbeatReport::kHostnameFieldNumber;
const int HeartbeatReport::kSecondsSinceEpochFieldNumber;
const int HeartbeatReport::kTotalTimeMilliFieldNumber;
const int HeartbeatReport::kBusyTimeMilliFieldNumber;
const int HeartbeatReport::kNetInMbFieldNumber;
const int HeartbeatReport::kNetOutMbFieldNumber;
const int HeartbeatReport::kProcessCpuUsageFieldNumber;
const int HeartbeatReport::kHostCpuUsageFieldNumber;
const int HeartbeatReport::kProcessRssMbFieldNumber;
const int HeartbeatReport::kProcessVirtMbFieldNumber;
const int HeartbeatReport::kHostInUseGbFieldNumber;
const int HeartbeatReport::kHostInUsePercentageFieldNumber;
const int HeartbeatReport::kHostNetInBwFieldNumber;
const int HeartbeatReport::kHostNetOutBwFieldNumber;
#endif // !_MSC_VER
HeartbeatReport::HeartbeatReport()
: ::google::protobuf::Message() {
SharedCtor();
}
void HeartbeatReport::InitAsDefaultInstance() {
}
HeartbeatReport::HeartbeatReport(const HeartbeatReport& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
}
void HeartbeatReport::SharedCtor() {
_cached_size_ = 0;
task_id_ = 0;
hostname_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
seconds_since_epoch_ = 0u;
total_time_milli_ = 0u;
busy_time_milli_ = 0u;
net_in_mb_ = 0u;
net_out_mb_ = 0u;
process_cpu_usage_ = 0u;
host_cpu_usage_ = 0u;
process_rss_mb_ = 0u;
process_virt_mb_ = 0u;
host_in_use_gb_ = 0u;
host_in_use_percentage_ = 0u;
host_net_in_bw_ = 0u;
host_net_out_bw_ = 0u;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
HeartbeatReport::~HeartbeatReport() {
SharedDtor();
}
void HeartbeatReport::SharedDtor() {
if (hostname_ != &::google::protobuf::internal::kEmptyString) {
delete hostname_;
}
if (this != default_instance_) {
}
}
void HeartbeatReport::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* HeartbeatReport::descriptor() {
protobuf_AssignDescriptorsOnce();
return HeartbeatReport_descriptor_;
}
const HeartbeatReport& HeartbeatReport::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto();
return *default_instance_;
}
HeartbeatReport* HeartbeatReport::default_instance_ = NULL;
HeartbeatReport* HeartbeatReport::New() const {
return new HeartbeatReport;
}
void HeartbeatReport::Clear() {
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
task_id_ = 0;
if (has_hostname()) {
if (hostname_ != &::google::protobuf::internal::kEmptyString) {
hostname_->clear();
}
}
seconds_since_epoch_ = 0u;
total_time_milli_ = 0u;
busy_time_milli_ = 0u;
net_in_mb_ = 0u;
net_out_mb_ = 0u;
process_cpu_usage_ = 0u;
}
if (_has_bits_[8 / 32] & (0xffu << (8 % 32))) {
host_cpu_usage_ = 0u;
process_rss_mb_ = 0u;
process_virt_mb_ = 0u;
host_in_use_gb_ = 0u;
host_in_use_percentage_ = 0u;
host_net_in_bw_ = 0u;
host_net_out_bw_ = 0u;
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool HeartbeatReport::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 task_id = 1 [default = 0];
case 1: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &task_id_)));
set_has_task_id();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(16)) goto parse_seconds_since_epoch;
break;
}
// optional uint32 seconds_since_epoch = 2;
case 2: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_seconds_since_epoch:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &seconds_since_epoch_)));
set_has_seconds_since_epoch();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(24)) goto parse_busy_time_milli;
break;
}
// optional uint32 busy_time_milli = 3;
case 3: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_busy_time_milli:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &busy_time_milli_)));
set_has_busy_time_milli();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(32)) goto parse_net_in_mb;
break;
}
// optional uint32 net_in_mb = 4;
case 4: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_net_in_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &net_in_mb_)));
set_has_net_in_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(40)) goto parse_net_out_mb;
break;
}
// optional uint32 net_out_mb = 5;
case 5: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_net_out_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &net_out_mb_)));
set_has_net_out_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(48)) goto parse_process_cpu_usage;
break;
}
// optional uint32 process_cpu_usage = 6;
case 6: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_process_cpu_usage:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &process_cpu_usage_)));
set_has_process_cpu_usage();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(56)) goto parse_host_cpu_usage;
break;
}
// optional uint32 host_cpu_usage = 7;
case 7: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_cpu_usage:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_cpu_usage_)));
set_has_host_cpu_usage();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(64)) goto parse_process_rss_mb;
break;
}
// optional uint32 process_rss_mb = 8;
case 8: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_process_rss_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &process_rss_mb_)));
set_has_process_rss_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(72)) goto parse_process_virt_mb;
break;
}
// optional uint32 process_virt_mb = 9;
case 9: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_process_virt_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &process_virt_mb_)));
set_has_process_virt_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(80)) goto parse_host_in_use_gb;
break;
}
// optional uint32 host_in_use_gb = 10;
case 10: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_in_use_gb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_in_use_gb_)));
set_has_host_in_use_gb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(88)) goto parse_host_net_in_bw;
break;
}
// optional uint32 host_net_in_bw = 11;
case 11: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_net_in_bw:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_net_in_bw_)));
set_has_host_net_in_bw();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(96)) goto parse_host_net_out_bw;
break;
}
// optional uint32 host_net_out_bw = 12;
case 12: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_net_out_bw:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_net_out_bw_)));
set_has_host_net_out_bw();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(104)) goto parse_total_time_milli;
break;
}
// optional uint32 total_time_milli = 13;
case 13: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_total_time_milli:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &total_time_milli_)));
set_has_total_time_milli();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(114)) goto parse_hostname;
break;
}
// optional string hostname = 14;
case 14: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
parse_hostname:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_hostname()));
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->hostname().data(), this->hostname().length(),
::google::protobuf::internal::WireFormat::PARSE);
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(120)) goto parse_host_in_use_percentage;
break;
}
// optional uint32 host_in_use_percentage = 15;
case 15: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_in_use_percentage:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_in_use_percentage_)));
set_has_host_in_use_percentage();
} else {
goto handle_uninterpreted;
}
if (input->ExpectAtEnd()) return true;
break;
}
default: {
handle_uninterpreted:
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
return true;
#undef DO_
}
void HeartbeatReport::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// optional int32 task_id = 1 [default = 0];
if (has_task_id()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->task_id(), output);
}
// optional uint32 seconds_since_epoch = 2;
if (has_seconds_since_epoch()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->seconds_since_epoch(), output);
}
// optional uint32 busy_time_milli = 3;
if (has_busy_time_milli()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->busy_time_milli(), output);
}
// optional uint32 net_in_mb = 4;
if (has_net_in_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->net_in_mb(), output);
}
// optional uint32 net_out_mb = 5;
if (has_net_out_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->net_out_mb(), output);
}
// optional uint32 process_cpu_usage = 6;
if (has_process_cpu_usage()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->process_cpu_usage(), output);
}
// optional uint32 host_cpu_usage = 7;
if (has_host_cpu_usage()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(7, this->host_cpu_usage(), output);
}
// optional uint32 process_rss_mb = 8;
if (has_process_rss_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(8, this->process_rss_mb(), output);
}
// optional uint32 process_virt_mb = 9;
if (has_process_virt_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(9, this->process_virt_mb(), output);
}
// optional uint32 host_in_use_gb = 10;
if (has_host_in_use_gb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(10, this->host_in_use_gb(), output);
}
// optional uint32 host_net_in_bw = 11;
if (has_host_net_in_bw()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(11, this->host_net_in_bw(), output);
}
// optional uint32 host_net_out_bw = 12;
if (has_host_net_out_bw()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(12, this->host_net_out_bw(), output);
}
// optional uint32 total_time_milli = 13;
if (has_total_time_milli()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(13, this->total_time_milli(), output);
}
// optional string hostname = 14;
if (has_hostname()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->hostname().data(), this->hostname().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
::google::protobuf::internal::WireFormatLite::WriteString(
14, this->hostname(), output);
}
// optional uint32 host_in_use_percentage = 15;
if (has_host_in_use_percentage()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(15, this->host_in_use_percentage(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
}
::google::protobuf::uint8* HeartbeatReport::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// optional int32 task_id = 1 [default = 0];
if (has_task_id()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->task_id(), target);
}
// optional uint32 seconds_since_epoch = 2;
if (has_seconds_since_epoch()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->seconds_since_epoch(), target);
}
// optional uint32 busy_time_milli = 3;
if (has_busy_time_milli()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->busy_time_milli(), target);
}
// optional uint32 net_in_mb = 4;
if (has_net_in_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(4, this->net_in_mb(), target);
}
// optional uint32 net_out_mb = 5;
if (has_net_out_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(5, this->net_out_mb(), target);
}
// optional uint32 process_cpu_usage = 6;
if (has_process_cpu_usage()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(6, this->process_cpu_usage(), target);
}
// optional uint32 host_cpu_usage = 7;
if (has_host_cpu_usage()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(7, this->host_cpu_usage(), target);
}
// optional uint32 process_rss_mb = 8;
if (has_process_rss_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(8, this->process_rss_mb(), target);
}
// optional uint32 process_virt_mb = 9;
if (has_process_virt_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(9, this->process_virt_mb(), target);
}
// optional uint32 host_in_use_gb = 10;
if (has_host_in_use_gb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(10, this->host_in_use_gb(), target);
}
// optional uint32 host_net_in_bw = 11;
if (has_host_net_in_bw()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(11, this->host_net_in_bw(), target);
}
// optional uint32 host_net_out_bw = 12;
if (has_host_net_out_bw()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(12, this->host_net_out_bw(), target);
}
// optional uint32 total_time_milli = 13;
if (has_total_time_milli()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(13, this->total_time_milli(), target);
}
// optional string hostname = 14;
if (has_hostname()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->hostname().data(), this->hostname().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
14, this->hostname(), target);
}
// optional uint32 host_in_use_percentage = 15;
if (has_host_in_use_percentage()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(15, this->host_in_use_percentage(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
return target;
}
int HeartbeatReport::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional int32 task_id = 1 [default = 0];
if (has_task_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->task_id());
}
// optional string hostname = 14;
if (has_hostname()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->hostname());
}
// optional uint32 seconds_since_epoch = 2;
if (has_seconds_since_epoch()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->seconds_since_epoch());
}
// optional uint32 total_time_milli = 13;
if (has_total_time_milli()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->total_time_milli());
}
// optional uint32 busy_time_milli = 3;
if (has_busy_time_milli()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->busy_time_milli());
}
// optional uint32 net_in_mb = 4;
if (has_net_in_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->net_in_mb());
}
// optional uint32 net_out_mb = 5;
if (has_net_out_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->net_out_mb());
}
// optional uint32 process_cpu_usage = 6;
if (has_process_cpu_usage()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->process_cpu_usage());
}
}
if (_has_bits_[8 / 32] & (0xffu << (8 % 32))) {
// optional uint32 host_cpu_usage = 7;
if (has_host_cpu_usage()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_cpu_usage());
}
// optional uint32 process_rss_mb = 8;
if (has_process_rss_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->process_rss_mb());
}
// optional uint32 process_virt_mb = 9;
if (has_process_virt_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->process_virt_mb());
}
// optional uint32 host_in_use_gb = 10;
if (has_host_in_use_gb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_in_use_gb());
}
// optional uint32 host_in_use_percentage = 15;
if (has_host_in_use_percentage()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_in_use_percentage());
}
// optional uint32 host_net_in_bw = 11;
if (has_host_net_in_bw()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_net_in_bw());
}
// optional uint32 host_net_out_bw = 12;
if (has_host_net_out_bw()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_net_out_bw());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void HeartbeatReport::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const HeartbeatReport* source =
::google::protobuf::internal::dynamic_cast_if_available<const HeartbeatReport*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void HeartbeatReport::MergeFrom(const HeartbeatReport& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_task_id()) {
set_task_id(from.task_id());
}
if (from.has_hostname()) {
set_hostname(from.hostname());
}
if (from.has_seconds_since_epoch()) {
set_seconds_since_epoch(from.seconds_since_epoch());
}
if (from.has_total_time_milli()) {
set_total_time_milli(from.total_time_milli());
}
if (from.has_busy_time_milli()) {
set_busy_time_milli(from.busy_time_milli());
}
if (from.has_net_in_mb()) {
set_net_in_mb(from.net_in_mb());
}
if (from.has_net_out_mb()) {
set_net_out_mb(from.net_out_mb());
}
if (from.has_process_cpu_usage()) {
set_process_cpu_usage(from.process_cpu_usage());
}
}
if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) {
if (from.has_host_cpu_usage()) {
set_host_cpu_usage(from.host_cpu_usage());
}
if (from.has_process_rss_mb()) {
set_process_rss_mb(from.process_rss_mb());
}
if (from.has_process_virt_mb()) {
set_process_virt_mb(from.process_virt_mb());
}
if (from.has_host_in_use_gb()) {
set_host_in_use_gb(from.host_in_use_gb());
}
if (from.has_host_in_use_percentage()) {
set_host_in_use_percentage(from.host_in_use_percentage());
}
if (from.has_host_net_in_bw()) {
set_host_net_in_bw(from.host_net_in_bw());
}
if (from.has_host_net_out_bw()) {
set_host_net_out_bw(from.host_net_out_bw());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void HeartbeatReport::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void HeartbeatReport::CopyFrom(const HeartbeatReport& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool HeartbeatReport::IsInitialized() const {
return true;
}
void HeartbeatReport::Swap(HeartbeatReport* other) {
if (other != this) {
std::swap(task_id_, other->task_id_);
std::swap(hostname_, other->hostname_);
std::swap(seconds_since_epoch_, other->seconds_since_epoch_);
std::swap(total_time_milli_, other->total_time_milli_);
std::swap(busy_time_milli_, other->busy_time_milli_);
std::swap(net_in_mb_, other->net_in_mb_);
std::swap(net_out_mb_, other->net_out_mb_);
std::swap(process_cpu_usage_, other->process_cpu_usage_);
std::swap(host_cpu_usage_, other->host_cpu_usage_);
std::swap(process_rss_mb_, other->process_rss_mb_);
std::swap(process_virt_mb_, other->process_virt_mb_);
std::swap(host_in_use_gb_, other->host_in_use_gb_);
std::swap(host_in_use_percentage_, other->host_in_use_percentage_);
std::swap(host_net_in_bw_, other->host_net_in_bw_);
std::swap(host_net_out_bw_, other->host_net_out_bw_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata HeartbeatReport::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = HeartbeatReport_descriptor_;
metadata.reflection = HeartbeatReport_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace PS
// @@protoc_insertion_point(global_scope)
| 36.529476
| 122
| 0.677356
|
yipeiw
|
f8ee113d78812276f71e6cd6a599f54d34354199
| 729
|
hpp
|
C++
|
lib/DeviceConfigurator/DeviceConfigurator.hpp
|
OscarArgueyo/baliza-ic-dyasc
|
33c9f8e577a2315982be5b223bbc3e3c38e23809
|
[
"MIT"
] | null | null | null |
lib/DeviceConfigurator/DeviceConfigurator.hpp
|
OscarArgueyo/baliza-ic-dyasc
|
33c9f8e577a2315982be5b223bbc3e3c38e23809
|
[
"MIT"
] | null | null | null |
lib/DeviceConfigurator/DeviceConfigurator.hpp
|
OscarArgueyo/baliza-ic-dyasc
|
33c9f8e577a2315982be5b223bbc3e3c38e23809
|
[
"MIT"
] | null | null | null |
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include "SPIFFS.h"
#include <Arduino.h>
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#include <WiFi.h>
//needed for library
#include <DNSServer.h>
#include <WebServer.h>
#include <WiFiManager.h>
#ifndef DeviceConfigurator_HPP
#define DeviceConfigurator_HPP
class DeviceConfigurator
{
private:
public:
DeviceConfigurator();
void setAPCredentials(String ssid , String password);
void setCICredentials(String url , String token);
void setup();
void loop();
void cleanFileSystem();
bool isConnected();
String getURLEndpoint();
String getICToken();
};
#endif
| 23.516129
| 90
| 0.684499
|
OscarArgueyo
|
f8ee35e5a1fc89be617224c7ecc7149ca2a835c7
| 113
|
hpp
|
C++
|
examples/SimpleProject/src/simple_private.hpp
|
Neumann-A/CMakeJSON
|
395c4fa4588f80727ddaddd7b61276c6823be6b8
|
[
"BSL-1.0"
] | 10
|
2021-03-02T10:01:57.000Z
|
2021-11-01T11:27:36.000Z
|
examples/SimpleProject/src/simple_private.hpp
|
Neumann-A/CMakeJSON
|
395c4fa4588f80727ddaddd7b61276c6823be6b8
|
[
"BSL-1.0"
] | 1
|
2021-03-03T10:02:28.000Z
|
2021-03-03T14:17:16.000Z
|
examples/SimpleProject/src/simple_private.hpp
|
Neumann-A/CMakeJSON
|
395c4fa4588f80727ddaddd7b61276c6823be6b8
|
[
"BSL-1.0"
] | null | null | null |
#include <string_view>
static constexpr std::string_view hello_private = "Hello from the private libs parts!";
| 22.6
| 87
| 0.778761
|
Neumann-A
|
f8ef62c4ed42e265af5d6992862863bde4556aaa
| 2,274
|
hpp
|
C++
|
libs/render/include/hamon/render/gl/wgl/context.hpp
|
shibainuudon/HamonEngine
|
508a69b0cf589ccb2e5d403ce9e78ff2b85cc058
|
[
"MIT"
] | null | null | null |
libs/render/include/hamon/render/gl/wgl/context.hpp
|
shibainuudon/HamonEngine
|
508a69b0cf589ccb2e5d403ce9e78ff2b85cc058
|
[
"MIT"
] | 21
|
2022-03-02T13:11:59.000Z
|
2022-03-30T15:12:41.000Z
|
libs/render/include/hamon/render/gl/wgl/context.hpp
|
shibainuudon/HamonEngine
|
508a69b0cf589ccb2e5d403ce9e78ff2b85cc058
|
[
"MIT"
] | null | null | null |
/**
* @file context.hpp
*
* @brief Context
*/
#ifndef HAMON_RENDER_GL_WGL_CONTEXT_HPP
#define HAMON_RENDER_GL_WGL_CONTEXT_HPP
#include <hamon/window.hpp>
#include <hamon/render/gl/wgl/wglext.hpp>
namespace hamon
{
inline namespace render
{
namespace gl
{
class Context
{
public:
explicit Context(Window const& window)
: m_hwnd(window.GetNativeHandle())
, m_hdc(::GetDC(m_hwnd))
{
SetPixelFormat(m_hdc, 32);
// 仮のGLコンテキストの作成
auto hglrc_dummy = ::wglCreateContext(m_hdc);
::wglMakeCurrent(m_hdc, hglrc_dummy);
// 使用する OpenGL のバージョンとプロファイルの指定
static const int att[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0,
};
// 使用するGLコンテキストの作成
m_hglrc = gl::wglCreateContextAttribsARB(m_hdc, NULL, att);
::wglMakeCurrent(m_hdc, m_hglrc);
// 仮のGLコンテキストの削除
::wglDeleteContext(hglrc_dummy);
}
~Context()
{
::wglDeleteContext(m_hglrc);
::ReleaseDC(m_hwnd, m_hdc);
}
void SwapBuffers(void)
{
::SwapBuffers(m_hdc);
}
private:
static void SetPixelFormat(::HDC hdc, int color_depth)
{
::PIXELFORMATDESCRIPTOR const pfd =
{
sizeof(::PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //Flags
PFD_TYPE_RGBA, //The kind of framebuffer. RGBA or palette.
(::BYTE)color_depth, //Colordepth of the framebuffer.
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24, //Number of bits for the depthbuffer
8, //Number of bits for the stencilbuffer
0, //Number of Aux buffers in the framebuffer.
PFD_MAIN_PLANE,
0,
0, 0, 0
};
int const format = ::ChoosePixelFormat(hdc, &pfd);
if (format == 0)
{
return; // 該当するピクセルフォーマットが無い
}
// OpenGLが使うデバイスコンテキストに指定のピクセルフォーマットをセット
if (!::SetPixelFormat(hdc, format, &pfd))
{
return; // DCへフォーマットを設定するのに失敗
}
}
private:
::HWND m_hwnd = nullptr;
::HDC m_hdc = nullptr;
::HGLRC m_hglrc = nullptr;
};
} // namespace gl
} // inline namespace render
} // namespace hamon
#endif // HAMON_RENDER_GL_WGL_CONTEXT_HPP
| 19.947368
| 71
| 0.656992
|
shibainuudon
|
f8f4a9ff2bdd920ef8f40c94203b80965f96b06c
| 1,913
|
cpp
|
C++
|
phxrpc/network/test_echo_client.cpp
|
bombshen/phxrpc
|
465db10bd4c4bf6d95f6e8b431cc7abcda731ffb
|
[
"BSD-3-Clause"
] | 1,117
|
2017-08-02T06:03:59.000Z
|
2022-03-31T18:36:53.000Z
|
phxrpc/network/test_echo_client.cpp
|
kuiwang/wechat-phxrpc
|
a5f5af70f27406880013d49780fc4819ba3b75ef
|
[
"BSD-3-Clause"
] | 31
|
2017-08-16T08:43:35.000Z
|
2021-02-13T22:49:25.000Z
|
phxrpc/network/test_echo_client.cpp
|
kuiwang/wechat-phxrpc
|
a5f5af70f27406880013d49780fc4819ba3b75ef
|
[
"BSD-3-Clause"
] | 359
|
2017-08-04T07:32:41.000Z
|
2022-03-31T10:19:45.000Z
|
/*
Tencent is pleased to support the open source community by making
PhxRPC available.
Copyright (C) 2016 THL A29 Limited, a Tencent company.
All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
https://opensource.org/licenses/BSD-3-Clause
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
See the AUTHORS file for names of contributors.
*/
#include <assert.h>
#include <memory>
#include <errno.h>
#include <string.h>
#include "socket_stream_block.h"
void test(int times) {
int step = (times < 20 ? 20 : times) / 20;
for (int i = 0; i < 20; i++) {
phxrpc::BlockTcpStream stream;
if (!phxrpc::BlockTcpUtils::Open(&stream, "127.0.0.1", 16161, 100, NULL, 0)) {
printf("Connect fail\n");
return;
}
char line[128] = { 0 };
if (!stream.getlineWithTrimRight(line, sizeof(line)).good()) {
printf("Welcome message fail, errno %d, %s\n", errno, strerror(errno));
return;
}
for (int i = 0; i < step; i++) {
stream << i << std::endl;
if (stream.getline(line, sizeof(line)).good()) {
assert(i == atoi(line));
} else {
break;
}
}
stream << "quit" << std::endl;
printf("#");
fflush (stdout);
}
printf("\n");
}
int main(int argc, char * argv[]) {
if (argc < 2) {
printf("Usage: %s <run times>\n", argv[0]);
return 0;
}
test(atoi(argv[1]));
return 0;
}
| 25.171053
| 86
| 0.594354
|
bombshen
|
f8fb86fb22532022ed7a5dda52dbbeaf3a3fc9ac
| 12,315
|
cpp
|
C++
|
Source/Diagnostics/FieldIO.cpp
|
MaxThevenet/WarpX
|
d9606e22c2feb35bf2cfcd8843db7dfcbaf6c2f6
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
Source/Diagnostics/FieldIO.cpp
|
MaxThevenet/WarpX
|
d9606e22c2feb35bf2cfcd8843db7dfcbaf6c2f6
|
[
"BSD-3-Clause-LBNL"
] | 1
|
2019-09-09T22:37:32.000Z
|
2019-09-09T22:37:32.000Z
|
Source/Diagnostics/FieldIO.cpp
|
MaxThevenet/WarpX
|
d9606e22c2feb35bf2cfcd8843db7dfcbaf6c2f6
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#include <WarpX.H>
#include <FieldIO.H>
using namespace amrex;
void
PackPlotDataPtrs (Vector<const MultiFab*>& pmf,
const std::array<std::unique_ptr<MultiFab>,3>& data)
{
BL_ASSERT(pmf.size() == AMREX_SPACEDIM);
#if (AMREX_SPACEDIM == 3)
pmf[0] = data[0].get();
pmf[1] = data[1].get();
pmf[2] = data[2].get();
#elif (AMREX_SPACEDIM == 2)
pmf[0] = data[0].get();
pmf[1] = data[2].get();
#endif
}
/** \brief Takes an array of 3 MultiFab `vector_field`
* (representing the x, y, z components of a vector),
* averages it to the cell center, and stores the
* resulting MultiFab in mf_avg (in the components dcomp to dcomp+2)
*/
void
AverageAndPackVectorField( MultiFab& mf_avg,
const std::array< std::unique_ptr<MultiFab>, 3 >& vector_field,
const int dcomp, const int ngrow )
{
// The object below is temporary, and is needed because
// `average_edge_to_cellcenter` requires fields to be passed as Vector
Vector<const MultiFab*> srcmf(AMREX_SPACEDIM);
// Check the type of staggering of the 3-component `vector_field`
// and average accordingly:
// - Fully cell-centered field (no average needed; simply copy)
if ( vector_field[0]->is_cell_centered() ){
MultiFab::Copy( mf_avg, *vector_field[0], 0, dcomp , 1, ngrow);
MultiFab::Copy( mf_avg, *vector_field[1], 0, dcomp+1, 1, ngrow);
MultiFab::Copy( mf_avg, *vector_field[2], 0, dcomp+2, 1, ngrow);
// - Fully nodal
} else if ( vector_field[0]->is_nodal() ){
amrex::average_node_to_cellcenter( mf_avg, dcomp ,
*vector_field[0], 0, 1, ngrow);
amrex::average_node_to_cellcenter( mf_avg, dcomp+1,
*vector_field[1], 0, 1, ngrow);
amrex::average_node_to_cellcenter( mf_avg, dcomp+2,
*vector_field[2], 0, 1, ngrow);
// - Face centered, in the same way as B on a Yee grid
} else if ( vector_field[0]->is_nodal(0) ){
PackPlotDataPtrs(srcmf, vector_field);
amrex::average_face_to_cellcenter( mf_avg, dcomp, srcmf, ngrow);
#if (AMREX_SPACEDIM == 2)
MultiFab::Copy( mf_avg, mf_avg, dcomp+1, dcomp+2, 1, ngrow);
MultiFab::Copy( mf_avg, *vector_field[1], 0, dcomp+1, 1, ngrow);
#endif
// - Edge centered, in the same way as E on a Yee grid
} else if ( !vector_field[0]->is_nodal(0) ){
PackPlotDataPtrs(srcmf, vector_field);
amrex::average_edge_to_cellcenter( mf_avg, dcomp, srcmf, ngrow);
#if (AMREX_SPACEDIM == 2)
MultiFab::Copy( mf_avg, mf_avg, dcomp+1, dcomp+2, 1, ngrow);
amrex::average_node_to_cellcenter( mf_avg, dcomp+1,
*vector_field[1], 0, 1, ngrow);
#endif
} else {
amrex::Abort("Unknown staggering.");
}
}
/** \brief Take a MultiFab `scalar_field`
* averages it to the cell center, and stores the
* resulting MultiFab in mf_avg (in the components dcomp)
*/
void
AverageAndPackScalarField( MultiFab& mf_avg,
const MultiFab & scalar_field,
const int dcomp, const int ngrow )
{
// Check the type of staggering of the 3-component `vector_field`
// and average accordingly:
// - Fully cell-centered field (no average needed; simply copy)
if ( scalar_field.is_cell_centered() ){
MultiFab::Copy( mf_avg, scalar_field, 0, dcomp, 1, ngrow);
// - Fully nodal
} else if ( scalar_field.is_nodal() ){
amrex::average_node_to_cellcenter( mf_avg, dcomp, scalar_field, 0, 1, ngrow);
} else {
amrex::Abort("Unknown staggering.");
}
}
/** \brief Write the different fields that are meant for output,
* into the vector of MultiFab `mf_avg` (one MultiFab per level)
* after averaging them to the cell centers.
*/
void
WarpX::AverageAndPackFields ( Vector<std::string>& varnames,
amrex::Vector<MultiFab>& mf_avg, const int ngrow) const
{
// Count how many different fields should be written (ncomp)
const int ncomp = 3*3
+ static_cast<int>(plot_part_per_cell)
+ static_cast<int>(plot_part_per_grid)
+ static_cast<int>(plot_part_per_proc)
+ static_cast<int>(plot_proc_number)
+ static_cast<int>(plot_divb)
+ static_cast<int>(plot_dive)
+ static_cast<int>(plot_rho)
+ static_cast<int>(plot_F)
+ static_cast<int>(plot_finepatch)*6
+ static_cast<int>(plot_crsepatch)*6
+ static_cast<int>(costs[0] != nullptr);
// Loop over levels of refinement
for (int lev = 0; lev <= finest_level; ++lev)
{
// Allocate pointers to the `ncomp` fields that will be added
mf_avg.push_back( MultiFab(grids[lev], dmap[lev], ncomp, ngrow));
// Go through the different fields, pack them into mf_avg[lev],
// add the corresponding names to `varnames` and increment dcomp
int dcomp = 0;
AverageAndPackVectorField(mf_avg[lev], current_fp[lev], dcomp, ngrow);
if(lev==0) for(auto name:{"jx","jy","jz"}) varnames.push_back(name);
dcomp += 3;
AverageAndPackVectorField(mf_avg[lev], Efield_aux[lev], dcomp, ngrow);
if(lev==0) for(auto name:{"Ex","Ey","Ez"}) varnames.push_back(name);
dcomp += 3;
AverageAndPackVectorField(mf_avg[lev], Bfield_aux[lev], dcomp, ngrow);
if(lev==0) for(auto name:{"Bx","By","Bz"}) varnames.push_back(name);
dcomp += 3;
if (plot_part_per_cell)
{
MultiFab temp_dat(grids[lev],mf_avg[lev].DistributionMap(),1,0);
temp_dat.setVal(0);
// MultiFab containing number of particles in each cell
mypc->Increment(temp_dat, lev);
AverageAndPackScalarField( mf_avg[lev], temp_dat, dcomp, ngrow );
if(lev==0) varnames.push_back("part_per_cell");
dcomp += 1;
}
if (plot_part_per_grid)
{
const Vector<long>& npart_in_grid = mypc->NumberOfParticlesInGrid(lev);
// MultiFab containing number of particles per grid
// (stored as constant for all cells in each grid)
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(mf_avg[lev]); mfi.isValid(); ++mfi) {
(mf_avg[lev])[mfi].setVal(static_cast<Real>(npart_in_grid[mfi.index()]),
dcomp);
}
if(lev==0) varnames.push_back("part_per_grid");
dcomp += 1;
}
if (plot_part_per_proc)
{
const Vector<long>& npart_in_grid = mypc->NumberOfParticlesInGrid(lev);
// MultiFab containing number of particles per process
// (stored as constant for all cells in each grid)
long n_per_proc = 0;
#ifdef _OPENMP
#pragma omp parallel reduction(+:n_per_proc)
#endif
for (MFIter mfi(mf_avg[lev]); mfi.isValid(); ++mfi) {
n_per_proc += npart_in_grid[mfi.index()];
}
mf_avg[lev].setVal(static_cast<Real>(n_per_proc), dcomp,1);
if(lev==0) varnames.push_back("part_per_proc");
dcomp += 1;
}
if (plot_proc_number)
{
// MultiFab containing the Processor ID
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(mf_avg[lev]); mfi.isValid(); ++mfi) {
(mf_avg[lev])[mfi].setVal(static_cast<Real>(ParallelDescriptor::MyProc()),
dcomp);
}
if(lev==0) varnames.push_back("proc_number");
dcomp += 1;
}
if (plot_divb)
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_divb");
ComputeDivB(mf_avg[lev], dcomp,
{Bfield_aux[lev][0].get(),
Bfield_aux[lev][1].get(),
Bfield_aux[lev][2].get()},
WarpX::CellSize(lev)
);
if(lev == 0) varnames.push_back("divB");
dcomp += 1;
}
if (plot_dive)
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_dive");
const BoxArray& ba = amrex::convert(boxArray(lev),IntVect::TheUnitVector());
MultiFab dive(ba,DistributionMap(lev),1,0);
ComputeDivE( dive, 0,
{Efield_aux[lev][0].get(),
Efield_aux[lev][1].get(),
Efield_aux[lev][2].get()},
WarpX::CellSize(lev)
);
AverageAndPackScalarField( mf_avg[lev], dive, dcomp, ngrow );
if(lev == 0) varnames.push_back("divE");
dcomp += 1;
}
if (plot_rho)
{
AverageAndPackScalarField( mf_avg[lev], *rho_fp[lev], dcomp, ngrow );
if(lev == 0) varnames.push_back("rho");
dcomp += 1;
}
if (plot_F)
{
AverageAndPackScalarField( mf_avg[lev], *F_fp[lev], dcomp, ngrow);
if(lev == 0) varnames.push_back("F");
dcomp += 1;
}
if (plot_finepatch)
{
AverageAndPackVectorField( mf_avg[lev], Efield_fp[lev], dcomp, ngrow );
if(lev==0) for(auto name:{"Ex_fp","Ey_fp","Ez_fp"}) varnames.push_back(name);
dcomp += 3;
AverageAndPackVectorField( mf_avg[lev], Bfield_fp[lev], dcomp, ngrow );
if(lev==0) for(auto name:{"Bx_fp","By_fp","Bz_fp"}) varnames.push_back(name);
dcomp += 3;
}
if (plot_crsepatch)
{
if (lev == 0)
{
mf_avg[lev].setVal(0.0, dcomp, 3, ngrow);
}
else
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_crsepatch");
std::array<std::unique_ptr<MultiFab>, 3> E = getInterpolatedE(lev);
AverageAndPackVectorField( mf_avg[lev], E, dcomp, ngrow );
}
if(lev==0) for(auto name:{"Ex_cp","Ey_cp","Ez_cp"}) varnames.push_back(name);
dcomp += 3;
// now the magnetic field
if (lev == 0)
{
mf_avg[lev].setVal(0.0, dcomp, 3, ngrow);
}
else
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_crsepatch");
std::array<std::unique_ptr<MultiFab>, 3> B = getInterpolatedB(lev);
AverageAndPackVectorField( mf_avg[lev], B, dcomp, ngrow );
}
if(lev==0) for(auto name:{"Bx_cp","By_cp","Bz_cp"}) varnames.push_back(name);
dcomp += 3;
}
if (costs[0] != nullptr)
{
AverageAndPackScalarField( mf_avg[lev], *costs[lev], dcomp, ngrow );
if(lev==0) varnames.push_back("costs");
dcomp += 1;
}
BL_ASSERT(dcomp == ncomp);
} // end loop over levels of refinement
};
/** \brief Reduce the size of all the fields in `source_mf`
* by `coarse_ratio` and store the results in `coarse_mf`.
* Calculate the corresponding coarse Geometry from `source_geom`
* and store the results in `coarse_geom` */
void
coarsenCellCenteredFields(
Vector<MultiFab>& coarse_mf, Vector<Geometry>& coarse_geom,
const Vector<MultiFab>& source_mf, const Vector<Geometry>& source_geom,
int coarse_ratio, int finest_level )
{
// Check that the Vectors to be filled have an initial size of 0
AMREX_ALWAYS_ASSERT( coarse_mf.size()==0 );
AMREX_ALWAYS_ASSERT( coarse_geom.size()==0 );
// Fill the vectors with one element per level
int ncomp = source_mf[0].nComp();
for (int lev=0; lev<=finest_level; lev++) {
AMREX_ALWAYS_ASSERT( source_mf[lev].is_cell_centered() );
coarse_geom.push_back(amrex::coarsen( source_geom[lev], IntVect(coarse_ratio)));
BoxArray small_ba = amrex::coarsen(source_mf[lev].boxArray(), coarse_ratio);
coarse_mf.push_back( MultiFab(small_ba, source_mf[lev].DistributionMap(), ncomp, 0) );
average_down(source_mf[lev], coarse_mf[lev], 0, ncomp, IntVect(coarse_ratio));
}
};
| 37.318182
| 94
| 0.571092
|
MaxThevenet
|
f8fc1b11572be70b4491f7245d385e3855af1bae
| 2,892
|
hpp
|
C++
|
include/Error.hpp
|
auroralimin/montador-assembly-inventado
|
b7deeb4a00f27e941636921a84d5222dd7b008a5
|
[
"Apache-2.0"
] | null | null | null |
include/Error.hpp
|
auroralimin/montador-assembly-inventado
|
b7deeb4a00f27e941636921a84d5222dd7b008a5
|
[
"Apache-2.0"
] | null | null | null |
include/Error.hpp
|
auroralimin/montador-assembly-inventado
|
b7deeb4a00f27e941636921a84d5222dd7b008a5
|
[
"Apache-2.0"
] | null | null | null |
#ifndef MONT_ERROR_HPP
#define MONT_ERROR_HPP
#include <string>
namespace mont {
/**
* @enum mont::errorType
* @brief Enum para os tipos de erro a serem mostrados
*/
enum errorType {
lexical,
sintatic,
semantic,
warning
};
/**
* @brief Classe responsável pelo tratamento e saída de erros
* Essa classe possui funções para impressão de erros e guarda se
* algum erro já foi detectado no código-fonte
*/
class Error {
public:
/**
* @brief Construtor da classe
*
* @param src é um std::string contendo o nome do arquivo de entrada
*/
Error(std::string src);
/**
* @brief Imprime um erro inspirado na formatação do clang++
*
* @param nLine é um int contendo o número da linha com o erro
* @param begin é um std::string contendo onde na linha o erro\
* começou
* @param msg é um std::string contendo o corpo da mensagem de erro
* @para type é um mont::errorType contendo o tipo do erro
*/
void printError(int nLine, std::string begin,
std::string msg, errorType type);
/**
* @brief Gera uma mensagem de erro para quantidade de operandos\
* inválida
*
* @param name é um std::string contendo o nome da instrução
* @param n1 é um int contendo o número de operandos esperado
* @param n2 é um int contendo o número de operandos obtido
*
* @retval eMsg < em todos os casos retorna a mensagem gerada
*/
std::string instError(std::string name, int n1, int n2);
/**
* @brief Seta a flag de erros indicando que houve erro(s)
*/
void hasError();
/**
* @brief Pega a flag que indica se houverão erros na montagem
*
* @retval true < caso haja um ou mais erros
* @retval false > caso não haja nenhum erro
*/
bool getErrorFlag();
/**
* @brief Checa se uma substring esta contida em uma linha do código
*
* @param nLine é o int com o número da linha do código-fonte
* @param substr é um std::string com a substring procurada
*
* @retval true < caso tenha encontrado a substring
* @retval false < caso não tenha encontrado a substring
*/
bool hasSubstr(int nLine, std::string substr);
private:
std::string src; /**< nome do arquivo fonte */
bool errorFlag; /**< flag que indica se um erro ocorreu */
};
}
#endif
| 33.241379
| 80
| 0.525242
|
auroralimin
|
f8fd44ee4ab5a777006ee2d55f567d2cfe3f847c
| 549
|
hpp
|
C++
|
demos/glyph_paint/glyph_paint.hpp
|
thknepper/CPPurses
|
4f35ba5284bc5ac563214f73f494bd75fd5bf73b
|
[
"MIT"
] | 1
|
2020-02-22T21:18:11.000Z
|
2020-02-22T21:18:11.000Z
|
demos/glyph_paint/glyph_paint.hpp
|
thknepper/CPPurses
|
4f35ba5284bc5ac563214f73f494bd75fd5bf73b
|
[
"MIT"
] | null | null | null |
demos/glyph_paint/glyph_paint.hpp
|
thknepper/CPPurses
|
4f35ba5284bc5ac563214f73f494bd75fd5bf73b
|
[
"MIT"
] | null | null | null |
#ifndef DEMOS_GLYPH_PAINT_GLYPH_PAINT_HPP
#define DEMOS_GLYPH_PAINT_GLYPH_PAINT_HPP
#include "paint_area.hpp"
#include "side_pane.hpp"
#include <cppurses/widget/layouts/horizontal.hpp>
namespace demos {
namespace glyph_paint {
class Glyph_paint : public cppurses::layout::Horizontal<> {
public:
Glyph_paint();
private:
Paint_area& paint_area{this->make_child<Paint_area>()};
Side_pane& side_pane{this->make_child<Side_pane>()};
};
} // namespace glyph_paint
} // namespace demos
#endif // DEMOS_GLYPH_PAINT_GLYPH_PAINT_HPP
| 23.869565
| 59
| 0.763206
|
thknepper
|
5d06deaf663fa615ba011fd8b3608d128e365532
| 1,730
|
cpp
|
C++
|
source/generic/s3eYahooGamesAdTrack_register.cpp
|
salqadri/s3eYahooGamesAdTrack
|
5183757b8fa03a6a1d368dc22e5364445209a290
|
[
"MIT"
] | null | null | null |
source/generic/s3eYahooGamesAdTrack_register.cpp
|
salqadri/s3eYahooGamesAdTrack
|
5183757b8fa03a6a1d368dc22e5364445209a290
|
[
"MIT"
] | null | null | null |
source/generic/s3eYahooGamesAdTrack_register.cpp
|
salqadri/s3eYahooGamesAdTrack
|
5183757b8fa03a6a1d368dc22e5364445209a290
|
[
"MIT"
] | null | null | null |
/*
* WARNING: this is an autogenerated file and will be overwritten by
* the extension interface script.
*/
/*
* This file contains the automatically generated loader-side
* functions that form part of the extension.
*
* This file is awlays compiled into all loaders but compiles
* to nothing if this extension is not enabled in the loader
* at build time.
*/
#include "s3eYahooGamesAdTrack_autodefs.h"
#include "s3eEdk.h"
#include "s3eYahooGamesAdTrack.h"
//Declarations of Init and Term functions
extern s3eResult s3eYahooGamesAdTrackInit();
extern void s3eYahooGamesAdTrackTerminate();
void s3eYahooGamesAdTrackRegisterExt()
{
/* fill in the function pointer struct for this extension */
void* funcPtrs[4];
funcPtrs[0] = (void*)ygnAdTrackStart;
funcPtrs[1] = (void*)ygnAdTrackStop;
funcPtrs[2] = (void*)ygnAdTrackTrackExternalPayment;
funcPtrs[3] = (void*)ygnAdTrackTrackGetInstalledSource;
/*
* Flags that specify the extension's use of locking and stackswitching
*/
int flags[4] = { 0 };
/*
* Register the extension
*/
s3eEdkRegister("s3eYahooGamesAdTrack", funcPtrs, sizeof(funcPtrs), flags, s3eYahooGamesAdTrackInit, s3eYahooGamesAdTrackTerminate, 0);
}
#if !defined S3E_BUILD_S3ELOADER
#if defined S3E_EDK_USE_STATIC_INIT_ARRAY
int s3eYahooGamesAdTrackStaticInit()
{
void** p = g_StaticInitArray;
void* end = p + g_StaticArrayLen;
while (*p) p++;
if (p < end)
*p = (void*)&s3eYahooGamesAdTrackRegisterExt;
return 0;
}
int g_s3eYahooGamesAdTrackVal = s3eYahooGamesAdTrackStaticInit();
#elif defined S3E_EDK_USE_DLLS
S3E_EXTERN_C S3E_DLL_EXPORT void RegisterExt()
{
s3eYahooGamesAdTrackRegisterExt();
}
#endif
#endif
| 27.03125
| 134
| 0.736416
|
salqadri
|
5d0833a25625749a373427e259501c8b3680a949
| 1,562
|
hpp
|
C++
|
src/org/apache/poi/wp/usermodel/CharacterRun.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/wp/usermodel/CharacterRun.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/wp/usermodel/CharacterRun.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /POI/java/org/apache/poi/wp/usermodel/CharacterRun.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/wp/usermodel/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct poi::wp::usermodel::CharacterRun
: public virtual ::java::lang::Object
{
virtual bool isBold() = 0;
virtual void setBold(bool bold) = 0;
virtual bool isItalic() = 0;
virtual void setItalic(bool italic) = 0;
virtual bool isSmallCaps() = 0;
virtual void setSmallCaps(bool smallCaps) = 0;
virtual bool isCapitalized() = 0;
virtual void setCapitalized(bool caps) = 0;
virtual bool isStrikeThrough() = 0;
virtual void setStrikeThrough(bool strike) = 0;
virtual bool isDoubleStrikeThrough() = 0;
virtual void setDoubleStrikethrough(bool dstrike) = 0;
virtual bool isShadowed() = 0;
virtual void setShadow(bool shadow) = 0;
virtual bool isEmbossed() = 0;
virtual void setEmbossed(bool emboss) = 0;
virtual bool isImprinted() = 0;
virtual void setImprinted(bool imprint) = 0;
virtual int32_t getFontSize() = 0;
virtual void setFontSize(int32_t halfPoints) = 0;
virtual int32_t getCharacterSpacing() = 0;
virtual void setCharacterSpacing(int32_t twips) = 0;
virtual int32_t getKerning() = 0;
virtual void setKerning(int32_t kern) = 0;
virtual bool isHighlighted() = 0;
virtual ::java::lang::String* getFontName() = 0;
virtual ::java::lang::String* text() = 0;
// Generated
static ::java::lang::Class *class_();
};
| 35.5
| 73
| 0.68758
|
pebble2015
|
5d1418cc9a428bf63eb145d1ebb41f4dcee64a48
| 1,878
|
cpp
|
C++
|
Static_data_member/Static_data_member/main.cpp
|
b01703020/Financial_Computing
|
d98d4f6e784997129ece15cdaf33c506e0f35c9e
|
[
"MIT"
] | null | null | null |
Static_data_member/Static_data_member/main.cpp
|
b01703020/Financial_Computing
|
d98d4f6e784997129ece15cdaf33c506e0f35c9e
|
[
"MIT"
] | null | null | null |
Static_data_member/Static_data_member/main.cpp
|
b01703020/Financial_Computing
|
d98d4f6e784997129ece15cdaf33c506e0f35c9e
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// Static_data_member
//
// Created by wu yen sun on 2022/2/22.
//
#include <iostream>
using namespace std;
class Rectangle
{
private:
int length, width; // non static data members
static int count; // static data member
public:
// default constructor
Rectangle() :length(0), width(0)
{
count++;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
// constructor with parameters
Rectangle(int length_, int width_) :length(length_), width(width_)
{
count++;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
//copy constructor
Rectangle(const Rectangle& R) :length(R.length), width(R.width)
{
count++;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
// destructor
~Rectangle()
{
count--;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
static int GetCount() { return count; } // count is private
};
void RectangleQuestion(void)
{
Rectangle R1, R2(10, 2), R3 = R2;
// R1 is created default constructor,
// R2 by constructor with parameters,
// R3 by copy constructor
cout << "The number of rectangles = " << Rectangle::GetCount() << endl;
// 3
// destructor will be invoked for each object;
//last created object will be the 1st to destroy
}
int Rectangle::count = 0;
// static data member must be initialized outside constructor
int main(void)
{
RectangleQuestion();
// after the function is completed, all 3 objects are destroyed
return 0;
}
| 24.710526
| 98
| 0.528222
|
b01703020
|
5d174d802d19486deba694a22ce7ff67af08559e
| 724
|
cpp
|
C++
|
src/kernel/kernel_types.cpp
|
cbeck88/wes-kernel
|
38296e9fcbda632b3cb332a807a590683dd26a1f
|
[
"MIT"
] | null | null | null |
src/kernel/kernel_types.cpp
|
cbeck88/wes-kernel
|
38296e9fcbda632b3cb332a807a590683dd26a1f
|
[
"MIT"
] | null | null | null |
src/kernel/kernel_types.cpp
|
cbeck88/wes-kernel
|
38296e9fcbda632b3cb332a807a590683dd26a1f
|
[
"MIT"
] | null | null | null |
#include "kernel_types.hpp"
namespace wesnoth {
static map_location _helper(int x, int y) {
map_location ret;
ret.x = x;
ret.y = y;
return ret;
}
// TODO: Fix this to correct for C++ vs WML 0 - 1 difference
std::set<map_location> hex::neighbors(map_location a) {
std::set<map_location> res;
bool b = (a.x & 1) == 0;
res.emplace(_helper(a.x, a.y-1));
res.emplace(_helper(a.x+1, a.y - (b ? 1 : 0)));
res.emplace(_helper(a.x+1, a.y + (b ? 0 : 1)));
res.emplace(_helper(a.x, a.y+1));
res.emplace(_helper(a.x-1, a.y + (b ? 0 : 1)));
res.emplace(_helper(a.x-1, a.y + (b ? 1 : 0)));
return res;
}
bool hex::adjacent(map_location a, map_location b) {
return geometry::adjacent(a, b);
}
} // end namespace wesnoth
| 24.133333
| 60
| 0.629834
|
cbeck88
|
5d1ca9dbd6f974892faa0bc4127f56a90289b8dd
| 15,271
|
cpp
|
C++
|
src/tests/unittests/CommandAllocatorTests.cpp
|
faro-oss/Dawn
|
0ac7aa3386b597742a45368a28a2e045c122cb8c
|
[
"Apache-2.0"
] | 1
|
2022-02-05T01:08:06.000Z
|
2022-02-05T01:08:06.000Z
|
src/tests/unittests/CommandAllocatorTests.cpp
|
sunnyps/dawn
|
afe91384086551ea3156fc67c525fdf864aa8437
|
[
"Apache-2.0"
] | 1
|
2021-12-18T01:33:44.000Z
|
2021-12-18T01:33:44.000Z
|
src/tests/unittests/CommandAllocatorTests.cpp
|
sunnyps/dawn
|
afe91384086551ea3156fc67c525fdf864aa8437
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2017 The Dawn 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 <gtest/gtest.h>
#include "dawn_native/CommandAllocator.h"
#include <limits>
using namespace dawn_native;
// Definition of the command types used in the tests
enum class CommandType {
Draw,
Pipeline,
PushConstants,
Big,
Small,
};
struct CommandDraw {
uint32_t first;
uint32_t count;
};
struct CommandPipeline {
uint64_t pipeline;
uint32_t attachmentPoint;
};
struct CommandPushConstants {
uint8_t size;
uint8_t offset;
};
constexpr int kBigBufferSize = 65536;
struct CommandBig {
uint32_t buffer[kBigBufferSize];
};
struct CommandSmall {
uint16_t data;
};
// Test allocating nothing works
TEST(CommandAllocator, DoNothingAllocator) {
CommandAllocator allocator;
}
// Test iterating over nothing works
TEST(CommandAllocator, DoNothingAllocatorWithIterator) {
CommandAllocator allocator;
CommandIterator iterator(std::move(allocator));
iterator.MakeEmptyAsDataWasDestroyed();
}
// Test basic usage of allocator + iterator
TEST(CommandAllocator, Basic) {
CommandAllocator allocator;
uint64_t myPipeline = 0xDEADBEEFBEEFDEAD;
uint32_t myAttachmentPoint = 2;
uint32_t myFirst = 42;
uint32_t myCount = 16;
{
CommandPipeline* pipeline = allocator.Allocate<CommandPipeline>(CommandType::Pipeline);
pipeline->pipeline = myPipeline;
pipeline->attachmentPoint = myAttachmentPoint;
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = myFirst;
draw->count = myCount;
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
CommandPipeline* pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, myPipeline);
ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint);
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test basic usage of allocator + iterator with data
TEST(CommandAllocator, BasicWithData) {
CommandAllocator allocator;
uint8_t mySize = 8;
uint8_t myOffset = 3;
uint32_t myValues[5] = {6, 42, 0xFFFFFFFF, 0, 54};
{
CommandPushConstants* pushConstants =
allocator.Allocate<CommandPushConstants>(CommandType::PushConstants);
pushConstants->size = mySize;
pushConstants->offset = myOffset;
uint32_t* values = allocator.AllocateData<uint32_t>(5);
for (size_t i = 0; i < 5; i++) {
values[i] = myValues[i];
}
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::PushConstants);
CommandPushConstants* pushConstants = iterator.NextCommand<CommandPushConstants>();
ASSERT_EQ(pushConstants->size, mySize);
ASSERT_EQ(pushConstants->offset, myOffset);
uint32_t* values = iterator.NextData<uint32_t>(5);
for (size_t i = 0; i < 5; i++) {
ASSERT_EQ(values[i], myValues[i]);
}
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test basic iterating several times
TEST(CommandAllocator, MultipleIterations) {
CommandAllocator allocator;
uint32_t myFirst = 42;
uint32_t myCount = 16;
{
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = myFirst;
draw->count = myCount;
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
// First iteration
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
// Second iteration
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test large commands work
TEST(CommandAllocator, LargeCommands) {
CommandAllocator allocator;
const int kCommandCount = 5;
uint32_t count = 0;
for (int i = 0; i < kCommandCount; i++) {
CommandBig* big = allocator.Allocate<CommandBig>(CommandType::Big);
for (int j = 0; j < kBigBufferSize; j++) {
big->buffer[j] = count++;
}
}
CommandIterator iterator(std::move(allocator));
CommandType type;
count = 0;
int numCommands = 0;
while (iterator.NextCommandId(&type)) {
ASSERT_EQ(type, CommandType::Big);
CommandBig* big = iterator.NextCommand<CommandBig>();
for (int i = 0; i < kBigBufferSize; i++) {
ASSERT_EQ(big->buffer[i], count);
count++;
}
numCommands++;
}
ASSERT_EQ(numCommands, kCommandCount);
iterator.MakeEmptyAsDataWasDestroyed();
}
// Test many small commands work
TEST(CommandAllocator, ManySmallCommands) {
CommandAllocator allocator;
// Stay under max representable uint16_t
const int kCommandCount = 50000;
uint16_t count = 0;
for (int i = 0; i < kCommandCount; i++) {
CommandSmall* small = allocator.Allocate<CommandSmall>(CommandType::Small);
small->data = count++;
}
CommandIterator iterator(std::move(allocator));
CommandType type;
count = 0;
int numCommands = 0;
while (iterator.NextCommandId(&type)) {
ASSERT_EQ(type, CommandType::Small);
CommandSmall* small = iterator.NextCommand<CommandSmall>();
ASSERT_EQ(small->data, count);
count++;
numCommands++;
}
ASSERT_EQ(numCommands, kCommandCount);
iterator.MakeEmptyAsDataWasDestroyed();
}
/* ________
* / \
* | POUIC! |
* \_ ______/
* v
* ()_()
* (O.o)
* (> <)o
*/
// Test usage of iterator.Reset
TEST(CommandAllocator, IteratorReset) {
CommandAllocator allocator;
uint64_t myPipeline = 0xDEADBEEFBEEFDEAD;
uint32_t myAttachmentPoint = 2;
uint32_t myFirst = 42;
uint32_t myCount = 16;
{
CommandPipeline* pipeline = allocator.Allocate<CommandPipeline>(CommandType::Pipeline);
pipeline->pipeline = myPipeline;
pipeline->attachmentPoint = myAttachmentPoint;
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = myFirst;
draw->count = myCount;
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
CommandPipeline* pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, myPipeline);
ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint);
iterator.Reset();
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, myPipeline);
ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint);
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test iterating empty iterators
TEST(CommandAllocator, EmptyIterator) {
{
CommandAllocator allocator;
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
{
CommandAllocator allocator;
CommandIterator iterator1(std::move(allocator));
CommandIterator iterator2(std::move(iterator1));
CommandType type;
bool hasNext = iterator2.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator1.MakeEmptyAsDataWasDestroyed();
iterator2.MakeEmptyAsDataWasDestroyed();
}
{
CommandIterator iterator1;
CommandIterator iterator2(std::move(iterator1));
CommandType type;
bool hasNext = iterator2.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator1.MakeEmptyAsDataWasDestroyed();
iterator2.MakeEmptyAsDataWasDestroyed();
}
}
template <size_t A>
struct alignas(A) AlignedStruct {
char dummy;
};
// Test for overflows in Allocate's computations, size 1 variant
TEST(CommandAllocator, AllocationOverflow_1) {
CommandAllocator allocator;
AlignedStruct<1>* data =
allocator.AllocateData<AlignedStruct<1>>(std::numeric_limits<size_t>::max() / 1);
ASSERT_EQ(data, nullptr);
}
// Test for overflows in Allocate's computations, size 2 variant
TEST(CommandAllocator, AllocationOverflow_2) {
CommandAllocator allocator;
AlignedStruct<2>* data =
allocator.AllocateData<AlignedStruct<2>>(std::numeric_limits<size_t>::max() / 2);
ASSERT_EQ(data, nullptr);
}
// Test for overflows in Allocate's computations, size 4 variant
TEST(CommandAllocator, AllocationOverflow_4) {
CommandAllocator allocator;
AlignedStruct<4>* data =
allocator.AllocateData<AlignedStruct<4>>(std::numeric_limits<size_t>::max() / 4);
ASSERT_EQ(data, nullptr);
}
// Test for overflows in Allocate's computations, size 8 variant
TEST(CommandAllocator, AllocationOverflow_8) {
CommandAllocator allocator;
AlignedStruct<8>* data =
allocator.AllocateData<AlignedStruct<8>>(std::numeric_limits<size_t>::max() / 8);
ASSERT_EQ(data, nullptr);
}
template <int DefaultValue>
struct IntWithDefault {
IntWithDefault() : value(DefaultValue) {
}
int value;
};
// Test that the allcator correctly defaults initalizes data for Allocate
TEST(CommandAllocator, AllocateDefaultInitializes) {
CommandAllocator allocator;
IntWithDefault<42>* int42 = allocator.Allocate<IntWithDefault<42>>(CommandType::Draw);
ASSERT_EQ(int42->value, 42);
IntWithDefault<43>* int43 = allocator.Allocate<IntWithDefault<43>>(CommandType::Draw);
ASSERT_EQ(int43->value, 43);
IntWithDefault<44>* int44 = allocator.Allocate<IntWithDefault<44>>(CommandType::Draw);
ASSERT_EQ(int44->value, 44);
CommandIterator iterator(std::move(allocator));
iterator.MakeEmptyAsDataWasDestroyed();
}
// Test that the allocator correctly default-initalizes data for AllocateData
TEST(CommandAllocator, AllocateDataDefaultInitializes) {
CommandAllocator allocator;
IntWithDefault<33>* int33 = allocator.AllocateData<IntWithDefault<33>>(1);
ASSERT_EQ(int33[0].value, 33);
IntWithDefault<34>* int34 = allocator.AllocateData<IntWithDefault<34>>(2);
ASSERT_EQ(int34[0].value, 34);
ASSERT_EQ(int34[0].value, 34);
IntWithDefault<35>* int35 = allocator.AllocateData<IntWithDefault<35>>(3);
ASSERT_EQ(int35[0].value, 35);
ASSERT_EQ(int35[1].value, 35);
ASSERT_EQ(int35[2].value, 35);
CommandIterator iterator(std::move(allocator));
iterator.MakeEmptyAsDataWasDestroyed();
}
// Tests flattening of multiple CommandAllocators into a single CommandIterator using
// AcquireCommandBlocks.
TEST(CommandAllocator, AcquireCommandBlocks) {
constexpr size_t kNumAllocators = 2;
constexpr size_t kNumCommandsPerAllocator = 2;
const uint64_t pipelines[kNumAllocators][kNumCommandsPerAllocator] = {
{0xDEADBEEFBEEFDEAD, 0xC0FFEEF00DC0FFEE},
{0x1337C0DE1337C0DE, 0xCAFEFACEFACECAFE},
};
const uint32_t attachmentPoints[kNumAllocators][kNumCommandsPerAllocator] = {{1, 2}, {3, 4}};
const uint32_t firsts[kNumAllocators][kNumCommandsPerAllocator] = {{42, 43}, {5, 6}};
const uint32_t counts[kNumAllocators][kNumCommandsPerAllocator] = {{16, 32}, {4, 8}};
std::vector<CommandAllocator> allocators(kNumAllocators);
for (size_t j = 0; j < kNumAllocators; ++j) {
CommandAllocator& allocator = allocators[j];
for (size_t i = 0; i < kNumCommandsPerAllocator; ++i) {
CommandPipeline* pipeline = allocator.Allocate<CommandPipeline>(CommandType::Pipeline);
pipeline->pipeline = pipelines[j][i];
pipeline->attachmentPoint = attachmentPoints[j][i];
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = firsts[j][i];
draw->count = counts[j][i];
}
}
CommandIterator iterator;
iterator.AcquireCommandBlocks(std::move(allocators));
for (size_t j = 0; j < kNumAllocators; ++j) {
for (size_t i = 0; i < kNumCommandsPerAllocator; ++i) {
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
CommandPipeline* pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, pipelines[j][i]);
ASSERT_EQ(pipeline->attachmentPoint, attachmentPoints[j][i]);
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, firsts[j][i]);
ASSERT_EQ(draw->count, counts[j][i]);
}
}
CommandType type;
ASSERT_FALSE(iterator.NextCommandId(&type));
iterator.MakeEmptyAsDataWasDestroyed();
}
| 30.299603
| 99
| 0.669177
|
faro-oss
|
5d1d93acaa5a650f59709505279c3fd21c6b802a
| 2,259
|
cpp
|
C++
|
base/SplashScreen.cpp
|
fmuecke/ipponboard_test
|
2ba8f324af91bfcdd26e37940157a1796f3b1f64
|
[
"BSD-2-Clause"
] | 3
|
2020-12-29T19:33:56.000Z
|
2021-11-09T20:29:30.000Z
|
base/SplashScreen.cpp
|
fmuecke/ipponboard_test
|
2ba8f324af91bfcdd26e37940157a1796f3b1f64
|
[
"BSD-2-Clause"
] | 3
|
2020-12-30T10:34:26.000Z
|
2021-01-05T08:55:12.000Z
|
base/SplashScreen.cpp
|
fmuecke/ipponboard_test
|
2ba8f324af91bfcdd26e37940157a1796f3b1f64
|
[
"BSD-2-Clause"
] | null | null | null |
// Copyright 2018 Florian Muecke. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.txt file.
#include "DonationManager.h"
#include "splashscreen.h"
#include "ui_splashscreen.h"
#include "versioninfo.h"
#include <algorithm>
using namespace std;
SplashScreen::SplashScreen(Data const& data, QWidget* parent)
: QDialog(parent)
, ui(new Ui::SplashScreen)
{
ui->setupUi(this);
// const int days_left = data.date.daysTo(QDate::currentDate());
// ui->label_valid->setText(
// "- " + QString::number( days_left ) +
// " " + tr("days left") + " -");
ui->textEdit_eula->setHtml(data.text);
ui->label_info->setText(data.info);
//ui->labelCopyright->setText(QString("© %1 Florian Mücke").arg(VersionInfo::CopyrightYear));
ui->commandLinkButton_donate->setText(DonationManager::GetDonationLabel());
/*std::vector<QCommandLinkButton*> buttons =
{
ui->commandLinkButton_donate,
ui->commandLinkButton_startSingleVersion,
ui->commandLinkButton_startTeamVersion
};
buttons.erase(
remove_if(
begin(buttons),
end(buttons),
[](QCommandLinkButton* b) { return !b->isEnabled(); }),
end(buttons));
auto r = qrand() % buttons.size();
buttons[r]->setFocus();
buttons[r]->setDefault(true);
//ui->commandLinkButton_donate->setFocus();
*/
setWindowFlags(Qt::Window);
}
SplashScreen::~SplashScreen()
{
delete ui;
}
void SplashScreen::SetImageStyleSheet(QString const& /*text*/)
{
//"image: url(:/res/images/logo.png);"
//ui->widget_image->setStyleSheet(text);
}
void SplashScreen::changeEvent(QEvent* e)
{
QWidget::changeEvent(e);
switch (e->type())
{
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void SplashScreen::on_commandLinkButton_startSingleVersion_pressed()
{
accept();
}
void SplashScreen::on_commandLinkButton_startTeamVersion_pressed()
{
done(QDialog::Accepted + 1);
}
void SplashScreen::on_commandLinkButton_donate_pressed()
{
DonationManager::OpenUrl();
}
//void SplashScreen::on_commandLinkButton_cancel_pressed()
//{
// reject();
//}
| 23.05102
| 95
| 0.665781
|
fmuecke
|
5d209da5ebc8fd0b040e73902be37e64d13111f5
| 6,756
|
cc
|
C++
|
src/latbin/lattice-align-words-lexicon.cc
|
brucerennie/kaldi
|
d366a93aad98127683b010fd01e145093c1e9e08
|
[
"Apache-2.0"
] | 36
|
2019-11-12T22:41:43.000Z
|
2022-02-01T15:24:02.000Z
|
src/latbin/lattice-align-words-lexicon.cc
|
brucerennie/kaldi
|
d366a93aad98127683b010fd01e145093c1e9e08
|
[
"Apache-2.0"
] | 8
|
2017-09-06T00:12:00.000Z
|
2019-03-22T08:03:19.000Z
|
src/latbin/lattice-align-words-lexicon.cc
|
brucerennie/kaldi
|
d366a93aad98127683b010fd01e145093c1e9e08
|
[
"Apache-2.0"
] | 29
|
2020-01-03T22:28:27.000Z
|
2022-03-30T23:00:27.000Z
|
// latbin/lattice-align-words-lexicon.cc
// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "lat/kaldi-lattice.h"
#include "lat/word-align-lattice-lexicon.h"
#include "lat/lattice-functions.h"
#include "lat/lattice-functions-transition-model.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using fst::StdArc;
using kaldi::int32;
const char *usage =
"Convert lattices so that the arcs in the CompactLattice format correspond with\n"
"words (i.e. aligned with word boundaries). This is the newest form, that\n"
"reads in a lexicon in integer format, where each line is (integer id of)\n"
" word-in word-out phone1 phone2 ... phoneN\n"
"(note: word-in is word before alignment, word-out is after, e.g. for replacing\n"
"<eps> with SIL or vice versa)\n"
"This may be more efficient if you first apply 'lattice-push'.\n"
"Usage: lattice-align-words-lexicon [options] <lexicon-file> <model> <lattice-rspecifier> <lattice-wspecifier>\n"
" e.g.: lattice-align-words-lexicon --partial-word-label=4324 --max-expand 10.0 --test true \\\n"
" data/lang/phones/align_lexicon.int final.mdl ark:1.lats ark:aligned.lats\n"
"See also: lattice-align-words, which is only applicable if your phones have word-position\n"
"markers, i.e. each phone comes in 5 versions like AA_B, AA_I, AA_W, AA_S, AA.\n";
ParseOptions po(usage);
bool output_if_error = true;
bool output_if_empty = false;
bool test = false;
bool allow_duplicate_paths = false;
po.Register("output-error-lats", &output_if_error, "Output lattices that aligned "
"with errors (e.g. due to force-out");
po.Register("output-if-empty", &output_if_empty, "If true: if algorithm gives "
"error and produces empty output, pass the input through.");
po.Register("test", &test, "If true, testing code will be activated "
"(the purpose of this is to validate the algorithm).");
po.Register("allow-duplicate-paths", &allow_duplicate_paths, "Only "
"has an effect if --test=true. If true, does not die "
"(only prints warnings) if duplicate paths are found. "
"This should only happen with very pathological lexicons, "
"e.g. as encountered in testing code.");
WordAlignLatticeLexiconOpts opts;
opts.Register(&po);
po.Read(argc, argv);
if (po.NumArgs() != 4) {
po.PrintUsage();
exit(1);
}
std::string
align_lexicon_rxfilename = po.GetArg(1),
model_rxfilename = po.GetArg(2),
lats_rspecifier = po.GetArg(3),
lats_wspecifier = po.GetArg(4);
std::vector<std::vector<int32> > lexicon;
{
bool binary_in;
Input ki(align_lexicon_rxfilename, &binary_in);
KALDI_ASSERT(!binary_in && "Not expecting binary file for lexicon");
if (!ReadLexiconForWordAlign(ki.Stream(), &lexicon)) {
KALDI_ERR << "Error reading alignment lexicon from "
<< align_lexicon_rxfilename;
}
}
TransitionModel tmodel;
ReadKaldiObject(model_rxfilename, &tmodel);
SequentialCompactLatticeReader clat_reader(lats_rspecifier);
CompactLatticeWriter clat_writer(lats_wspecifier);
WordAlignLatticeLexiconInfo lexicon_info(lexicon);
{ std::vector<std::vector<int32> > temp; lexicon.swap(temp); }
// No longer needed.
int32 num_done = 0, num_err = 0;
for (; !clat_reader.Done(); clat_reader.Next()) {
std::string key = clat_reader.Key();
const CompactLattice &clat = clat_reader.Value();
CompactLattice aligned_clat;
bool ok = WordAlignLatticeLexicon(clat, tmodel, lexicon_info, opts,
&aligned_clat);
if (ok && test) { // We only test if it succeeded.
if (!TestWordAlignedLattice(lexicon_info, tmodel, clat, aligned_clat,
allow_duplicate_paths)) {
KALDI_WARN << "Lattice failed test (activated because --test=true). "
<< "Probable code error, please contact Kaldi maintainers.";
ok = false;
}
}
if (!ok) {
num_err++;
if (output_if_empty && aligned_clat.NumStates() == 0 &&
clat.NumStates() != 0) {
KALDI_WARN << "Algorithm produced no output (due to --max-expand?), "
<< "so passing input through as output, for key " << key;
TopSortCompactLatticeIfNeeded(&aligned_clat);
clat_writer.Write(key, clat);
continue;
}
if (!output_if_error)
KALDI_WARN << "Lattice for " << key << " did not align correctly";
else {
if (aligned_clat.Start() != fst::kNoStateId) {
KALDI_WARN << "Outputting partial lattice for " << key;
TopSortCompactLatticeIfNeeded(&aligned_clat);
clat_writer.Write(key, aligned_clat);
} else {
KALDI_WARN << "Empty aligned lattice for " << key
<< ", producing no output.";
}
}
} else {
if (aligned_clat.Start() == fst::kNoStateId) {
num_err++;
KALDI_WARN << "Lattice was empty for key " << key;
} else {
num_done++;
KALDI_VLOG(2) << "Aligned lattice for " << key;
TopSortCompactLatticeIfNeeded(&aligned_clat);
clat_writer.Write(key, aligned_clat);
}
}
}
KALDI_LOG << "Successfully aligned " << num_done << " lattices; "
<< num_err << " had errors.";
return (num_done > num_err ? 0 : 1); // We changed the error condition slightly here,
// if there are errors in the word-boundary phones we can get situations
// where most lattices give an error.
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 40.45509
| 121
| 0.623594
|
brucerennie
|
5d20b7caf134216cd8aec42ce48677e2ffb28593
| 255
|
cpp
|
C++
|
CCured/program-dependence-graph/SVF/Test-Suite/cpp_types/broken.cpp
|
Lightninghkm/DataGuard
|
4ac1370f7607cec5fc81c3b57f5a62fb1d40f463
|
[
"Apache-2.0"
] | 9
|
2022-02-25T01:48:43.000Z
|
2022-03-20T04:48:44.000Z
|
CCured/program-dependence-graph/SVF/Test-Suite/cpp_types/broken.cpp
|
Lightninghkm/DataGuard
|
4ac1370f7607cec5fc81c3b57f5a62fb1d40f463
|
[
"Apache-2.0"
] | 1
|
2022-03-19T08:48:07.000Z
|
2022-03-21T00:51:51.000Z
|
CCured/program-dependence-graph/SVF/Test-Suite/cpp_types/broken.cpp
|
Lightninghkm/DataGuard
|
4ac1370f7607cec5fc81c3b57f5a62fb1d40f463
|
[
"Apache-2.0"
] | null | null | null |
void checkType(void* clz, char* ty){}
class A {
public:
A(){}
};
class B : public A {
public:
B(){}
};
class C : public B {
public:
C(){}
};
int main(void) {
A *a = new A();
checkType(a,"A");
}
| 11.086957
| 37
| 0.419608
|
Lightninghkm
|
5d2742c249ffa5a13b239bde8ab0b7ed8cb3b1d5
| 115
|
cc
|
C++
|
abc.cc
|
lh2debug/quartzmemkv2
|
664a85f4ee1869f4ff7fafd88f9cbe36ace30fc5
|
[
"BSD-3-Clause"
] | null | null | null |
abc.cc
|
lh2debug/quartzmemkv2
|
664a85f4ee1869f4ff7fafd88f9cbe36ace30fc5
|
[
"BSD-3-Clause"
] | null | null | null |
abc.cc
|
lh2debug/quartzmemkv2
|
664a85f4ee1869f4ff7fafd88f9cbe36ace30fc5
|
[
"BSD-3-Clause"
] | null | null | null |
#include "pmalloc.h"
int main(){
int *p = (int*)pmalloc(sizeof(int));
pfree((void*)p, sizeof(int));
return 0;
}
| 16.428571
| 37
| 0.617391
|
lh2debug
|
5d278783c192dcee83bf53f80743a7fb618784fa
| 3,031
|
cpp
|
C++
|
tools/fact-generator/src/PyFactGen.cpp
|
TheoKant/cclyzer-souffle
|
dfcd01daa592a2356e36aaeaa9c933305c253cba
|
[
"MIT"
] | 63
|
2016-02-06T21:06:40.000Z
|
2021-11-16T19:58:27.000Z
|
tools/fact-generator/src/PyFactGen.cpp
|
TheoKant/cclyzer-souffle
|
dfcd01daa592a2356e36aaeaa9c933305c253cba
|
[
"MIT"
] | 11
|
2019-05-23T20:55:12.000Z
|
2021-12-08T22:18:01.000Z
|
tools/fact-generator/src/PyFactGen.cpp
|
TheoKant/cclyzer-souffle
|
dfcd01daa592a2356e36aaeaa9c933305c253cba
|
[
"MIT"
] | 14
|
2016-02-21T17:12:36.000Z
|
2021-09-26T02:48:41.000Z
|
/**
* This module is intended to provide a python interface to
* fact-generator, by leveraging the Boost.Python library.
**/
#include <boost/filesystem.hpp>
#include <boost/python.hpp>
#include "ParseException.hpp"
namespace fs = boost::filesystem;
namespace py = boost::python;
void
pyfactgen(py::list inputFiles, std::string outputDir, std::string delim = "\t")
{
int length = py::extract<int>(inputFiles.attr("__len__")());
std::vector<fs::path> files(length);
// Create list of input files
for (int i = 0; i < len(inputFiles); ++i) {
files[i] = py::extract<char const *>(inputFiles[i]);
// Check file existence
if (!fs::exists(files[i])) {
std::stringstream error_stream;
error_stream << "No such file or directory: "
<< files[i];
std::string err_msg = error_stream.str();
PyErr_SetString(PyExc_IOError, err_msg.c_str());
boost::python::throw_error_already_set();
return;
}
}
// Create non-existing directory
if (!fs::exists(outputDir))
fs::create_directory(outputDir);
if (!fs::is_directory(outputDir)) {
PyErr_SetString(PyExc_ValueError,
"Invalid output directory path");
boost::python::throw_error_already_set();
return;
}
// Remove old contents
for (fs::directory_iterator end, it(outputDir); it != end; ++it)
remove_all(it->path());
// Ensure output directory is empty
if (!fs::is_empty(outputDir)) {
PyErr_SetString(PyExc_ValueError,
"Output directory not empty");
boost::python::throw_error_already_set();
return;
}
void factgen2(std::vector<fs::path> files, fs::path outputDir, std::string delim);
// Run fact generation
factgen2(files, outputDir, delim);
}
// Translate parse exception to python
PyObject *parseExceptionType = NULL;
void translateParseException(ParseException const &e)
{
assert(parseExceptionType != NULL);
py::object pythonExceptionInstance(e);
PyErr_SetObject(parseExceptionType, pythonExceptionInstance.ptr());
}
// Create thin wrappers for overloaded function
BOOST_PYTHON_FUNCTION_OVERLOADS(pyfactgen_overloads, pyfactgen, 2, 3)
// Path converter
struct path_to_python_str
{
static PyObject* convert(fs::path const& p)
{
return boost::python::incref(
boost::python::object(p.string()).ptr());
}
};
// Declare boost python module
BOOST_PYTHON_MODULE(factgen)
{
using namespace boost::python;
// register exception
class_<ParseException>
parseExceptionClass("ParseException", py::init<fs::path>());
parseExceptionType = parseExceptionClass.ptr();
register_exception_translator<ParseException>
(&translateParseException);
// register the path-to-python converter
to_python_converter<fs::path, path_to_python_str>();
def("run", pyfactgen, pyfactgen_overloads());
}
| 26.356522
| 86
| 0.649951
|
TheoKant
|
5d2d63e0d058226c1e41194642b755d655e13334
| 2,244
|
hh
|
C++
|
src/EDepSimRootPersistencyManager.hh
|
andrewmogan/edep-sim
|
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
|
[
"MIT"
] | 15
|
2017-04-25T14:20:22.000Z
|
2022-03-15T19:39:43.000Z
|
src/EDepSimRootPersistencyManager.hh
|
andrewmogan/edep-sim
|
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
|
[
"MIT"
] | 24
|
2017-11-08T21:16:48.000Z
|
2022-03-04T13:33:18.000Z
|
src/EDepSimRootPersistencyManager.hh
|
andrewmogan/edep-sim
|
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
|
[
"MIT"
] | 20
|
2017-11-09T15:41:46.000Z
|
2022-01-25T20:52:32.000Z
|
////////////////////////////////////////////////////////////
// $Id: EDepSim::RootPersistencyManager.hh,v 1.31 2011/09/06 18:58:35 mcgrew Exp $
//
#ifndef EDepSim_RootPersistencyManager_hh_seen
#define EDepSim_RootPersistencyManager_hh_seen
#include <string>
#include <vector>
#include <map>
class TFile;
class TTree;
class TGeoManager;
#include "EDepSimPersistencyManager.hh"
/// Provide a root output for the geant 4 events. This just takes the summary
/// from EDepSim::PersistencyManager and dumps it as a tree.
namespace EDepSim {class RootPersistencyManager;}
class EDepSim::RootPersistencyManager : public EDepSim::PersistencyManager {
public:
/// Creates a root persistency manager. Through the "magic" of
/// G4VPersistencyManager the ultimate base class, this declared to the G4
/// persistency management system. You can only have one active
/// persistency class at any give moment.
RootPersistencyManager();
virtual ~RootPersistencyManager();
/// Return true if the ROOT output file is active. This means that the
/// output file is open and ready to accept data.
bool IsOpen();
/// Return a pointer to the current TFile.
TFile* GetTFile() const {return fOutput;}
/// Stores an event to the output file.
virtual G4bool Store(const G4Event* anEvent);
virtual G4bool Store(const G4Run* aRun);
virtual G4bool Store(const G4VPhysicalVolume* aWorld);
/// Retrieve information from a file. These are not implemented.
virtual G4bool Retrieve(G4Event *&e) {e=NULL; return false;}
virtual G4bool Retrieve(G4Run* &r) {r=NULL; return false;}
virtual G4bool Retrieve(G4VPhysicalVolume* &w) {w=NULL; return false;}
/// Interface with PersistencyMessenger (open and close the
/// database).
virtual G4bool Open(G4String dbname);
virtual G4bool Close(void);
private:
/// Make the MC Header and add it to truth.
void MakeMCHeader(const G4Event* src);
private:
/// The ROOT output file that events are saved into.
TFile *fOutput;
/// The event tree that contains the output events.
TTree *fEventTree;
/// The number of events saved to the output file since the last write.
int fEventsNotSaved;
};
#endif
| 33.492537
| 82
| 0.701872
|
andrewmogan
|
5d36a3a91d19830a053d6e2eb27a45be1dcff4d6
| 1,446
|
cc
|
C++
|
Player.cc
|
p-rivero/EDA-ThePurge2020
|
81a48df7bdaff6067792d037b9e6627739b959d1
|
[
"MIT"
] | null | null | null |
Player.cc
|
p-rivero/EDA-ThePurge2020
|
81a48df7bdaff6067792d037b9e6627739b959d1
|
[
"MIT"
] | null | null | null |
Player.cc
|
p-rivero/EDA-ThePurge2020
|
81a48df7bdaff6067792d037b9e6627739b959d1
|
[
"MIT"
] | null | null | null |
//////// STUDENTS DO NOT NEED TO READ BELOW THIS LINE ////////
#include "Player.hh"
void Player::reset (ifstream& is) {
// Should read what Board::print_state() prints.
// Should fill the same data structures as
// Board::Board (istream& is, int seed), except for settings and names.
// THESE DATA STRUCTURES MUST BE RESET: maps WITH clear(), etc.
*(Action*)this = Action();
citizens .clear();
player2builders .clear();
player2warriors .clear();
player2barricades.clear();
player2builders = vector<set<int>>(num_players());
player2warriors = vector<set<int>>(num_players());
player2barricades = vector<set<Pos>>(num_players());
read_grid(is);
string s;
is >> s >> rnd;
_my_assert(s == "round", "Expected 'round' while parsing.");
_my_assert(rnd >= 0 and rnd < num_rounds(), "Round is not ok.");
is >> s >> day;
_my_assert(s == "day", "Expected 'day' while parsing.");
is >> s;
_my_assert(s == "score", "Expected 'score' while parsing.");
scr = vector<int>(num_players());
for (auto& s : scr) {
is >> s;
_my_assert(s >= 0, "Score cannot be negative.");
}
is >> s;
_my_assert(s == "status", "Expected 'status' while parsing.");
stats = vector<double>(num_players());
for (auto& st : stats) {
is >> st;
_my_assert(st == -1 or (st >= 0 and st <= 1), "Status is not ok.");
}
_my_assert(ok(), "Invariants are not satisfied.");
// forget();
}
| 27.283019
| 73
| 0.612033
|
p-rivero
|
5d37e21f1f2a113a54bbe005cd72b14b5fd908e9
| 1,396
|
hpp
|
C++
|
Code/Engine/Scene/D3D11Scene.hpp
|
ntaylorbishop/Copycat
|
c02f2881f0700a33a2630fd18bc409177d80b8cd
|
[
"MIT"
] | 2
|
2017-10-02T03:18:55.000Z
|
2018-11-21T16:30:36.000Z
|
Code/Engine/Scene/D3D11Scene.hpp
|
ntaylorbishop/Copycat
|
c02f2881f0700a33a2630fd18bc409177d80b8cd
|
[
"MIT"
] | null | null | null |
Code/Engine/Scene/D3D11Scene.hpp
|
ntaylorbishop/Copycat
|
c02f2881f0700a33a2630fd18bc409177d80b8cd
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Engine/General/Core/EngineCommon.hpp"
class D3D11Model;
class D3D11Material;
class D3D11MeshRenderer;
const float ANIMATION_FPS = 30.f;
const float MESH_LOAD_ENGINE_SCALE = 0.4f;
class D3D11Scene {
public:
//LOADING SAVING
void AddModelsFromDirectory(const char* dir);
static D3D11Scene* LoadSceneFromDirectory(const char* sceneDir);
static D3D11Scene* LoadSceneFromFBXFile(const char* filename);
void SaveSceneToFile(const char* filepath);
//STRUCTORS
D3D11Scene() { }
~D3D11Scene() { }
//RENDER
void RenderForShadows(D3D11Material* shadowMat) const;
void RenderWithMaterial(D3D11Material* mat) const;
void Render(bool isRenderingTransparent = false, D3D11MeshRenderer* customMeshRenderer = nullptr) const;
void RenderSkybox(D3D11MeshRenderer* customMeshRenderer = nullptr) const;
//ADDING REMOVING
void AddModel(D3D11Model* newMesh);
void RemoveModel(D3D11Model* mesh);
void SetSkybox(D3D11Model* skybox) { m_skybox = skybox; }
void EnableDebugSorting() { m_debugShouldSort = true; }
void DisableDebugSorting() { m_debugShouldSort = false; }
private:
//PRIVATE ADD REMOVE
void AddStaticMeshToOpaquePass(D3D11Model* newMesh);
void RemoveStaticMeshFromOpaquePass(D3D11Model* mesh);
D3D11Model* m_opaqueMeshes = nullptr;
size_t m_numMeshes = 0;
D3D11Model* m_skybox = nullptr;
bool m_debugShouldSort = false;
};
| 28.489796
| 105
| 0.77149
|
ntaylorbishop
|
5d3976ed6c5b2959434579750f8e5ee37ca0872d
| 3,045
|
cpp
|
C++
|
hoo/emitter/DefinitionEmitter.cpp
|
benoybose/hoolang
|
4e280a03caec837be35c8aac948923e1bea96b85
|
[
"BSD-3-Clause"
] | null | null | null |
hoo/emitter/DefinitionEmitter.cpp
|
benoybose/hoolang
|
4e280a03caec837be35c8aac948923e1bea96b85
|
[
"BSD-3-Clause"
] | 14
|
2020-07-24T10:25:59.000Z
|
2020-08-02T13:27:09.000Z
|
hoo/emitter/DefinitionEmitter.cpp
|
benoybose/hoolang
|
4e280a03caec837be35c8aac948923e1bea96b85
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2021 Benoy Bose
*
* 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 <hoo/emitter/DefinitionEmitter.hh>
#include <hoo/emitter/ClassDefinitionEmitter.hh>
#include <hoo/emitter/EmitterException.hh>
#include <hoo/emitter/FunctionDefinitionEmitter.hh>
#include <hoo/ast/ClassDefinition.hh>
#include <hoo/ast/FunctionDefinition.hh>
#include <memory>
namespace hoo
{
namespace emitter
{
DefinitionEmitter::DefinitionEmitter(std::shared_ptr<Definition> definition,
const EmitterContext& context,
std::shared_ptr<ClassDefinition> parent_class_definition) :
EmitterBase(context),
_definition(definition),
_parent_class_definition (parent_class_definition)
{
}
std::shared_ptr<ClassDefinition> DefinitionEmitter::GetParentClass()
{
return _parent_class_definition;
}
void DefinitionEmitter::Emit()
{
auto const definitionType = _definition->GetDefinitionType();
switch (definitionType) {
case DEFINITION_CLASS:
{
auto classDefinition = std::dynamic_pointer_cast<ClassDefinition>(_definition);
ClassDefinitionEmitter emitter(classDefinition,
_emitter_context,
_parent_class_definition);
emitter.Emit();
break;
}
case DEFINITION_FUNCTION:
{
auto function_definition = std::dynamic_pointer_cast<FunctionDefinition>(_definition);
FunctionDefinitionEmitter emitter(function_definition,
_emitter_context,
_parent_class_definition);
emitter.Emit();
break;
}
default:
{
throw EmitterException(ERR_EMITTER_UNSUPPORTED_DEFINITION);
}
}
}
}
}
| 39.038462
| 106
| 0.649589
|
benoybose
|
5d39b30e65c6aa79ab650860f8d001bd3dfb1d96
| 472
|
cpp
|
C++
|
ConsoleApplication1/ConsoleApplication1/JsonParser.cpp
|
AndrFran/CodeInstrumentation
|
e58ab6d4a6dd5e70d00b5915820af5b0cd9dc33c
|
[
"MIT"
] | null | null | null |
ConsoleApplication1/ConsoleApplication1/JsonParser.cpp
|
AndrFran/CodeInstrumentation
|
e58ab6d4a6dd5e70d00b5915820af5b0cd9dc33c
|
[
"MIT"
] | null | null | null |
ConsoleApplication1/ConsoleApplication1/JsonParser.cpp
|
AndrFran/CodeInstrumentation
|
e58ab6d4a6dd5e70d00b5915820af5b0cd9dc33c
|
[
"MIT"
] | null | null | null |
#include "JsonParser.h"
namespace WpfApplication2
{
JsonParser::JsonParser()
{
serializer = new JavaScriptSerializer();
}
std::unordered_map<std::wstring, std::any> JsonParser::Deserialize(const std::wstring &json)
{
serializer->Deserialize<std::unordered_map<std::wstring, std::any>>(json);
std::unordered_map<std::wstring, std::any> ParsedFunction = serializer->Deserialize<std::unordered_map<std::wstring, std::any>>(json);
return ParsedFunction;
}
}
| 26.222222
| 136
| 0.735169
|
AndrFran
|
5d41558a4723b240fe82cae068b4139894708bdb
| 1,217
|
cpp
|
C++
|
unittest/vslib/test_sai_vs_vlan.cpp
|
vmittal-msft/sonic-sairedis
|
6baff35880005aee2854fdcde105c4322c28d04f
|
[
"Apache-2.0"
] | 50
|
2016-03-23T08:04:44.000Z
|
2022-03-25T05:06:16.000Z
|
unittest/vslib/test_sai_vs_vlan.cpp
|
vmittal-msft/sonic-sairedis
|
6baff35880005aee2854fdcde105c4322c28d04f
|
[
"Apache-2.0"
] | 589
|
2016-04-01T04:09:09.000Z
|
2022-03-31T00:38:10.000Z
|
unittest/vslib/test_sai_vs_vlan.cpp
|
vmittal-msft/sonic-sairedis
|
6baff35880005aee2854fdcde105c4322c28d04f
|
[
"Apache-2.0"
] | 234
|
2016-03-28T20:59:21.000Z
|
2022-03-23T09:26:22.000Z
|
#include <gtest/gtest.h>
extern "C" {
#include "sai.h"
}
#include "swss/logger.h"
TEST(libsaivs, vlan)
{
sai_vlan_api_t *api = nullptr;
sai_api_query(SAI_API_VLAN, (void**)&api);
EXPECT_NE(api, nullptr);
sai_object_id_t id;
EXPECT_NE(SAI_STATUS_SUCCESS, api->create_vlan(&id,0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->remove_vlan(0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->set_vlan_attribute(0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_attribute(0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->create_vlan_member(&id,0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->remove_vlan_member(0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->set_vlan_member_attribute(0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_member_attribute(0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->create_vlan_members(0,0,0,0,SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->remove_vlan_members(0,0,SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_stats(0,0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_stats_ext(0,0,0,SAI_STATS_MODE_READ,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->clear_vlan_stats(0,0,0));
}
| 33.805556
| 109
| 0.750205
|
vmittal-msft
|
5d41b503b13fdb258fc80e6d5c1fe552b2ad1d56
| 3,234
|
hpp
|
C++
|
src/Property_reflect.hpp
|
cpp-ftw/tmp-lib
|
6b4afd294b20d615abe9f409241409bed378eaa7
|
[
"MIT"
] | null | null | null |
src/Property_reflect.hpp
|
cpp-ftw/tmp-lib
|
6b4afd294b20d615abe9f409241409bed378eaa7
|
[
"MIT"
] | null | null | null |
src/Property_reflect.hpp
|
cpp-ftw/tmp-lib
|
6b4afd294b20d615abe9f409241409bed378eaa7
|
[
"MIT"
] | null | null | null |
#ifndef PROPERTY_HPP_INCLUDED
#define PROPERTY_HPP_INCLUDED
// mire jó: getter és setter helyettesítése egy publikus, fiktív adattaggal.
#define PROPERTY( parent, return_type, name) Property<parent, return_type, (& parent :: set ##name), (& parent :: get ##name)> name{this}
#define PROPERTY_(parent, return_type, name) Property<parent, return_type, (& parent :: set_##name), (& parent :: get_##name)> name{this}
// 1 db akármilyen típusú member pointert tárol
template<typename CLASS, typename T, T CLASS::* MPTR>
struct MptrHolder
{
static constexpr auto mptr = MPTR;
};
// n db akármilyen típusú member pointert tárol
template<typename CLASS, typename... MPTRS>
struct MptrCollection
{
// belső használatú fos, hátha jobban olvasható a variadic magic
#define SELF (static_cast< CLASS*>(self))
#define CSELF (static_cast<const CLASS*>(self))
static void set_objs(CLASS * self)
{
using swallow = int[];
(void) swallow {0, ((void)((SELF->*(MPTRS::mptr)).obj = SELF), 0)...};
}
#undef SELF
#undef CSELF
};
// levezeti 1 db member pointer osztályának típusát
template<typename CLASS, typename T>
CLASS make_mptr_class(T CLASS::* mptr);
// levezeti 1 db member pointer típusát
template<typename CLASS, typename T>
T make_mptr_type(T CLASS::* mptr);
// becsomagol 1 db member pointert egy típusba
#define PROPERTY_MAKE(x) MptrHolder<decltype(make_mptr_class(x)), decltype(make_mptr_type(x)), x>
// becsomagol n db member pointert egy típusba
#define PROPERTY_DECLARE(x, ...) using properties = MptrCollection<Vektor, __VA_ARGS__>
template<typename CLASS>
class PropertyCRTP;
template <typename CLASS, typename T,
void (CLASS::*SETTERPTR) (T const& newvalue),
T (CLASS::*GETTERPTR) () const>
class Property
{
friend class PropertyCRTP<CLASS>;
template<typename, typename...>
friend class MptrCollection;
CLASS * obj;
constexpr explicit Property (CLASS* obj) : obj (obj) {}
// no-op: a PropertyCRTP feladata a pointerek beállítgatása, és ezt még
// azelőtt megteszi, hogy ide eljutnánk, így itt nem szabad rajta piszkálni
// private + friend, azért, hogy ne lehessen leírni:
// auto x = foo.property;
constexpr Property() { }
constexpr Property(Property const&) { }
constexpr Property(Property&&) { }
friend CLASS;
public:
// property beállítása
Property& operator= (T const& newvalue)
{
((*obj).*SETTERPTR) (newvalue);
return *this;
}
// property lekérdezése
operator T () const
{
return ((*obj).*GETTERPTR) ();
}
// property = property eset kezelése
Property& operator= (Property const& the_other)
{
*this = the_other.operator T();
return *this;
}
};
// ebből kell leszármaznia a Property-t tartalmazó osztálynak
template<typename Derived>
class PropertyCRTP
{
void set_objs()
{
using d_prop = typename Derived::properties;
d_prop::set_objs(static_cast<Derived*>(this));
}
protected:
PropertyCRTP() {
set_objs();
}
PropertyCRTP(PropertyCRTP const&) {
set_objs();
}
PropertyCRTP(PropertyCRTP&&) {
set_objs();
}
};
#endif // PROPERTY_HPP_INCLUDED
| 27.40678
| 137
| 0.675943
|
cpp-ftw
|
5d467ab3ed5e73c364e210676a97cc7d1a1fcbcc
| 12,126
|
cpp
|
C++
|
src/PFsLib/PFsLib.cpp
|
KurtE/UsbMscFat
|
8c4f312b229af5db17a4b43852469466e542e3d0
|
[
"MIT"
] | 2
|
2022-02-04T20:37:37.000Z
|
2022-03-01T02:41:14.000Z
|
src/PFsLib/PFsLib.cpp
|
KurtE/UsbMscFat
|
8c4f312b229af5db17a4b43852469466e542e3d0
|
[
"MIT"
] | 1
|
2021-03-10T01:35:04.000Z
|
2021-03-10T01:35:04.000Z
|
src/PFsLib/PFsLib.cpp
|
KurtE/UsbMscFat
|
8c4f312b229af5db17a4b43852469466e542e3d0
|
[
"MIT"
] | 3
|
2021-03-09T01:06:44.000Z
|
2021-03-29T12:21:20.000Z
|
#include "PFsLib.h"
//Set to 0 for debug info
#define DBG_Print 1
#if defined(DBG_Print)
#define DBGPrintf Serial.printf
#else
void inline DBGPrintf(...) {};
#endif
//------------------------------------------------------------------------------
#define PRINT_FORMAT_PROGRESS 1
#if !PRINT_FORMAT_PROGRESS
#define writeMsg(str)
#elif defined(__AVR__)
#define writeMsg(str) if (m_pr) m_pr->print(F(str))
#else // PRINT_FORMAT_PROGRESS
#define writeMsg(str) if (m_pr) m_pr->write(str)
#endif // PRINT_FORMAT_PROGRESS
//----------------------------------------------------------------
#define SECTORS_2GB 4194304 // (2^30 * 2) / 512
#define SECTORS_32GB 67108864 // (2^30 * 32) / 512
#define SECTORS_127GB 266338304 // (2^30 * 32) / 512
//uint8_t partVols_drive_index[10];
//=============================================================================
bool PFsLib::deletePartition(BlockDeviceInterface *blockDev, uint8_t part, print_t* pr, Stream &Serialx)
{
uint8_t sectorBuffer[512];
m_pr = pr;
MbrSector_t* mbr = reinterpret_cast<MbrSector_t*>(sectorBuffer);
if (!blockDev->readSector(0, sectorBuffer)) {
writeMsg("\nERROR: read MBR failed.\n");
return false;
}
if ((part < 1) || (part > 4)) {
m_pr->printf("ERROR: Invalid Partition: %u, only 1-4 are valid\n", part);
return false;
}
writeMsg("Warning this will delete the partition are you sure, continue: Y? ");
int ch;
//..... TODO CIN for READ ......
while ((ch = Serialx.read()) == -1) ;
if (ch != 'Y') {
writeMsg("Canceled");
return false;
}
DBGPrintf("MBR Before");
#if(DBG_Print)
dump_hexbytes(&mbr->part[0], 4*sizeof(MbrPart_t));
#endif
// Copy in the higher numer partitions;
for (--part; part < 3; part++) memcpy(&mbr->part[part], &mbr->part[part+1], sizeof(MbrPart_t));
// clear out the last one
memset(&mbr->part[part], 0, sizeof(MbrPart_t));
DBGPrintf("MBR After");
#if(DBG_Print)
dump_hexbytes(&mbr->part[0], 4*sizeof(MbrPart_t));
#endif
return blockDev->writeSector(0, sectorBuffer);
}
//===========================================================================
//----------------------------------------------------------------
#define SECTORS_2GB 4194304 // (2^30 * 2) / 512
#define SECTORS_32GB 67108864 // (2^30 * 32) / 512
#define SECTORS_127GB 266338304 // (2^30 * 32) / 512
//uint8_t partVols_drive_index[10];
//----------------------------------------------------------------
// Function to handle one MS Drive...
//msc[drive_index].usbDrive()
void PFsLib::InitializeDrive(BlockDeviceInterface *dev, uint8_t fat_type, print_t* pr)
{
uint8_t sectorBuffer[512];
m_dev = dev;
m_pr = pr;
//TODO: have to see if this is still valid
PFsVolume partVol;
/*
for (int ii = 0; ii < count_partVols; ii++) {
if (partVols_drive_index[ii] == drive_index) {
while (Serial.read() != -1) ;
writeMsg("Warning it appears like this drive has valid partitions, continue: Y? ");
int ch;
while ((ch = Serial.read()) == -1) ;
if (ch != 'Y') {
writeMsg("Canceled");
return;
}
break;
}
}
if (drive_index == LOGICAL_DRIVE_SDIO) {
dev = sd.card();
} else if (drive_index == LOGICAL_DRIVE_SDSPI) {
dev = sdSPI.card();
} else {
if (!msDrives[drive_index]) {
writeMsg("Not a valid USB drive");
return;
}
dev = (USBMSCDevice*)msc[drive_index].usbDrive();
}
*/
uint32_t sectorCount = dev->sectorCount();
m_pr->printf("sectorCount = %u, FatType: %x\n", sectorCount, fat_type);
// Serial.printf("Blocks: %u Size: %u\n", msDrives[drive_index].msCapacity.Blocks, msDrives[drive_index].msCapacity.BlockSize);
if ((fat_type == FAT_TYPE_EXFAT) && (sectorCount < 0X100000 )) fat_type = 0; // hack to handle later
if ((fat_type == FAT_TYPE_FAT16) && (sectorCount >= SECTORS_2GB )) fat_type = 0; // hack to handle later
if ((fat_type == FAT_TYPE_FAT32) && (sectorCount >= SECTORS_127GB )) fat_type = 0; // hack to handle later
if (fat_type == 0) {
// assume 512 byte blocks here..
if (sectorCount < SECTORS_2GB) fat_type = FAT_TYPE_FAT16;
else if (sectorCount < SECTORS_32GB) fat_type = FAT_TYPE_FAT32;
else fat_type = FAT_TYPE_EXFAT;
}
// lets generate a MBR for this type...
memset(sectorBuffer, 0, 512); // lets clear out the area.
MbrSector_t* mbr = reinterpret_cast<MbrSector_t*>(sectorBuffer);
setLe16(mbr->signature, MBR_SIGNATURE);
// Temporary until exfat is setup...
if (fat_type == FAT_TYPE_EXFAT) {
m_pr->println("TODO createPartition on ExFat");
m_dev->writeSector(0, sectorBuffer);
createExFatPartition(m_dev, 2048, sectorCount, sectorBuffer, &Serial);
return;
} else {
// Fat16/32
m_dev->writeSector(0, sectorBuffer);
createFatPartition(m_dev, fat_type, 2048, sectorCount, sectorBuffer, &Serial);
}
m_dev->syncDevice();
writeMsg("Format Done\r\n");
}
void PFsLib::formatter(PFsVolume &partVol, uint8_t fat_type, bool dump_drive, bool g_exfat_dump_changed_sectors, Stream &Serialx)
{
uint8_t sectorBuffer[512];
if (fat_type == 0) fat_type = partVol.fatType();
if (fat_type != FAT_TYPE_FAT12) {
//
uint8_t buffer[512];
MbrSector_t *mbr = (MbrSector_t *)buffer;
if (!partVol.blockDevice()->readSector(0, buffer)) return;
MbrPart_t *pt = &mbr->part[partVol.part() - 1];
uint32_t sector = getLe32(pt->relativeSectors);
// I am going to read in 24 sectors for EXFat..
uint8_t *bpb_area = (uint8_t*)malloc(512*24);
if (!bpb_area) {
Serialx.println("Unable to allocate dump memory");
return;
}
// Lets just read in the top 24 sectors;
uint8_t *sector_buffer = bpb_area;
for (uint32_t i = 0; i < 24; i++) {
partVol.blockDevice()->readSector(sector+i, sector_buffer);
sector_buffer += 512;
}
if (dump_drive) {
sector_buffer = bpb_area;
for (uint32_t i = 0; i < 12; i++) {
Serialx.printf("\nSector %u(%u)\n", i, sector);
dump_hexbytes(sector_buffer, 512);
sector++;
sector_buffer += 512;
}
for (uint32_t i = 12; i < 24; i++) {
Serialx.printf("\nSector %u(%u)\n", i, sector);
compare_dump_hexbytes(sector_buffer, sector_buffer - (512*12), 512);
sector++;
sector_buffer += 512;
}
} else {
if (fat_type != FAT_TYPE_EXFAT) {
PFsFatFormatter::format(partVol, fat_type, sectorBuffer, &Serialx);
} else {
Serialx.println("ExFatFormatter - WIP");
PFsExFatFormatter::format(partVol, sectorBuffer, &Serial);
if (g_exfat_dump_changed_sectors) {
// Now lets see what changed
uint8_t *sector_buffer = bpb_area;
for (uint32_t i = 0; i < 24; i++) {
partVol.blockDevice()->readSector(sector, buffer);
Serialx.printf("Sector %u(%u)\n", i, sector);
if (memcmp(buffer, sector_buffer, 512)) {
compare_dump_hexbytes(buffer, sector_buffer, 512);
Serialx.println();
}
sector++;
sector_buffer += 512;
}
}
}
}
free(bpb_area);
}
else
Serialx.println("Cannot format an invalid partition");
}
//================================================================================================
void PFsLib::print_partion_info(PFsVolume &partVol, Stream &Serialx)
{
uint8_t buffer[512];
MbrSector_t *mbr = (MbrSector_t *)buffer;
if (!partVol.blockDevice()->readSector(0, buffer)) return;
MbrPart_t *pt = &mbr->part[partVol.part() - 1];
uint32_t starting_sector = getLe32(pt->relativeSectors);
uint32_t sector_count = getLe32(pt->totalSectors);
Serialx.printf("Starting Sector: %u, Sector Count: %u\n", starting_sector, sector_count);
FatPartition *pfp = partVol.getFatVol();
if (pfp) {
Serialx.printf("fatType:%u\n", pfp->fatType());
Serialx.printf("bytesPerClusterShift:%u\n", pfp->bytesPerClusterShift());
Serialx.printf("bytesPerCluster:%u\n", pfp->bytesPerCluster());
Serialx.printf("bytesPerSector:%u\n", pfp->bytesPerSector());
Serialx.printf("bytesPerSectorShift:%u\n", pfp->bytesPerSectorShift());
Serialx.printf("sectorMask:%u\n", pfp->sectorMask());
Serialx.printf("sectorsPerCluster:%u\n", pfp->sectorsPerCluster());
Serialx.printf("sectorsPerFat:%u\n", pfp->sectorsPerFat());
Serialx.printf("clusterCount:%u\n", pfp->clusterCount());
Serialx.printf("dataStartSector:%u\n", pfp->dataStartSector());
Serialx.printf("fatStartSector:%u\n", pfp->fatStartSector());
Serialx.printf("rootDirEntryCount:%u\n", pfp->rootDirEntryCount());
Serialx.printf("rootDirStart:%u\n", pfp->rootDirStart());
}
}
uint32_t PFsLib::mbrDmp(BlockDeviceInterface *blockDev, uint32_t device_sector_count, Stream &Serialx) {
MbrSector_t mbr;
uint32_t next_free_sector = 8192; // Some inital value this is default for Win32 on SD...
// bool valid = true;
if (!blockDev->readSector(0, (uint8_t*)&mbr)) {
Serialx.print("\nread MBR failed.\n");
//errorPrint();
return (uint32_t)-1;
}
Serialx.print("\nmsc # Partition Table\n");
Serialx.print("\tpart,boot,bgnCHS[3],type,endCHS[3],start,length\n");
for (uint8_t ip = 1; ip < 5; ip++) {
MbrPart_t *pt = &mbr.part[ip - 1];
uint32_t starting_sector = getLe32(pt->relativeSectors);
uint32_t total_sector = getLe32(pt->totalSectors);
if (starting_sector > next_free_sector) {
Serialx.printf("\t < unused area starting at: %u length %u >\n", next_free_sector, starting_sector-next_free_sector);
}
switch (pt->type) {
case 4:
case 6:
case 0xe:
Serial.print("FAT16:\t");
break;
case 11:
case 12:
Serial.print("FAT32:\t");
break;
case 7:
Serial.print("exFAT:\t");
break;
case 0xf:
Serial.print("Extend:\t");
break;
case 0x83: Serial.print("ext2/3/4:\t"); break;
default:
Serialx.print("pt_#");
Serialx.print(pt->type);
Serialx.print(":\t");
break;
}
Serialx.print( int(ip)); Serial.print( ',');
Serialx.print(int(pt->boot), HEX); Serial.print( ',');
for (int i = 0; i < 3; i++ ) {
Serialx.print("0x"); Serial.print(int(pt->beginCHS[i]), HEX); Serial.print( ',');
}
Serialx.print("0x"); Serial.print(int(pt->type), HEX); Serial.print( ',');
for (int i = 0; i < 3; i++ ) {
Serialx.print("0x"); Serial.print(int(pt->endCHS[i]), HEX); Serial.print( ',');
}
Serialx.print(starting_sector, DEC); Serial.print(',');
Serialx.println(total_sector);
// Lets get the max of start+total
if (starting_sector && total_sector) next_free_sector = starting_sector + total_sector;
}
if ((device_sector_count != (uint32_t)-1) && (next_free_sector < device_sector_count)) {
Serialx.printf("\t < unused area starting at: %u length %u >\n", next_free_sector, device_sector_count-next_free_sector);
}
return next_free_sector;
}
//----------------------------------------------------------------
void PFsLib::dump_hexbytes(const void *ptr, int len)
{
if (ptr == NULL || len <= 0) return;
const uint8_t *p = (const uint8_t *)ptr;
while (len) {
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
m_pr->printf("%02X ", p[i]);
}
m_pr->print(":");
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
m_pr->printf("%c", ((p[i] >= ' ') && (p[i] <= '~')) ? p[i] : '.');
}
m_pr->println();
p += 32;
len -= 32;
}
}
void PFsLib::compare_dump_hexbytes(const void *ptr, const uint8_t *compare_buf, int len)
{
if (ptr == NULL || len <= 0) return;
const uint8_t *p = (const uint8_t *)ptr;
while (len) {
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
Serial.printf("%c%02X", (p[i]==compare_buf[i])? ' ' : '*',p[i]);
}
Serial.print(":");
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
Serial.printf("%c", ((p[i] >= ' ') && (p[i] <= '~')) ? p[i] : '.');
}
Serial.println();
p += 32;
compare_buf += 32;
len -= 32;
}
}
| 33.131148
| 129
| 0.593023
|
KurtE
|
5d4b3af8036e4e9bcbfac2a2acb41882b3699e47
| 4,042
|
cc
|
C++
|
logga/fitness.cc
|
wahibium/KFF
|
609e5afac8a9477dd1af31eacadbcd5b61530113
|
[
"MIT"
] | 11
|
2015-06-08T22:16:47.000Z
|
2022-03-19T15:11:14.000Z
|
logga/fitness.cc
|
wahibium/KFF
|
609e5afac8a9477dd1af31eacadbcd5b61530113
|
[
"MIT"
] | null | null | null |
logga/fitness.cc
|
wahibium/KFF
|
609e5afac8a9477dd1af31eacadbcd5b61530113
|
[
"MIT"
] | 4
|
2015-06-12T21:24:47.000Z
|
2021-04-23T09:58:33.000Z
|
// ================================================================================
// ================================================================================
//
// Instructions for adding a new fitness function:
// ------------------------------------------------
//
// 1. create a function with the same input parameters as other fitness functions
// defined in this file (e.g., onemax) that returns the value of the fitness
// given a binary chromosome of a particular length (sent as input parameters
// to the fitness)
//
// 2. put the function definition in the fitness.h header file (look at onemax
// as an example)
//
// 3. increase the counter numFitness and add a structure to the array of the
// fitness descriptions fitnessDesc below. For compatibility of recent input
// files, put it at the end of this array, in order not to change the numbers
// of already defined and used functions. The structure has the following items
// (in this order):
// a) a string description of the function (informative in output data files)
// b) a pointer to the function (simple "&" followed by the name of a function)
// c) a pointer to the function that returns true if an input solution is
// globally optimal and false if this is not the case. If such function is
// not available, just use NULL instead. The algorithm will understand...
// d) a pointer to the function for initialization of the particular fitness
// function (not used in any of these and probably not necessary for most
// of the functions, but in case reading input file would be necessary
// or so, it might be used in this way). Use NULL if there is no such
// function
// e) a pointer to the "done" function, called when the fitness is not to be
// used anymore, in case some memory is allocated in its initialization;
// here it can be freed. Use NULL if there is no need for such function
//
// 4. the function will be assigned a number equal to its ordering number in the
// array of function descriptions fitnessDesc minus 1 (the functions are
// assigned numbers consequently starting at 0); so its number will be equal
// to the number of fitness definitions minus 1 at the time it is added. Its
// description in output files will be the same as the description string
// (see 3a)
//
// ================================================================================
// ================================================================================
#include <stdio.h>
#include <stdlib.h>
#include "chromosome.h"
#include "fitness.h"
#include "gga.h"
#define numFitness 3
static Fitness fitnessDesc[numFitness] = {
{"Roofline Model",&roofline,&bestSolution,NULL,NULL},
{"Simple Model",&simplemodel,&bestSolution,NULL,NULL},
{"Complex Model",&complexmodel,&bestSolution,NULL,NULL},
};
Fitness *fitness;
long fitnessCalls_;
char BestSolution(Chromosome *chromosome)
{
register int i;
for (i=0; (i<n)&&(x[i]==1); i++);
return (i==n);
}
int SetFitness(int n)
{
if ((n>=0) && (n<numFitness))
fitness = &(fitnessDesc[n]);
else
{
fprintf(stderr,"ERROR: Specified fitness function doesn't exist (%u)!",n);
exit(-1);
}
return 0;
}
char* GetFitnessDesc(int n)
{
return fitnessDesc[n].description;
}
int InitializeFitness(GGAParams *ggaParams)
{
if (fitness->init)
return fitness->init(ggaParams);
return 0;
}
int DoneFitness(GGAParams *ggaParams)
{
if (fitness->done)
return fitness->done(ggaParams);
return 0;
}
float GetFitnessValue(Chromosome *chromosome)
{
fitnessCalled();
return fitness->fitness(x,n);
}
int IsBestDefined()
{
return (int) (fitness->isBest!=NULL);
}
int IsOptimal(char *x, int n)
{
return fitness->isBest(x,n);
}
int ResetFitnessCalls(void)
{
return (int) (fitnessCalls_=0);
}
long FitnessCalled(void)
{
return fitnessCalls_++;
}
long GetFitnessCalls(void)
{
return fitnessCalls_;
}
| 28.069444
| 84
| 0.621969
|
wahibium
|
5d53daf83387b633254466c89b432cdcb386f0ac
| 1,225
|
cpp
|
C++
|
grammar/src/numExpression.cpp
|
troeggla/blocky
|
ef2e32369065f7aff7c7c807712c67d9eb25f75d
|
[
"BSD-2-Clause"
] | null | null | null |
grammar/src/numExpression.cpp
|
troeggla/blocky
|
ef2e32369065f7aff7c7c807712c67d9eb25f75d
|
[
"BSD-2-Clause"
] | null | null | null |
grammar/src/numExpression.cpp
|
troeggla/blocky
|
ef2e32369065f7aff7c7c807712c67d9eb25f75d
|
[
"BSD-2-Clause"
] | null | null | null |
#include "numExpression.hpp"
NumExpression::NumExpression(double value) {
this->value = new double;
*(this->value) = value;
}
NumExpression::NumExpression(BlockScope* scope, std::string var) : scope(scope), var(var) {
}
NumExpression::NumExpression(NumExpression *ex1, NumExpression *ex2, char op) : ex1(ex1), ex2(ex2), op(op) {
}
NumExpression::~NumExpression() {
delete value;
delete ex1;
delete ex2;
}
std::string NumExpression::getType() {
return "numerical";
}
double NumExpression::evaluate() {
if (this->value != 0) {
return *value;
} else if (scope != 0) {
return scope->get_var(var);
} else {
double val1 = ex1->evaluate();
double val2 = ex2->evaluate();
switch (op) {
case '+':
return ex1->evaluate() + ex2->evaluate();
case '-':
return ex1->evaluate() - ex2->evaluate();
case '*':
return ex1->evaluate() * ex2->evaluate();
case '/':
return ex1->evaluate() / ex2->evaluate();
case '^':
return pow(ex1->evaluate(), ex2->evaluate());
case '%':
return (int)ex1->evaluate() % (int)ex2->evaluate();
}
}
}
| 25
| 108
| 0.553469
|
troeggla
|
5d5fca61eb70013bfa5cfa0b88ec29791f68293e
| 1,689
|
cpp
|
C++
|
src/generator/constant.cpp
|
ikitayama/cobi
|
e9bc4a5675ead1874ad9ffa953de8edb3a763479
|
[
"BSD-3-Clause"
] | null | null | null |
src/generator/constant.cpp
|
ikitayama/cobi
|
e9bc4a5675ead1874ad9ffa953de8edb3a763479
|
[
"BSD-3-Clause"
] | null | null | null |
src/generator/constant.cpp
|
ikitayama/cobi
|
e9bc4a5675ead1874ad9ffa953de8edb3a763479
|
[
"BSD-3-Clause"
] | 1
|
2018-12-14T02:45:41.000Z
|
2018-12-14T02:45:41.000Z
|
/*****************************************************************************
** Cobi http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 2009-2010 **
** Forschungszentrum Juelich, Juelich Supercomputing Centre **
** **
** See the file COPYRIGHT in the base directory for details **
*****************************************************************************/
/**
* @file constant.cpp
* @author Jan Mussler
* @brief Implements the constant AST nodes
*
* NullOp, String and Integer const expressions
*/
#include "generator.h"
using namespace gi::generator;
BPatch_snippet* NullOp::getSnippet(IContext* c) {
return new BPatch_nullExpr();
}
NullOp::~NullOp() {
}
NullOp::NullOp() {
}
Constant* Constant::createConstant(int i) {
return new IntConstant(i);
}
Constant* Constant::createConstant(std::string s) {
return new StrConstant(s);
}
IntConstant::IntConstant(int i) : value(i) {
}
string IntConstant::getStringValue(IContext* c) {
stringstream ss;
ss << value;
return ss.str();
}
BPatch_snippet* IntConstant::getSnippet(IContext* c) {
return new BPatch_constExpr(value);
}
StrConstant::StrConstant(std::string s) : value(s) {
}
string StrConstant::getStringValue(IContext* c) {
return value;
}
BPatch_snippet* StrConstant::getSnippet(IContext* c) {
return new BPatch_constExpr(value.c_str());
}
| 26.809524
| 80
| 0.492599
|
ikitayama
|
5d62dadacc9740ce55d885e4a0aa7d6751eb4b75
| 2,419
|
cpp
|
C++
|
Permissions/Permissions/Private/Permissions.cpp
|
forced1988/Ark-Server-Plugins
|
a5f05fa0b1df467d001f7ce09de2e7468e22e5eb
|
[
"MIT"
] | 1
|
2021-01-25T13:41:34.000Z
|
2021-01-25T13:41:34.000Z
|
Permissions/Permissions/Private/Permissions.cpp
|
forced1988/Ark-Server-Plugins
|
a5f05fa0b1df467d001f7ce09de2e7468e22e5eb
|
[
"MIT"
] | null | null | null |
Permissions/Permissions/Private/Permissions.cpp
|
forced1988/Ark-Server-Plugins
|
a5f05fa0b1df467d001f7ce09de2e7468e22e5eb
|
[
"MIT"
] | 1
|
2020-05-24T18:01:41.000Z
|
2020-05-24T18:01:41.000Z
|
#ifdef PERMISSIONS_ARK
#include "../Public/ArkPermissions.h"
#else
#include "../Public/AtlasPermissions.h"
#endif
#include "Main.h"
namespace Permissions
{
TArray<FString> GetPlayerGroups(uint64 steam_id)
{
return database->GetPlayerGroups(steam_id);
}
TArray<FString> GetGroupPermissions(const FString& group)
{
if (group.IsEmpty())
return {};
return database->GetGroupPermissions(group);
}
TArray<FString> GetAllGroups()
{
return database->GetAllGroups();
}
TArray<uint64> GetGroupMembers(const FString& group)
{
return database->GetGroupMembers(group);
}
bool IsPlayerInGroup(uint64 steam_id, const FString& group)
{
TArray<FString> groups = GetPlayerGroups(steam_id);
for (const auto& current_group : groups)
{
if (current_group == group)
return true;
}
return false;
}
std::optional<std::string> AddPlayerToGroup(uint64 steam_id, const FString& group)
{
return database->AddPlayerToGroup(steam_id, group);
}
std::optional<std::string> RemovePlayerFromGroup(uint64 steam_id, const FString& group)
{
return database->RemovePlayerFromGroup(steam_id, group);
}
std::optional<std::string> AddGroup(const FString& group)
{
return database->AddGroup(group);
}
std::optional<std::string> RemoveGroup(const FString& group)
{
return database->RemoveGroup(group);
}
bool IsGroupHasPermission(const FString& group, const FString& permission)
{
if (!database->IsGroupExists(group))
return false;
TArray<FString> permissions = GetGroupPermissions(group);
for (const auto& current_perm : permissions)
{
if (current_perm == permission)
return true;
}
return false;
}
bool IsPlayerHasPermission(uint64 steam_id, const FString& permission)
{
TArray<FString> groups = GetPlayerGroups(steam_id);
for (const auto& current_group : groups)
{
if (IsGroupHasPermission(current_group, permission) || IsGroupHasPermission(current_group, "*"))
return true;
}
return false;
}
std::optional<std::string> GroupGrantPermission(const FString& group, const FString& permission)
{
return database->GroupGrantPermission(group, permission);
}
std::optional<std::string> GroupRevokePermission(const FString& group, const FString& permission)
{
return database->GroupRevokePermission(group, permission);
}
}
| 23.038095
| 100
| 0.702356
|
forced1988
|
5d63da1666829dbbde3b023b8dfce0c11ae41b22
| 6,867
|
cpp
|
C++
|
vendor/mysql-connector-c++-1.1.3/test/framework/test_listener.cpp
|
caiqingfeng/libmrock
|
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
|
[
"Apache-2.0"
] | 1
|
2015-12-01T04:16:54.000Z
|
2015-12-01T04:16:54.000Z
|
vendor/mysql-connector-c++-1.1.3/test/framework/test_listener.cpp
|
caiqingfeng/libmrock
|
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
|
[
"Apache-2.0"
] | null | null | null |
vendor/mysql-connector-c++-1.1.3/test/framework/test_listener.cpp
|
caiqingfeng/libmrock
|
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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; version 2 of the License.
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.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include "test_listener.h"
#include "test_timer.h"
namespace testsuite
{
TestsListener::TestsListener()
: curSuiteName("n/a")
, curTestName("n/a")
, curTestOrdNum(0)
, executed(0)
, exceptions(0)
, verbose(false)
, timing(false)
{
//TODO: Make StartOptions dependent
outputter.reset(new TAP());
}
void TestsListener::setVerbose(bool verbosity)
{
theInstance().verbose=verbosity;
}
bool TestsListener::doTiming(bool timing)
{
bool preserve= theInstance().timing;
theInstance().timing=timing;
return preserve;
}
//TODO: "set" counterparts
std::ostream & TestsListener::errorsLog()
{
if (theInstance().verbose)
return theInstance().outputter->errorsLog();
else
{
theInstance().devNull.str("");
return theInstance().devNull;
}
}
void TestsListener::errorsLog(const String::value_type * msg)
{
if (msg != NULL)
errorsLog() << msg << std::endl;
}
void TestsListener::errorsLog(const String & msg)
{
errorsLog() << msg << std::endl;
}
void TestsListener::errorsLog(const String::value_type * msg
, const String::value_type * file
, int line)
{
if (msg != NULL)
{
errorsLog() << msg << " File: " << file << " Line: " << line << std::endl;
}
}
std::ostream & TestsListener::messagesLog()
{
if (theInstance().verbose)
return theInstance().outputter->messagesLog();
else
{
theInstance().devNull.str("");
return theInstance().devNull;
}
}
void TestsListener::messagesLog(const String::value_type * msg)
{
if (msg != NULL)
messagesLog() << msg;
}
void TestsListener::messagesLog(const String & msg)
{
if (theInstance().verbose)
messagesLog() << msg;
}
void TestsListener::currentTestName(const String & name)
{
theInstance().curTestName=name;
}
const String & TestsListener::currentSuiteName()
{
return theInstance().curSuiteName;
}
String TestsListener::testFullName()
{
return theInstance().curSuiteName + "::" + theInstance().curTestName;
}
void TestsListener::incrementCounter(int incrVal)
{
theInstance().curTestOrdNum+=incrVal;
}
int TestsListener::recordFailed()
{
failedTests.push_back(curTestOrdNum);
return static_cast<int> (failedTests.size());
}
void TestsListener::nextSuiteStarts(const String & name, int testsNumber)
{
/*
if ( name.length() > 0 )
theInstance().messagesLog()
<< "=============== " << name << " ends. " << "==============="
<< std::endl;*/
theInstance().curSuiteName=name;
/*
theInstance().messagesLog()
<< "=============== " << name << " starts. " << "==============="
<< std::endl;*/
theInstance().outputter->SuiteHeader(name, theInstance().curTestOrdNum + 1
, testsNumber);
}
void TestsListener::testHasStarted()
{
//std::cout << ".";
++theInstance().executed;
theInstance().executionComment= "";
if (theInstance().timing)
{
Timer::startTest(testFullName());
}
}
void TestsListener::testHasFinished(TestRunResult result, const String & msg)
{
static String timingResult("");
if (theInstance().timing)
{
clock_t time=Timer::stopTest(testFullName());
float total = Timer::translate2seconds(time);
static std::stringstream tmp;
tmp.precision(10);
tmp.str("");
tmp << std::showpoint;
tmp << std::endl << "# " << std::setw(40) << std::left << "Total" << " = ";
tmp << std::setw(13) << std::right << total << "s";
tmp << " (100.00%)" << std::endl;
const List & names=Timer::getNames(testFullName());
ConstIterator it=names.begin();
for (; it != names.end(); ++it)
{
time=Timer::getTime(*it);
tmp << "# " << std::setw(38) << std::left << *it;
tmp << " = " << std::setw(13) << std::right << Timer::translate2seconds(time) << "s";
tmp << " (";
tmp << std::setw(6) << std::right;
if (total > 0.0) {
tmp.precision(5);
tmp << ((100 / total) * Timer::translate2seconds(time));
tmp.precision(10);
} else {
tmp << "n/a ";
}
tmp << "%)";
tmp << " (line " << Timer::getLine(*it) << ")" << std::endl;
}
timingResult=tmp.str();
}
else
timingResult="";
if (!msg.empty())
StringUtils::concatSeparated(theInstance().executionComment, msg);
if (!timingResult.empty())
StringUtils::concatSeparated(theInstance().executionComment, timingResult);
if (result != trrPassed)
{
// Output about test fail and recording info
theInstance().recordFailed();
if (result == trrThrown)
++theInstance().exceptions;
theInstance().outputter->TestFailed(theInstance().curTestOrdNum
, theInstance().curTestName
, theInstance().executionComment);
}
else
{
// Output about test success
theInstance().outputter->TestPassed(theInstance().curTestOrdNum
, theInstance().curTestName
, theInstance().executionComment);
}
}
void TestsListener::setTestExecutionComment(const String & msg)
{
theInstance().executionComment= msg;
}
void TestsListener::testHasFailed(const String & msg)
{
setTestExecutionComment(msg);
errorsLog(msg);
throw TestFailedException();
}
void TestsListener::summary()
{
outputter->Summary(executed
, failed() /*+ exceptions - exceptions are already counted in failed()*/
, failedTests);
}
bool TestsListener::allTestsPassed()
{
return theInstance().exceptions && !theInstance().failed() == 0;
}
void TestsListener::bailSuite(const String & reason)
{
static const String bail("BAIL ");
theInstance().outputter->Comment(bail + reason);
}
}
| 24.01049
| 93
| 0.631863
|
caiqingfeng
|
5d65cc6b1abef32c0c8e33f3ea14d46bbc57dc5a
| 3,170
|
cpp
|
C++
|
editor/src/free_camera.cpp
|
trbflxr/xe
|
13123869a848972e064cb8c6838c4215f034f3d9
|
[
"MIT"
] | null | null | null |
editor/src/free_camera.cpp
|
trbflxr/xe
|
13123869a848972e064cb8c6838c4215f034f3d9
|
[
"MIT"
] | null | null | null |
editor/src/free_camera.cpp
|
trbflxr/xe
|
13123869a848972e064cb8c6838c4215f034f3d9
|
[
"MIT"
] | null | null | null |
//
// Created by trbflxr on 3/31/2020.
//
#include "free_camera.hpp"
#include <xe/core/engine.hpp>
namespace xe {
FreeCamera::FreeCamera(const vec2u &resolution, float fovDeg, float aspect, float nearZ, float farZ,
float moveSpeed, float sprintSpeed, float mouseSensitivity) :
camera_(resolution, fovDeg, aspect, nearZ, farZ),
moveSpeed_(moveSpeed),
sprintSpeed_(sprintSpeed),
mouseSensitivity_(mouseSensitivity) {
windowSize_ = Engine::ref().window().size();
windowCenter_ = windowSize_ / 2.0f;
lastMousePosition_ = windowCenter_;
}
void FreeCamera::destroy() {
camera_.destroy();
}
void FreeCamera::onRender() {
camera_.updateUniforms();
}
void FreeCamera::onUpdate() {
auto ts = Engine::ref().delta();
if (mouseLocked_) {
vec2 mouseChange = Engine::getMousePosition() - lastMousePosition_;
//rotate
camera_.transform().rotate(quat(vec3::unitYN(), mouseChange.x * mouseSensitivity_), Transform::Space::Parent);
camera_.transform().rotate(quat(-camera_.transform().localRight(), mouseChange.y * mouseSensitivity_), Transform::Space::Parent);
Engine::executeInRenderThread([this]() {
lastMousePosition_ = Engine::getMousePosition();
Engine::setMousePosition(windowCenter_);
});
//move
float speed = Engine::isKeyPressed(Keyboard::LShift) ? moveSpeed_ * sprintSpeed_ : moveSpeed_;
if (Engine::isKeyPressed(Keyboard::W)) {
camera_.transform().translate(camera_.transform().localForward() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::S)) {
camera_.transform().translate(-camera_.transform().localForward() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::A)) {
camera_.transform().translate(-camera_.transform().localRight() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::D)) {
camera_.transform().translate(camera_.transform().localRight() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::Space)) {
camera_.transform().translate(vec3::unitY() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::LControl)) {
camera_.transform().translate(vec3::unitYN() * speed * ts, Transform::Space::Parent);
}
}
}
bool FreeCamera::onKeyPressed(Event::Key key) {
if (key.code == Keyboard::Escape || key.code == Keyboard::R) {
mouseLocked_ = false;
return true;
}
return false;
}
bool FreeCamera::onMousePressed(Event::MouseButton mb) {
if (mb.button == Mouse::Right) {
mouseLocked_ = !mouseLocked_;
if (mouseLocked_) {
Engine::executeInRenderThread([this]() {
Engine::setMousePosition(windowCenter_);
});
}
Engine::ref().window().setCursorVisible(!mouseLocked_);
return true;
}
return false;
}
bool FreeCamera::onFocusLost() {
mouseLocked_ = false;
Engine::ref().window().setCursorVisible(!mouseLocked_);
return false;
}
}
| 31.386139
| 135
| 0.64511
|
trbflxr
|
5d67ed157395edff6549590a1c433b0315941bea
| 14,999
|
cc
|
C++
|
INET_EC/common/IntervalTree.cc
|
LarryNguyen/ECSim-
|
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
|
[
"Apache-2.0"
] | 12
|
2020-11-30T08:04:23.000Z
|
2022-03-23T11:49:26.000Z
|
Simulation/OMNeT++/inet/src/inet/common/IntervalTree.cc
|
StarStuffSteve/masters-research-project
|
47c1874913d0961508f033ca9a1144850eb8f8b7
|
[
"Apache-2.0"
] | 1
|
2021-01-26T10:49:56.000Z
|
2021-01-31T16:58:52.000Z
|
Simulation/OMNeT++/inet/src/inet/common/IntervalTree.cc
|
StarStuffSteve/masters-research-project
|
47c1874913d0961508f033ca9a1144850eb8f8b7
|
[
"Apache-2.0"
] | 8
|
2021-03-15T02:05:51.000Z
|
2022-03-21T13:14:02.000Z
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** \author Jia Pan */
#include "inet/common/IntervalTree.h"
#include <iostream>
#include <cstdlib>
namespace inet {
IntervalTreeNode::IntervalTreeNode()
{
}
IntervalTreeNode::IntervalTreeNode(const Interval* new_interval) :
stored_interval(new_interval), key(new_interval->low), high(new_interval->high), max_high(high)
{
}
IntervalTreeNode::~IntervalTreeNode()
{
delete stored_interval;
}
IntervalTree::IntervalTree()
{
nil = new IntervalTreeNode;
nil->left = nil->right = nil->parent = nil;
nil->red = false;
nil->key = nil->high = nil->max_high = -SimTime::getMaxTime(); //-std::numeric_limits<double>::max();
nil->stored_interval = nullptr;
root = new IntervalTreeNode;
root->parent = root->left = root->right = nil;
root->key = root->high = root->max_high = SimTime::getMaxTime(); // std::numeric_limits<double>::max();
root->red = false;
root->stored_interval = nullptr;
/// the following are used for the query function
recursion_node_stack_size = 128;
recursion_node_stack = (it_recursion_node*) malloc(recursion_node_stack_size * sizeof(it_recursion_node));
recursion_node_stack_top = 1;
recursion_node_stack[0].start_node = nullptr;
}
IntervalTree::~IntervalTree()
{
IntervalTreeNode* x = root->left;
std::deque<IntervalTreeNode*> nodes_to_free;
if (x != nil)
{
if (x->left != nil)
{
nodes_to_free.push_back(x->left);
}
if (x->right != nil)
{
nodes_to_free.push_back(x->right);
}
delete x;
while (nodes_to_free.size() > 0)
{
x = nodes_to_free.back();
nodes_to_free.pop_back();
if (x->left != nil)
{
nodes_to_free.push_back(x->left);
}
if (x->right != nil)
{
nodes_to_free.push_back(x->right);
}
delete x;
}
}
delete nil;
delete root;
free(recursion_node_stack);
}
void IntervalTree::leftRotate(IntervalTreeNode* x)
{
IntervalTreeNode* y;
y = x->right;
x->right = y->left;
if (y->left != nil)
y->left->parent = x;
y->parent = x->parent;
if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
x->max_high = std::max(x->left->max_high, std::max(x->right->max_high, x->high));
y->max_high = std::max(x->max_high, std::max(y->right->max_high, y->high));
}
void IntervalTree::rightRotate(IntervalTreeNode* y)
{
IntervalTreeNode* x;
x = y->left;
y->left = x->right;
if (nil != x->right)
x->right->parent = y;
x->parent = y->parent;
if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
x->right = y;
y->parent = x;
y->max_high = std::max(y->left->max_high, std::max(y->right->max_high, y->high));
x->max_high = std::max(x->left->max_high, std::max(y->max_high, x->high));
}
/// @brief Inserts z into the tree as if it were a regular binary tree
void IntervalTree::recursiveInsert(IntervalTreeNode* z)
{
IntervalTreeNode* x;
IntervalTreeNode* y;
z->left = z->right = nil;
y = root;
x = root->left;
while (x != nil)
{
y = x;
if (x->key > z->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if ((y == root) || (y->key > z->key))
y->left = z;
else
y->right = z;
}
void IntervalTree::fixupMaxHigh(IntervalTreeNode* x)
{
while (x != root)
{
x->max_high = std::max(x->high, std::max(x->left->max_high, x->right->max_high));
x = x->parent;
}
}
IntervalTreeNode* IntervalTree::insert(const Interval* new_interval)
{
IntervalTreeNode* y;
IntervalTreeNode* x;
IntervalTreeNode* new_node;
x = new IntervalTreeNode(new_interval);
recursiveInsert(x);
fixupMaxHigh(x->parent);
new_node = x;
x->red = true;
while (x->parent->red)
{
/// use sentinel instead of checking for root
if (x->parent == x->parent->parent->left)
{
y = x->parent->parent->right;
if (y->red)
{
x->parent->red = false;
y->red = false;
x->parent->parent->red = true;
x = x->parent->parent;
}
else
{
if (x == x->parent->right)
{
x = x->parent;
leftRotate(x);
}
x->parent->red = false;
x->parent->parent->red = true;
rightRotate(x->parent->parent);
}
}
else
{
y = x->parent->parent->left;
if (y->red)
{
x->parent->red = false;
y->red = false;
x->parent->parent->red = true;
x = x->parent->parent;
}
else
{
if (x == x->parent->left)
{
x = x->parent;
rightRotate(x);
}
x->parent->red = false;
x->parent->parent->red = true;
leftRotate(x->parent->parent);
}
}
}
root->left->red = false;
return new_node;
}
IntervalTreeNode* IntervalTree::getMinimum(IntervalTreeNode *x) const
{
while (x->left != nil)
x = x->left;
return x;
}
IntervalTreeNode* IntervalTree::getMaximum(IntervalTreeNode *x) const
{
while (x->right != nil)
x = x->right;
return x;
}
IntervalTreeNode* IntervalTree::getSuccessor(IntervalTreeNode* x) const
{
IntervalTreeNode* y;
if (nil != x->right)
return getMinimum(x->right);
else
{
y = x->parent;
while (y != nil && x == y->right)
{
x = y;
y = y->parent;
}
return y;
}
}
IntervalTreeNode* IntervalTree::getPredecessor(IntervalTreeNode* x) const
{
IntervalTreeNode* y;
if (nil != x->left)
return getMaximum(x->left);
else
{
y = x->parent;
while (y != nil && x == y->left)
{
x = y;
y = y->parent;
}
return y;
}
}
void IntervalTreeNode::print(IntervalTreeNode* nil, IntervalTreeNode* root) const
{
stored_interval->print();
std::cout << ", k = " << key << ", h = " << high << ", mH = " << max_high;
std::cout << " l->key = ";
if (left == nil)
std::cout << "nullptr";
else
std::cout << left->key;
std::cout << " r->key = ";
if (right == nil)
std::cout << "nullptr";
else
std::cout << right->key;
std::cout << " p->key = ";
if (parent == root)
std::cout << "nullptr";
else
std::cout << parent->key;
std::cout << " red = " << (int) red << std::endl;
}
void IntervalTree::recursivePrint(IntervalTreeNode* x) const
{
if (x != nil)
{
recursivePrint(x->left);
x->print(nil, root);
recursivePrint(x->right);
}
}
void IntervalTree::print() const
{
recursivePrint(root->left);
}
void IntervalTree::deleteFixup(IntervalTreeNode* x)
{
IntervalTreeNode* w;
IntervalTreeNode* root_left_node = root->left;
while ((!x->red) && (root_left_node != x))
{
if (x == x->parent->left)
{
w = x->parent->right;
if (w->red)
{
w->red = false;
x->parent->red = true;
leftRotate(x->parent);
w = x->parent->right;
}
if ((!w->right->red) && (!w->left->red))
{
w->red = true;
x = x->parent;
}
else
{
if (!w->right->red)
{
w->left->red = false;
w->red = true;
rightRotate(w);
w = x->parent->right;
}
w->red = x->parent->red;
x->parent->red = false;
w->right->red = false;
leftRotate(x->parent);
x = root_left_node;
}
}
else
{
w = x->parent->left;
if (w->red)
{
w->red = false;
x->parent->red = true;
rightRotate(x->parent);
w = x->parent->left;
}
if ((!w->right->red) && (!w->left->red))
{
w->red = true;
x = x->parent;
}
else
{
if (!w->left->red)
{
w->right->red = false;
w->red = true;
leftRotate(w);
w = x->parent->left;
}
w->red = x->parent->red;
x->parent->red = false;
w->left->red = false;
rightRotate(x->parent);
x = root_left_node;
}
}
}
x->red = false;
}
void IntervalTree::deleteNode(const Interval* ivl)
{
IntervalTreeNode* node = recursiveSearch(root, ivl);
if (node != nil)
deleteNode(node);
}
IntervalTreeNode* IntervalTree::recursiveSearch(IntervalTreeNode* node, const Interval* ivl) const
{
if (node != nil)
{
if (node->stored_interval == ivl)
return node;
IntervalTreeNode* left = recursiveSearch(node->left, ivl);
if (left != nil)
return left;
IntervalTreeNode* right = recursiveSearch(node->right, ivl);
if (right != nil)
return right;
}
return nil;
}
const Interval* IntervalTree::deleteNode(IntervalTreeNode* z)
{
IntervalTreeNode* y;
IntervalTreeNode* x;
const Interval* node_to_delete = z->stored_interval;
y = ((z->left == nil) || (z->right == nil)) ? z : getSuccessor(z);
x = (y->left == nil) ? y->right : y->left;
if (root == (x->parent = y->parent))
{
root->left = x;
}
else
{
if (y == y->parent->left)
{
y->parent->left = x;
}
else
{
y->parent->right = x;
}
}
/// @brief y should not be nil in this case
/// y is the node to splice out and x is its child
if (y != z)
{
y->max_high = -SimTime::getMaxTime(); // -std::numeric_limits<double>::max();
y->left = z->left;
y->right = z->right;
y->parent = z->parent;
z->left->parent = z->right->parent = y;
if (z == z->parent->left)
z->parent->left = y;
else
z->parent->right = y;
fixupMaxHigh(x->parent);
if (!(y->red))
{
y->red = z->red;
deleteFixup(x);
}
else
y->red = z->red;
delete z;
}
else
{
fixupMaxHigh(x->parent);
if (!(y->red))
deleteFixup(x);
delete y;
}
return node_to_delete;
}
/// @brief returns 1 if the intervals overlap, and 0 otherwise
bool overlap(simtime_t a1, simtime_t a2, simtime_t b1, simtime_t b2)
{
if (a1 <= b1)
{
return (b1 <= a2);
}
else
{
return (a1 <= b2);
}
}
std::deque<const Interval*> IntervalTree::query(simtime_t low, simtime_t high)
{
std::deque<const Interval*> result_stack;
IntervalTreeNode* x = root->left;
bool run = (x != nil);
current_parent = 0;
while (run)
{
if (overlap(low, high, x->key, x->high))
{
result_stack.push_back(x->stored_interval);
recursion_node_stack[current_parent].try_right_branch = true;
}
if (x->left->max_high >= low)
{
if (recursion_node_stack_top == recursion_node_stack_size)
{
recursion_node_stack_size *= 2;
recursion_node_stack = (it_recursion_node *) realloc(recursion_node_stack,
recursion_node_stack_size * sizeof(it_recursion_node));
if (recursion_node_stack == nullptr)
exit(1);
}
recursion_node_stack[recursion_node_stack_top].start_node = x;
recursion_node_stack[recursion_node_stack_top].try_right_branch = false;
recursion_node_stack[recursion_node_stack_top].parent_index = current_parent;
current_parent = recursion_node_stack_top++;
x = x->left;
}
else
x = x->right;
run = (x != nil);
while ((!run) && (recursion_node_stack_top > 1))
{
if (recursion_node_stack[--recursion_node_stack_top].try_right_branch)
{
x = recursion_node_stack[recursion_node_stack_top].start_node->right;
current_parent = recursion_node_stack[recursion_node_stack_top].parent_index;
recursion_node_stack[current_parent].try_right_branch = true;
run = (x != nil);
}
}
}
return result_stack;
}
} // namespace inet
| 26.5
| 110
| 0.521435
|
LarryNguyen
|
5d6caa686364a210fef45b77563ab8c435466a96
| 9,044
|
hpp
|
C++
|
src/shared/charov.hpp
|
gtaisbetterthanfn/modloader
|
18f85c2766d4e052a452c7b1d8f5860a6daac24b
|
[
"MIT"
] | 186
|
2015-01-18T05:46:11.000Z
|
2022-03-22T10:03:44.000Z
|
src/shared/charov.hpp
|
AlisonMDL/modloader
|
18f85c2766d4e052a452c7b1d8f5860a6daac24b
|
[
"MIT"
] | 82
|
2015-01-14T01:02:04.000Z
|
2022-03-20T23:55:59.000Z
|
src/shared/charov.hpp
|
AlisonMDL/modloader
|
18f85c2766d4e052a452c7b1d8f5860a6daac24b
|
[
"MIT"
] | 34
|
2015-01-07T11:17:00.000Z
|
2022-02-28T00:16:20.000Z
|
/*
* Wide char overload for char functions
* (C) 2012 Denilson das Mercês Amorim <dma_2012@hotmail.com>
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef _CHAROV_HPP_
#define _CHAROV_HPP_
#include <cstdio>
#include <cstdarg>
#include <cwchar>
#if defined _WIN32
#if defined __GNUG__
// on MinGW, check if have broken vswprintf
#ifndef _GLIBCXX_HAVE_BROKEN_VSWPRINTF
#define CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#endif
#elif _MSC_VER >= 1400 // MSVC 2005
#define CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#endif
#endif
namespace cwc
{
//=================================== stdio ===================================//
// testing WEOF\EOF
inline bool is_eof(wint_t c)
{
return c == WEOF;
}
inline bool is_eof(wchar_t c)
{
return c == WEOF;
}
inline bool is_eof(int c)
{
return c == EOF;
}
inline bool is_eof(char c)
{
return c == EOF;
}
// printf & scanf //
inline int vfprintf(FILE* stream, const wchar_t* format, va_list arg)
{
return std::vfwprintf(stream, format, arg);
}
// sprintf is broken on windows, sorry for the incovenience
#if !defined(_WIN32) || defined CHAR_OVERLOAD_USE_BROKEN_SPRINTF || defined CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#if !defined(_WIN32) || defined CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#define CHAR_OVERLOAD_SPRINTF_IS_OKAY
#endif
inline int vsnprintf(wchar_t* s, size_t len, const wchar_t* format, va_list arg)
{
#ifdef CHAR_OVERLOAD_SPRINTF_IS_OKAY
return std::vswprintf(s, len, format, arg);
#else
return ::vswprintf(s, format, arg);
#endif
}
inline int vsprintf(wchar_t* s, const wchar_t* format, va_list arg)
{
return vsnprintf(s, -1, format, arg);
}
inline int snprintf(wchar_t* s, size_t n, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vsnprintf(s, n, format, va);
va_end(va);
return x;
}
inline int sprintf(wchar_t* s, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vsprintf(s, format, va);
va_end(va);
return x;
}
//#undef CHAR_OVERLOAD_SPRINTF_IS_OKAY
#endif // sprintf's
inline int vprintf(const wchar_t* format, va_list arg)
{
return std::vwprintf(format, arg);
}
inline int fprintf(FILE* stream, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vfprintf(stream, format, va);
va_end(va);
return x;
}
inline int wprintf(const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vprintf(format, va);
va_end(va);
return x;
}
inline int vfscanf(FILE* stream, const wchar_t* format, va_list arg)
{
return std::vfwscanf(stream, format, arg);
}
inline int vsscanf(const wchar_t* s, const wchar_t* format, va_list arg)
{
return std::vswscanf(s, format, arg);
}
inline int vscanf(const wchar_t* format, va_list arg)
{
return std::vwscanf(format, arg);
}
inline int fscanf(FILE* stream, const wchar_t* format, ... )
{
va_list va; int x; va_start(va, format);
x = vfscanf(stream, format, va);
va_end(va);
return x;
}
inline int sscanf(const wchar_t* s, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vsscanf(s, format, va);
va_end(va);
return x;
}
inline int wscanf(const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vscanf(format, va);
va_end(va);
return x;
}
// (un)(put/get) char //
inline wint_t fgetc(FILE* stream)
{
return std::fgetwc(stream);
}
inline wchar_t* fgets(wchar_t* str, int num, FILE* stream)
{
return std::fgetws(str, num, stream);
}
inline wint_t fputc(wchar_t c, FILE* stream )
{
return std::fputwc(c, stream);
}
inline int fputs(const wchar_t* str, FILE* stream)
{
return std::fputws(str, stream);
}
inline wint_t getc(FILE* stream)
{
return std::getwc(stream);
}
inline wint_t putc(wchar_t c, FILE* stream)
{
return std::putwc(c, stream);
}
inline wint_t putchar(wchar_t c)
{
return std::putwchar(c);
}
inline wint_t ungetc(wint_t c, FILE* stream)
{
return std::ungetwc(c, stream);
}
//=================================== stdlib ===================================//
inline double strtod(const wchar_t* str, wchar_t** endptr)
{
return wcstod(str, endptr);
}
inline float strtof(const wchar_t* str, wchar_t** endptr)
{
return wcstof(str, endptr);
}
inline long double strtold(const wchar_t* str, wchar_t ** endptr)
{
return wcstold(str, endptr);
}
inline long int strtol(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstol(str, endptr, base);
}
inline long long int strtoll(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstoll(str, endptr, base);
}
inline unsigned long int strtoul(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstoul(str, endptr, base);
}
inline unsigned long long int strtoull(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstoull(str, endptr, base);
}
//=================================== time ===================================//
inline size_t strftime(wchar_t* ptr, size_t maxsize, const wchar_t* format, const struct tm* timeptr)
{
return wcsftime(ptr, maxsize, format, timeptr);
}
//=================================== string ===================================//
////////////// this library funcs //////////////////////////
template<class T, class U>
inline T* strcpy(T* dest, const U* src, T replace_invalid_chars = 0)
{
T* p = dest;
do
{
if(*src > 0x7F) *p = replace_invalid_chars;
else *p = *src++;
}
while(*p++);
return dest;
}
template<class T, class U>
inline T* strncpy(T* dest, const U* src, size_t num, T replace_invalid_chars = 0)
{
T* p = dest;
bool found_null = false;
while(num-- != 0)
{
if(found_null)
{
*p = 0;
}
else
{
if(*src > 0x7F) *p = replace_invalid_chars;
else *p = *src++;
if(*p++ == 0) found_null = true;
}
}
return dest;
}
template<class T, class U>
inline size_t strncmp(const T* a, const U* b, size_t num)
{
while(num-- != 0)
{
if(*a != *b) return *a - *b;
else if(*a == 0) return 0;
++a, ++b;
}
return 0;
}
template<class T, class U>
inline size_t strcmp(const T* a, const U* b)
{
return strncmp(a, b, (size_t)(-1));
}
////////////// standard //////////////////////////
inline wchar_t* strcpy(wchar_t* dest, const wchar_t* src)
{
return wcscpy(dest, src);
}
inline size_t strcmp(const wchar_t* a, const wchar_t* b)
{
return wcscmp(a, b);
}
inline wchar_t* strncpy(wchar_t* dest, const wchar_t* src, size_t num)
{
return wcsncpy(dest, src, num);
}
inline size_t strncmp(const wchar_t* a, const wchar_t* b, size_t num)
{
return wcsncmp(a, b, num);
}
inline wchar_t* strcat(wchar_t* destination, const wchar_t* source) // <<
{
return wcscat(destination, source);
}
inline const wchar_t* strchr(const wchar_t* s, wchar_t c)
{
return wcschr(s, c);
}
inline wchar_t* strchr(wchar_t* s, wchar_t c)
{
return wcschr(s, c);
}
inline int strcoll(const wchar_t* str1, const wchar_t* str2)
{
return wcscoll(str1, str2);
}
inline size_t strcspn(const wchar_t* str1, const wchar_t* str2)
{
return wcscspn(str1, str2);
}
inline size_t strlen(const wchar_t* str)
{
return wcslen(str);
}
inline wchar_t* strncat(wchar_t* destination, wchar_t* source, size_t num)
{
return wcsncat(destination, source, num);
}
inline const wchar_t* strpbrk(const wchar_t* str1, const wchar_t* str2)
{
return wcspbrk(str1, str2);
}
inline wchar_t* strpbrk(wchar_t* str1, const wchar_t* str2)
{
return wcspbrk(str1, str2);
}
inline const wchar_t* strrchr(const wchar_t* s, wchar_t c)
{
return wcsrchr(s, c);
}
inline wchar_t* strrchr(wchar_t* s, wchar_t c)
{
return wcsrchr(s, c);
}
inline size_t strspn(const wchar_t* str1, const wchar_t* str2)
{
return wcsspn(str1, str2);
}
inline const wchar_t* strstr(const wchar_t* str1, const wchar_t* str2)
{
return wcsstr(str1, str2);
}
inline wchar_t* strstr(wchar_t* str1, const wchar_t* str2)
{
return wcsstr(str1, str2);
}
inline wchar_t* strtok(wchar_t* str, const wchar_t* delims)
{
#if _MSC_VER < 1900 || defined(_CRT_NON_CONFORMING_WCSTOK) // not VS2015 or [VS2015 and non conforming wcstok]
return wcstok(str, delims);
#else
static wchar_t* context = nullptr;
return wcstok(str, delims, &context);
#endif
}
inline size_t strxfrm(wchar_t* destination, const wchar_t* source, size_t num)
{
return wcsxfrm(destination, source, num);
}
#ifdef _WIN32
inline int stricmp(const wchar_t* a1, const wchar_t* a2)
{
return _wcsicmp(a1, a2);
}
inline int strnicmp(const wchar_t* a1, const wchar_t* a2, size_t num)
{
return _wcsnicmp(a1, a2, num);
}
#endif
//--------------------------------------------------------------------------
// NOT GOING TO OVERLOAD wmemXXX functions, makes non-sense in my mind
//--------------------------------------------------------------------------
} // namespace
#endif // include guard
| 20.232662
| 112
| 0.655573
|
gtaisbetterthanfn
|
5d6f057de6f52fce9b6924a624470a38bbae2955
| 923
|
cpp
|
C++
|
145_postorderTraversal.cpp
|
imxiaobo/leetcode-solutions
|
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
|
[
"MIT"
] | null | null | null |
145_postorderTraversal.cpp
|
imxiaobo/leetcode-solutions
|
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
|
[
"MIT"
] | null | null | null |
145_postorderTraversal.cpp
|
imxiaobo/leetcode-solutions
|
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
stack<std::pair<TreeNode *, int>> stack;
vector<int> postorder;
if (root) {
stack.push(std::make_pair(root, 0));
while (!stack.empty()) {
std::pair<TreeNode *, int> &t = stack.top();
if (!t.first) {
stack.pop();
} else if (t.second == 0) {
++t.second;
stack.push(std::make_pair(t.first->left, 0));
} else if (t.second == 1) {
++t.second;
stack.push(std::make_pair(t.first->right, 0));
} else if (t.second == 2) {
postorder.push_back(t.first->val);
stack.pop();
}
}
}
return postorder;
}
};
| 23.666667
| 59
| 0.510293
|
imxiaobo
|
5d7132399c20435b79d204111ab0de85b6bd163c
| 3,761
|
hpp
|
C++
|
core/src/api/Currency.hpp
|
tmpfork/lib-ledger-core
|
8741e84f38f863fd941d3bd56a470f37eb36da04
|
[
"MIT"
] | null | null | null |
core/src/api/Currency.hpp
|
tmpfork/lib-ledger-core
|
8741e84f38f863fd941d3bd56a470f37eb36da04
|
[
"MIT"
] | null | null | null |
core/src/api/Currency.hpp
|
tmpfork/lib-ledger-core
|
8741e84f38f863fd941d3bd56a470f37eb36da04
|
[
"MIT"
] | null | null | null |
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from currency.djinni
#ifndef DJINNI_GENERATED_CURRENCY_HPP
#define DJINNI_GENERATED_CURRENCY_HPP
#include "../utils/optional.hpp"
#include "BitcoinLikeNetworkParameters.hpp"
#include "CurrencyUnit.hpp"
#include "EthereumLikeNetworkParameters.hpp"
#include "WalletType.hpp"
#include <cstdint>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace ledger { namespace core { namespace api {
/**Structure of cryptocurrency */
struct Currency final {
/**WalletType object defining the type of wallet the currency belongs to */
WalletType walletType;
/**String which represents currency name */
std::string name;
/**
*Integer cointype, part of BIP32 path
*One can refer to https://github.com/satoshilabs/slips/blob/master/slip-0044.md
*/
int32_t bip44CoinType;
/**String representing schemes allowing to send money to a cryptocurrency address (e.g. bitcoin) */
std::string paymentUriScheme;
/**List of CurrencyUnit objects (e.g. BTC, mBTC ...) */
std::vector<CurrencyUnit> units;
/**
*TODO: find a better solution to have only a networkParameters
*Optional BitcoinLikeNetworkParameters, for more details refer to BitcoinLikeNetworkParameters doc
*/
std::experimental::optional<BitcoinLikeNetworkParameters> bitcoinLikeNetworkParameters;
/**Optional EthereumLikeNetworkParameters, for more details refer to EthereumLikeNetworkParameters doc */
std::experimental::optional<EthereumLikeNetworkParameters> ethereumLikeNetworkParameters;
Currency(WalletType walletType_,
std::string name_,
int32_t bip44CoinType_,
std::string paymentUriScheme_,
std::vector<CurrencyUnit> units_,
std::experimental::optional<BitcoinLikeNetworkParameters> bitcoinLikeNetworkParameters_,
std::experimental::optional<EthereumLikeNetworkParameters> ethereumLikeNetworkParameters_)
: walletType(std::move(walletType_))
, name(std::move(name_))
, bip44CoinType(std::move(bip44CoinType_))
, paymentUriScheme(std::move(paymentUriScheme_))
, units(std::move(units_))
, bitcoinLikeNetworkParameters(std::move(bitcoinLikeNetworkParameters_))
, ethereumLikeNetworkParameters(std::move(ethereumLikeNetworkParameters_))
{}
Currency(const Currency& cpy) {
this->walletType = cpy.walletType;
this->name = cpy.name;
this->bip44CoinType = cpy.bip44CoinType;
this->paymentUriScheme = cpy.paymentUriScheme;
this->units = cpy.units;
this->bitcoinLikeNetworkParameters = cpy.bitcoinLikeNetworkParameters;
this->ethereumLikeNetworkParameters = cpy.ethereumLikeNetworkParameters;
}
Currency() = default;
Currency& operator=(const Currency& cpy) {
this->walletType = cpy.walletType;
this->name = cpy.name;
this->bip44CoinType = cpy.bip44CoinType;
this->paymentUriScheme = cpy.paymentUriScheme;
this->units = cpy.units;
this->bitcoinLikeNetworkParameters = cpy.bitcoinLikeNetworkParameters;
this->ethereumLikeNetworkParameters = cpy.ethereumLikeNetworkParameters;
return *this;
}
template <class Archive>
void load(Archive& archive) {
archive(walletType, name, bip44CoinType, paymentUriScheme, units, bitcoinLikeNetworkParameters, ethereumLikeNetworkParameters);
}
template <class Archive>
void save(Archive& archive) const {
archive(walletType, name, bip44CoinType, paymentUriScheme, units, bitcoinLikeNetworkParameters, ethereumLikeNetworkParameters);
}
};
} } } // namespace ledger::core::api
#endif //DJINNI_GENERATED_CURRENCY_HPP
| 39.177083
| 135
| 0.727998
|
tmpfork
|
5d74b13656ffaa4a8a9ab331222acd315f1826fd
| 2,901
|
hpp
|
C++
|
include/codegen/include/GlobalNamespace/OVRInput_OVRControllerTouchpad.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/GlobalNamespace/OVRInput_OVRControllerTouchpad.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/GlobalNamespace/OVRInput_OVRControllerTouchpad.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: OVRInput
#include "GlobalNamespace/OVRInput.hpp"
// Including type: OVRInput/OVRControllerBase
#include "GlobalNamespace/OVRInput_OVRControllerBase.hpp"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: OVRInput/OVRControllerTouchpad
class OVRInput::OVRControllerTouchpad : public GlobalNamespace::OVRInput::OVRControllerBase {
public:
// private OVRPlugin/Vector2f moveAmount
// Offset: 0x104
GlobalNamespace::OVRPlugin::Vector2f moveAmount;
// private System.Single maxTapMagnitude
// Offset: 0x10C
float maxTapMagnitude;
// private System.Single minMoveMagnitude
// Offset: 0x110
float minMoveMagnitude;
// public System.Void .ctor()
// Offset: 0xE71180
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::.ctor()
// Base method: System.Void Object::.ctor()
static OVRInput::OVRControllerTouchpad* New_ctor();
// public override OVRInput/Controller Update()
// Offset: 0xE7A194
// Implemented from: OVRInput/OVRControllerBase
// Base method: OVRInput/Controller OVRControllerBase::Update()
GlobalNamespace::OVRInput::Controller Update();
// public override System.Void ConfigureButtonMap()
// Offset: 0xE7A350
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureButtonMap()
void ConfigureButtonMap();
// public override System.Void ConfigureTouchMap()
// Offset: 0xE7A524
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureTouchMap()
void ConfigureTouchMap();
// public override System.Void ConfigureNearTouchMap()
// Offset: 0xE7A5DC
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureNearTouchMap()
void ConfigureNearTouchMap();
// public override System.Void ConfigureAxis1DMap()
// Offset: 0xE7A62C
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureAxis1DMap()
void ConfigureAxis1DMap();
// public override System.Void ConfigureAxis2DMap()
// Offset: 0xE7A67C
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureAxis2DMap()
void ConfigureAxis2DMap();
}; // OVRInput/OVRControllerTouchpad
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRInput::OVRControllerTouchpad*, "", "OVRInput/OVRControllerTouchpad");
#pragma pack(pop)
| 42.661765
| 112
| 0.728025
|
Futuremappermydud
|
5d850acb324df49c7a3df716382af314f38f2025
| 285
|
cpp
|
C++
|
solutions/1198.find-smallest-common-element-in-all-rows.326220064.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 78
|
2020-10-22T11:31:53.000Z
|
2022-02-22T13:27:49.000Z
|
solutions/1198.find-smallest-common-element-in-all-rows.326220064.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | null | null | null |
solutions/1198.find-smallest-common-element-in-all-rows.326220064.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 26
|
2020-10-23T15:10:44.000Z
|
2021-11-07T16:13:50.000Z
|
class Solution {
public:
int smallestCommonElement(vector<vector<int>> &mat) {
int m[10001] = {};
for (auto j = 0; j < mat[0].size(); ++j)
for (auto i = 0; i < mat.size(); ++i)
if (++m[mat[i][j]] == mat.size())
return mat[i][j];
return -1;
}
};
| 23.75
| 55
| 0.491228
|
satu0king
|
5d850af6a4b8948f669234ddabaaf6e29b7f4058
| 1,134
|
cpp
|
C++
|
PokemanSafari_M1/Character.cpp
|
ilanisakov/RailShooter
|
612945b96b37989927b99f50ffa96e2fe7e22e21
|
[
"MIT"
] | null | null | null |
PokemanSafari_M1/Character.cpp
|
ilanisakov/RailShooter
|
612945b96b37989927b99f50ffa96e2fe7e22e21
|
[
"MIT"
] | null | null | null |
PokemanSafari_M1/Character.cpp
|
ilanisakov/RailShooter
|
612945b96b37989927b99f50ffa96e2fe7e22e21
|
[
"MIT"
] | null | null | null |
/////////////////////////////////////////////////////////////////////
// File: Character.cpp
// DSA2 PokemanSafari_M1
// Authors:
// Ilan Isakov
// Marty Kurtz
// Mary Spencer
//
// Description:
//
/////////////////////////////////////////////////////////////////////
#include "Character.h"
/////////////////////////////////////////////////////////////////////
// Constructor
/////////////////////////////////////////////////////////////////////
Character::Character(CHARACTER_TYPE type, String name,
std::vector<vector3> VectorList,
std::vector<vector3> movementPath) :
MyBoundingObjectClass(VectorList, name)
{
this->path = movementPath; // path for the character
this->charType = type;
this->currentSeg = 0; //current line segment of the track
}
/////////////////////////////////////////////////////////////////
// Render()
/////////////////////////////////////////////////////////////////
void Character::UpdateRender()
{
}
/////////////////////////////////////////////////////////////////
// UpdateLocation()
/////////////////////////////////////////////////////////////////
void Character::UpdateLocation(){
}
| 28.35
| 69
| 0.368607
|
ilanisakov
|
5d872b50248f3d7876c6910e699d896450e89eb2
| 244
|
cpp
|
C++
|
examples/physics/cmsToyGV/TBBProcessingDemo/TBBTestModules/busy_wait_scale_factor.cpp
|
Geant-RnD/geant
|
ffff95e23547531f3254ada2857c062a31f33e8f
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2016-10-16T14:37:42.000Z
|
2018-04-05T15:49:09.000Z
|
examples/physics/cmsToyGV/TBBProcessingDemo/TBBTestModules/busy_wait_scale_factor.cpp
|
Geant-RnD/geant
|
ffff95e23547531f3254ada2857c062a31f33e8f
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
examples/physics/cmsToyGV/TBBProcessingDemo/TBBTestModules/busy_wait_scale_factor.cpp
|
Geant-RnD/geant
|
ffff95e23547531f3254ada2857c062a31f33e8f
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
//
// busy_wait_scale_factor.cpp
// DispatchProcessingDemo
//
// Created by Chris Jones on 10/3/11.
// Copyright 2011 FNAL. All rights reserved.
//
#include "busy_wait_scale_factor.h"
double busy_wait_scale_factor = 2.2e+07; //counts/sec
| 20.333333
| 53
| 0.733607
|
Geant-RnD
|
5d8e06c6d5a7671d4c9bd59fce419b4a8e2aa8c4
| 11,187
|
cp
|
C++
|
Linux/Sources/Application/Calendar/Component_Editing/CNewToDoDialog.cp
|
mbert/mulberry-main
|
6b7951a3ca56e01a7be67aa12e55bfeafc63950d
|
[
"ECL-2.0",
"Apache-2.0"
] | 12
|
2015-04-21T16:10:43.000Z
|
2021-11-05T13:41:46.000Z
|
Linux/Sources/Application/Calendar/Component_Editing/CNewToDoDialog.cp
|
SpareSimian/mulberry-main
|
e868f3f4d86efae3351000818a3cb2d72ae5eac3
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2015-11-02T13:32:11.000Z
|
2019-07-10T21:11:21.000Z
|
Linux/Sources/Application/Calendar/Component_Editing/CNewToDoDialog.cp
|
SpareSimian/mulberry-main
|
e868f3f4d86efae3351000818a3cb2d72ae5eac3
|
[
"ECL-2.0",
"Apache-2.0"
] | 6
|
2015-01-12T08:49:12.000Z
|
2021-03-27T09:11:10.000Z
|
/*
Copyright (c) 2007-2011 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "CNewToDoDialog.h"
#include "CICalendar.h"
#include "CICalendarManager.h"
#include "CCalendarPopup.h"
#include "CCalendarView.h"
#include "CDateTimeZoneSelect.h"
#include "CErrorDialog.h"
#include "CMulberryApp.h"
#include "CNewComponentAlarm.h"
#include "CNewComponentAttendees.h"
#include "CNewComponentDetails.h"
#include "CNewComponentRepeat.h"
#include "CPreferences.h"
#include "CTabController.h"
#include "CTextField.h"
#include "CWindowsMenu.h"
#include "CXStringResources.h"
#include "CCalendarStoreManager.h"
#include "CICalendarLocale.h"
#include "CITIPProcessor.h"
#include "TPopupMenu.h"
#include <JXTextButton.h>
#include <JXTextCheckbox.h>
#include <JXUpRect.h>
#include <JXWindow.h>
#include <jXGlobals.h>
#include <cassert>
// ---------------------------------------------------------------------------
// CNewToDoDialog [public]
/**
Default constructor */
CNewToDoDialog::CNewToDoDialog(JXDirector* supervisor)
: CNewComponentDialog(supervisor)
{
}
// ---------------------------------------------------------------------------
// ~CNewToDoDialog [public]
/**
Destructor */
CNewToDoDialog::~CNewToDoDialog()
{
}
#pragma mark -
void CNewToDoDialog::OnCreate()
{
// Get UI items
CNewComponentDialog::OnCreate();
// begin JXLayout1
mCompleted =
new JXTextCheckbox("Completed", mContainer,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 5,40, 90,20);
assert( mCompleted != NULL );
mCompletedDateTimeZone =
new CDateTimeZoneSelect(mContainer,
JXWidget::kHElastic, JXWidget::kVElastic, 94,35, 400,30);
assert( mCompletedDateTimeZone != NULL );
mCompletedNow =
new JXTextButton("Now", mContainer,
JXWidget::kHElastic, JXWidget::kVElastic, 495,40, 35,20);
assert( mCompletedNow != NULL );
mCompletedNow->SetFontSize(10);
// end JXLayout1
ListenTo(mCompleted);
ListenTo(mCompletedNow);
}
void CNewToDoDialog::InitPanels()
{
// Load each panel for the tabs
mPanels.push_back(new CNewComponentDetails(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Details");
mPanels.push_back(new CNewComponentRepeat(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Repeat");
mPanels.push_back(new CNewComponentAlarm(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Alarms");
mPanels.push_back(new CNewComponentAttendees(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Attendees");
}
void CNewToDoDialog::ListenTo_Message(long msg, void* param)
{
switch(msg)
{
case iCal::CICalendar::eBroadcast_Closed:
// Force dialog to close immediately as event is about to be deleted.
// Any changes so far will be lost.
OnCancel();
break;
default:;
}
}
// Handle controls
void CNewToDoDialog::Receive(JBroadcaster* sender, const Message& message)
{
if (message.Is(JXTextButton::kPushed))
{
if (sender == mCompletedNow)
{
DoNow();
return;
}
}
else if (message.Is(JXCheckbox::kPushed))
{
if (sender == mCompleted)
{
DoCompleted(mCompleted->IsChecked());
return;
}
}
CNewComponentDialog::Receive(sender, message);
}
void CNewToDoDialog::DoCompleted(bool set)
{
if (set && !mCompletedExists)
{
mActualCompleted.SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
mActualCompleted.SetNow();
mCompletedExists = true;
mCompletedDateTimeZone->SetDateTimeZone(mActualCompleted, false);
}
mCompletedDateTimeZone->SetVisible(set);
mCompletedNow->SetVisible(set);
}
void CNewToDoDialog::DoNow()
{
mActualCompleted.SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
mActualCompleted.SetNow();
mCompletedDateTimeZone->SetDateTimeZone(mActualCompleted, false);
}
void CNewToDoDialog::SetComponent(iCal::CICalendarComponentRecur& vcomponent, const iCal::CICalendarComponentExpanded* expanded)
{
CNewComponentDialog::SetComponent(vcomponent, expanded);
mCompletedExists = static_cast<iCal::CICalendarVToDo&>(vcomponent).HasCompleted();
mCompleted->SetState(mCompletedExists || (static_cast<iCal::CICalendarVToDo&>(vcomponent).GetStatus() == iCal::eStatus_VToDo_Completed));
if (mCompletedExists)
{
// COMPLETED is in UTC but we adjust to local timezone
mActualCompleted = static_cast<iCal::CICalendarVToDo&>(vcomponent).GetCompleted();
mActualCompleted.AdjustTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
mCompletedDateTimeZone->SetDateTimeZone(mActualCompleted, false);
}
DoCompleted(static_cast<iCal::CICalendarVToDo&>(vcomponent).GetStatus() == iCal::eStatus_VToDo_Completed);
}
void CNewToDoDialog::GetComponent(iCal::CICalendarComponentRecur& vcomponent)
{
CNewComponentDialog::GetComponent(vcomponent);
static_cast<iCal::CICalendarVToDo&>(vcomponent).EditStatus(mCompleted->IsChecked() ? iCal::eStatus_VToDo_Completed : iCal::eStatus_VToDo_NeedsAction);
// Changed completed date if needed
mCompletedDateTimeZone->GetDateTimeZone(mActualCompleted, false);
if (mCompleted->IsChecked() && (static_cast<iCal::CICalendarVToDo&>(vcomponent).GetCompleted() != mActualCompleted))
{
// Adjust to UTC and then change
mActualCompleted.AdjustToUTC();
static_cast<iCal::CICalendarVToDo&>(vcomponent).EditCompleted(mActualCompleted);
}
}
void CNewToDoDialog::SetReadOnly(bool read_only)
{
CNewComponentDialog::SetReadOnly(read_only);
mCompleted->SetActive(!mReadOnly);
mCompletedDateTimeZone->SetActive(!mReadOnly);
mCompletedNow->SetActive(!mReadOnly);
}
void CNewToDoDialog::ChangedMyStatus(const iCal::CICalendarProperty& attendee, const cdstring& new_status)
{
static_cast<CNewComponentAttendees*>(mPanels.back())->ChangedMyStatus(attendee, new_status);
}
bool CNewToDoDialog::DoNewOK()
{
// Check and get new calendar if different
iCal::CICalendarRef newcal;
iCal::CICalendar* new_cal = NULL;
if (!GetCalendar(0, newcal, new_cal))
// Return to dialog
return false;
// Get updated info
GetComponent(*mComponent);
// Look for change to calendar
if (newcal != mComponent->GetCalendar())
{
// Use new calendar
mComponent->SetCalendar(newcal);
// Set the default calendar for next time
const calstore::CCalendarStoreNode* node = calstore::CCalendarStoreManager::sCalendarStoreManager->GetNode(new_cal);
if (node != NULL)
CPreferences::sPrefs->mDefaultCalendar.SetValue(node->GetAccountName());
}
// Add to calendar (this will do the display update)
//iCal::CICalendar* cal = iCal::CICalendar::GetICalendar(mVToDo->GetCalendar());
new_cal->AddNewVToDo(static_cast<iCal::CICalendarVToDo*>(mComponent));
CCalendarView::ToDosChangedAll();
return true;
}
bool CNewToDoDialog::DoEditOK()
{
// Find the original calendar if it still exists
iCal::CICalendarRef oldcal = mComponent->GetCalendar();
iCal::CICalendar* old_cal = iCal::CICalendar::GetICalendar(oldcal);
if (old_cal == NULL)
{
// Inform user of missing calendar
CErrorDialog::StopAlert(rsrc::GetString("CNewToDoDialog::MissingOriginal"));
// Disable OK button
mOKBtn->SetActive(false);
return false;
}
// Find the original to do if it still exists
iCal::CICalendarVToDo* original = static_cast<iCal::CICalendarVToDo*>(old_cal->FindComponent(mComponent));
if (original == NULL)
{
// Inform user of missing calendar
CErrorDialog::StopAlert(rsrc::GetString("CNewToDoDialog::MissingOriginal"));
// Disable OK button and return to dialog
mOKBtn->SetActive(false);
return false;
}
// Check and get new calendar if different
iCal::CICalendarRef newcal;
iCal::CICalendar* new_cal = NULL;
if (!GetCalendar(oldcal, newcal, new_cal))
// Return to dialog
return false;
// Get updated info
GetComponent(*original);
// Look for change to calendar
if (new_cal != NULL)
{
// Remove from old calendar (without deleting)
old_cal->RemoveVToDo(original, false);
// Add to new calendar (without initialising)
original->SetCalendar(newcal);
new_cal->AddNewVToDo(original, true);
}
// Tell it it has changed (i.e. bump sequence, dirty calendar)
original->Changed();
CCalendarView::ToDosChangedAll();
return true;
}
void CNewToDoDialog::DoCancel()
{
// Delete the to do which we own and is not going to be used
delete mComponent;
mComponent = NULL;
}
void CNewToDoDialog::StartNew(const iCal::CICalendar* calin)
{
const iCal::CICalendarList& cals = calstore::CCalendarStoreManager::sCalendarStoreManager->GetActiveCalendars();
if (cals.size() == 0)
return;
const iCal::CICalendar* cal = calin;
if (cal == NULL)
{
// Default calendar is the first one
cal = cals.front();
// Check prefs for default calendar
const calstore::CCalendarStoreNode* node = calstore::CCalendarStoreManager::sCalendarStoreManager->GetNode(CPreferences::sPrefs->mDefaultCalendar.GetValue());
if ((node != NULL) && (node->GetCalendar() != NULL))
cal = node->GetCalendar();
}
// Start with an empty to do
iCal::CICalendarVToDo* vtodo = static_cast<iCal::CICalendarVToDo*>(iCal::CICalendarVToDo::Create(cal->GetRef()));
// Set event with initial timing
vtodo->EditTiming();
StartModeless(*vtodo, NULL, CNewToDoDialog::eNew);
}
void CNewToDoDialog::StartEdit(const iCal::CICalendarVToDo& original, const iCal::CICalendarComponentExpanded* expanded)
{
// Look for an existinf dialog for this event
for(std::set<CNewComponentDialog*>::const_iterator iter = sDialogs.begin(); iter != sDialogs.end(); iter++)
{
if ((*iter)->ContainsComponent(original))
{
(*iter)->GetWindow()->Raise();
return;
}
}
// Use a copy of the event
iCal::CICalendarVToDo* vtodo = new iCal::CICalendarVToDo(original);
StartModeless(*vtodo, expanded, CNewToDoDialog::eEdit);
}
void CNewToDoDialog::StartDuplicate(const iCal::CICalendarVToDo& original)
{
// Start with an empty new event
iCal::CICalendarVToDo* vtodo = new iCal::CICalendarVToDo(original);
vtodo->Duplicated();
StartModeless(*vtodo, NULL, CNewToDoDialog::eDuplicate);
}
void CNewToDoDialog::StartModeless(iCal::CICalendarVToDo& vtodo, const iCal::CICalendarComponentExpanded* expanded, EModelessAction action)
{
CNewToDoDialog* dlog = new CNewToDoDialog(JXGetApplication());
dlog->OnCreate();
dlog->SetAction(action);
dlog->SetComponent(vtodo, expanded);
dlog->Activate();
}
| 29.208877
| 160
| 0.729061
|
mbert
|
5d92bbd820187dea53283279f100927a6d8aeca3
| 969
|
cpp
|
C++
|
mogupro/game/src/Sound/cSE.cpp
|
desspert/mogupro
|
ac39f5ec3fb670cf5044ef501951270d7d92a748
|
[
"MIT"
] | null | null | null |
mogupro/game/src/Sound/cSE.cpp
|
desspert/mogupro
|
ac39f5ec3fb670cf5044ef501951270d7d92a748
|
[
"MIT"
] | null | null | null |
mogupro/game/src/Sound/cSE.cpp
|
desspert/mogupro
|
ac39f5ec3fb670cf5044ef501951270d7d92a748
|
[
"MIT"
] | null | null | null |
#include <Sound/cSE.h>
#include <cinder/app/App.h>
namespace Sound
{
using namespace cinder;
cSE::cSE( std::string const& assetsSePath )
{
auto ctx = audio::master( );
ctx->enable( );
mGainRef = ctx->makeNode( new audio::GainNode( 1.0F ) );
mBufferPlayerRef = ctx->makeNode( new audio::BufferPlayerNode( ) );
mBufferPlayerRef->loadBuffer( audio::load( app::loadAsset( assetsSePath ) ) );
mBufferPlayerRef >> mGainRef >> ctx->getOutput( );
};
cSE::~cSE( )
{
stop( );
}
void cSE::play( )
{
mBufferPlayerRef->start( );
}
void cSE::stop( )
{
mBufferPlayerRef->stop( );
}
bool cSE::isPlaying( )
{
return mBufferPlayerRef->isEnabled( );
}
bool cSE::isLooping( )
{
return mBufferPlayerRef->isLoopEnabled( );
}
void cSE::setLooping( const bool islooping )
{
mBufferPlayerRef->setLoopEnabled( islooping );
}
void cSE::setGain( const float gain )
{
mGainRef->setValue( gain );
}
;
}
| 21.533333
| 83
| 0.625387
|
desspert
|
5d93a684b854063b4df7b8fedd29f58eeb77cecc
| 10,716
|
cc
|
C++
|
targets/ARCH/ETHERNET/oran/5g/oran.cc
|
Ting-An-Lin/OAI_ORAN_FHI_integration
|
0671d428ce5ad5d6040b393c90679d59c074bd2d
|
[
"Apache-2.0"
] | 1
|
2021-12-14T12:07:10.000Z
|
2021-12-14T12:07:10.000Z
|
targets/ARCH/ETHERNET/oran/5g/oran.cc
|
Ting-An-Lin/OAI_ORAN_FHI_integration
|
0671d428ce5ad5d6040b393c90679d59c074bd2d
|
[
"Apache-2.0"
] | null | null | null |
targets/ARCH/ETHERNET/oran/5g/oran.cc
|
Ting-An-Lin/OAI_ORAN_FHI_integration
|
0671d428ce5ad5d6040b393c90679d59c074bd2d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (the "License"); you may not use this file
* except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.openairinterface.org/?page_id=698
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
#include <stdio.h>
#include "common_lib.h"
#include "ethernet_lib.h"
#include "shared_buffers.h"
#include "openair1/PHY/defs_nr_common.h"
#include "xran_lib_wrap.hpp"
typedef struct {
eth_state_t e;
shared_buffers buffers;
rru_config_msg_type_t last_msg;
int capabilities_sent;
void *oran_priv;
} oran_eth_state_t;
char *msg_type(int t)
{
static char *s[12] = {
"RAU_tick",
"RRU_capabilities",
"RRU_config",
"RRU_config_ok",
"RRU_start",
"RRU_stop",
"RRU_sync_ok",
"RRU_frame_resynch",
"RRU_MSG_max_num",
"RRU_check_sync",
"RRU_config_update",
"RRU_config_update_ok",
};
if (t < 0 || t > 11) return "UNKNOWN";
return s[t];
}
void xran_fh_rx_callback(void *pCallbackTag, xran_status_t status){
rte_pause();
}
void xran_fh_srs_callback(void *pCallbackTag, xran_status_t status){
rte_pause();
}
void xran_fh_rx_prach_callback(void *pCallbackTag, xran_status_t status){
rte_pause();
}
int trx_oran_start(openair0_device *device)
{
xranLibWraper *xranlib;
xranlib = new xranLibWraper;
if(xranlib->SetUp() < 0) {
return (-1);
}
xranlib->Init();
xranlib->Open(nullptr,
nullptr,
(void *)xran_fh_rx_callback,
(void *)xran_fh_rx_prach_callback,
(void *)xran_fh_srs_callback);
xranlib->Start();
printf("ORAN 5G: %s\n", __FUNCTION__);
return 0;
}
void trx_oran_end(openair0_device *device)
{
printf("ORAN: %s\n", __FUNCTION__);
}
int trx_oran_stop(openair0_device *device)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_set_freq(openair0_device* device,
openair0_config_t *openair0_cfg,
int exmimo_dump_config)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_set_gains(openair0_device* device,
openair0_config_t *openair0_cfg)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_get_stats(openair0_device* device)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_reset_stats(openair0_device* device)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int ethernet_tune(openair0_device *device,
unsigned int option,
int value)
{
printf("ORAN: %s\n", __FUNCTION__);
return 0;
}
int trx_oran_write_raw(openair0_device *device,
openair0_timestamp timestamp,
void **buff, int nsamps, int cc, int flags)
{
printf("ORAN: %s\n", __FUNCTION__);
return nsamps*4;
}
int trx_oran_read_raw(openair0_device *device,
openair0_timestamp *timestamp,
void **buff, int nsamps, int cc)
{
printf("ORAN: %s\n", __FUNCTION__);
return nsamps*4;
}
int trx_oran_ctlsend(openair0_device *device, void *msg, ssize_t msg_len)
{
RRU_CONFIG_msg_t *rru_config_msg = msg;
oran_eth_state_t *s = device->priv;
printf("ORAN 5G: %s\n", __FUNCTION__);
printf(" rru_config_msg->type %d [%s]\n", rru_config_msg->type,
msg_type(rru_config_msg->type));
s->last_msg = rru_config_msg->type;
return msg_len;
}
int trx_oran_ctlrecv(openair0_device *device, void *msg, ssize_t msg_len)
{
RRU_CONFIG_msg_t *rru_config_msg = msg;
oran_eth_state_t *s = device->priv;
printf("ORAN 5G: %s\n", __FUNCTION__);
if (s->last_msg == RAU_tick && s->capabilities_sent == 0) {
RRU_capabilities_t *cap;
rru_config_msg->type = RRU_capabilities;
rru_config_msg->len = sizeof(RRU_CONFIG_msg_t)-MAX_RRU_CONFIG_SIZE+sizeof(RRU_capabilities_t);
cap = (RRU_capabilities_t*)&rru_config_msg->msg[0];
cap->FH_fmt = ORAN_only;
cap->num_bands = 1;
cap->band_list[0] = 78;
cap->nb_rx[0] = 1;
cap->nb_tx[0] = 1;
cap->max_pdschReferenceSignalPower[0] = -27;
cap->max_rxgain[0] = 90;
s->capabilities_sent = 1;
return rru_config_msg->len;
}
// if (s->last_msg == RRU_config) {
// rru_config_msg->type = RRU_config_ok;
// return 0;
// }
printf("--------------- rru_config_msg->type %d [%s]\n", rru_config_msg->type,
msg_type(rru_config_msg->type));
if (s->last_msg == RRU_config) {
rru_config_msg->type = RRU_config_ok;
printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
s->oran_priv = oran_start(s->e.if_name, &s->buffers);
}
return 0;
}
/*This function reads the IQ samples from OAI, symbol by symbol.
It also handles the shared buffers. */
void oran_fh_if4p5_south_in(RU_t *ru,
int *frame,
int *slot)
{
oran_eth_state_t *s = ru->ifdevice.priv;
NR_DL_FRAME_PARMS *fp;
int symbol;
int32_t *rxdata;
int antenna = 0;
printf("Ann in oran.c: nr_oran_fh_if4p5_south_in\n");
lock_ul_buffers(&s->buffers, *slot);
next:
while (!(s->buffers.ul_busy[*slot] == 0x3fff ||
s->buffers.prach_busy[*slot] == 1))
wait_buffers(&s->buffers, *slot);
if (s->buffers.prach_busy[*slot] == 1) {
int i;
int antenna = 0;
uint16_t *in;
uint16_t *out;
in = (uint16_t *)s->buffers.prach[*slot];
out = (uint16_t *)ru->prach_rxsigF[antenna];
for (i = 0; i < 849; i++)
out[i] = ntohs(in[i]);
s->buffers.prach_busy[*slot] = 0;
ru->wakeup_prach_gNB(ru->gNB_list[0], ru, *frame, *slot);
goto next;
}
fp = ru->nr_frame_parms;
for (symbol = 0; symbol < 14; symbol++) {
int i;
uint16_t *p = (uint16_t *)(&s->buffers.ul[*slot][symbol*1272*4]);
for (i = 0; i < 1272*2; i++) {
p[i] = htons(p[i]);
}
rxdata = &ru->common.rxdataF[antenna][symbol * fp->ofdm_symbol_size];
#if 1
memcpy(rxdata + 2048 - 1272/2,
&s->buffers.ul[*slot][symbol*1272*4],
(1272/2) * 4);
memcpy(rxdata,
&s->buffers.ul[*slot][symbol*1272*4] + (1272/2)*4,
(1272/2) * 4);
#endif
}
s->buffers.ul_busy[*slot] = 0;
signal_buffers(&s->buffers, *slot);
unlock_buffers(&s->buffers, *slot);
//printf("ORAN: %s (f.sf %d.%d)\n", __FUNCTION__, *frame, *subframe);
RU_proc_t *proc = &ru->proc;
extern uint16_t sl_ahead;
int f = *frame;
int sl = *slot;
//calculate timestamp_rx, timestamp_tx based on frame and subframe
proc->tti_rx = sl;
proc->frame_rx = f;
proc->timestamp_rx = ((proc->frame_rx * 20) + proc->tti_rx ) * fp->samples_per_tti ;
if (get_nprocs()<=4) {
proc->tti_tx = (sl+sl_ahead)%20;
proc->frame_tx = (sl>(19-sl_ahead)) ? (f+1)&1023 : f;
}
}
void oran_fh_if4p5_south_out(RU_t *ru,
int frame,
int slot,
uint64_t timestamp)
{
oran_eth_state_t *s = ru->ifdevice.priv;
NR_DL_FRAME_PARMS *fp;
int symbol;
int32_t *txdata;
int aa = 0;
printf("Ann in oran.c: oran_fh_if4p5_south_out\n");
//printf("ORAN: %s (f.sf %d.%d ts %ld)\n", __FUNCTION__, frame, subframe, timestamp);
lock_dl_buffers(&s->buffers, slot);
fp = ru->nr_frame_parms;
if (ru->num_gNB != 1 || ru->nb_tx != 1 || fp->ofdm_symbol_size != 2048 ||
fp->Ncp != NORMAL || fp->symbols_per_slot != 14) {
printf("%s:%d:%s: unsupported configuration\n",
__FILE__, __LINE__, __FUNCTION__);
exit(1);
}
for (symbol = 0; symbol < 14; symbol++) {
txdata = &ru->common.txdataF_BF[aa][symbol * fp->ofdm_symbol_size];
#if 1
memcpy(&s->buffers.dl[slot][symbol*1272*4],
txdata + 2048 - (1272/2),
(1272/2) * 4);
memcpy(&s->buffers.dl[slot][symbol*1272*4] + (1272/2)*4,
txdata + 1,
(1272/2) * 4);
#endif
int i;
uint16_t *p = (uint16_t *)(&s->buffers.dl[slot][symbol*1272*4]);
for (i = 0; i < 1272*2; i++) {
p[i] = htons(p[i]);
}
}
s->buffers.dl_busy[slot] = 0x3fff;
unlock_buffers(&s->buffers, slot);
}
void *get_internal_parameter(char *name)
{
printf("BENETEL 5G: %s\n", __FUNCTION__);
if (!strcmp(name, "fh_if4p5_south_in"))
return oran_fh_if4p5_south_in;
if (!strcmp(name, "fh_if4p5_south_out"))
return oran_fh_if4p5_south_out;
return NULL;
}
__attribute__((__visibility__("default")))
int transport_init(openair0_device *device,
openair0_config_t *openair0_cfg,
eth_params_t * eth_params )
{
oran_eth_state_t *eth;
printf("Ann: ORANNNi 5g\n");
printf("ORAN 5g: %s\n", __FUNCTION__);
device->Mod_id = 0;
device->transp_type = ETHERNET_TP;
device->trx_start_func = trx_oran_start;
device->trx_get_stats_func = trx_oran_get_stats;
device->trx_reset_stats_func = trx_oran_reset_stats;
device->trx_end_func = trx_oran_end;
device->trx_stop_func = trx_oran_stop;
device->trx_set_freq_func = trx_oran_set_freq;
device->trx_set_gains_func = trx_oran_set_gains;
device->trx_write_func = trx_oran_write_raw;
device->trx_read_func = trx_oran_read_raw;
device->trx_ctlsend_func = trx_oran_ctlsend;
device->trx_ctlrecv_func = trx_oran_ctlrecv;
device->get_internal_parameter = get_internal_parameter;
eth = calloc(1, sizeof(oran_eth_state_t));
if (eth == NULL) {
AssertFatal(0==1, "out of memory\n");
}
eth->e.flags = ETH_RAW_IF4p5_MODE;
eth->e.compression = NO_COMPRESS;
eth->e.if_name = eth_params->local_if_name;
device->priv = eth;
device->openair0_cfg=&openair0_cfg[0];
eth->last_msg = -1;
init_buffers(ð->buffers);
return 0;
}
| 25.946731
| 99
| 0.616461
|
Ting-An-Lin
|
5d94c25e1c854ddf57fa85a8230f66057227d78c
| 3,215
|
cc
|
C++
|
Engine/spcOpenGL/gl4/gl4texturecube.cc
|
marcellfischbach/SpiceEngine
|
e25e1e4145b7afaea9179bb8e33e4d184bd407c4
|
[
"BSD-3-Clause"
] | null | null | null |
Engine/spcOpenGL/gl4/gl4texturecube.cc
|
marcellfischbach/SpiceEngine
|
e25e1e4145b7afaea9179bb8e33e4d184bd407c4
|
[
"BSD-3-Clause"
] | 1
|
2021-09-09T12:51:56.000Z
|
2021-09-09T12:51:56.000Z
|
Engine/spcOpenGL/gl4/gl4texturecube.cc
|
marcellfischbach/SpiceEngine
|
e25e1e4145b7afaea9179bb8e33e4d184bd407c4
|
[
"BSD-3-Clause"
] | null | null | null |
#include <spcOpenGL/gl4/gl4texturecube.hh>
#include <spcOpenGL/gl4/gl4pixelformatmap.hh>
#include <spcCore/graphics/image.hh>
#include <spcCore/graphics/isampler.hh>
#include <spcCore/math/math.hh>
#include <GL/glew.h>
namespace spc::opengl
{
GL4TextureCube::GL4TextureCube()
: iTextureCube()
, m_size(0)
, m_sampler(nullptr)
{
SPC_CLASS_GEN_CONSTR;
glGenTextures(1, &m_name);
}
GL4TextureCube::~GL4TextureCube()
{
glDeleteTextures(1, &m_name);
m_name = 0;
}
void GL4TextureCube::Bind()
{
glBindTexture(GL_TEXTURE_CUBE_MAP, m_name);
}
bool GL4TextureCube::Initialize(UInt16 size, ePixelFormat format, bool generateMipMaps)
{
m_size = size;
m_format = format;
Bind();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
UInt8 level = 0;
while (true)
{
Level lvl;
lvl.Size = size;
m_level.push_back(lvl);
for (GLenum i=0; i<6; i++)
{
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
level,
GL4PixelFormatInternal[format],
size,
size,
0,
GL4PixelFormatClient[format],
GL4PixelFormatClientDataType[format],
nullptr
);
}
if (!generateMipMaps || size == 1)
{
break;
}
size = spcMax(size / 2, 1);
level++;
}
return true;
}
void GL4TextureCube::Data(eCubeFace face, const Image* image)
{
for (UInt16 l=0; l<image->GetNumberOfLayers(); l++)
{
Data(face, l, image->GetPixelFormat(), image->GetData(l));
}
}
void GL4TextureCube::Data(eCubeFace face, UInt16 level, const Image* image)
{
Data(face, level, image->GetPixelFormat(), image->GetData(level));
}
void GL4TextureCube::Data(eCubeFace face, UInt16 level, ePixelFormat format, const void* data)
{
if (level >= m_level.size())
{
return;
}
Level& lvl = m_level[level];
glTexSubImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + static_cast<GLenum>(face),
level,
0, 0,
lvl.Size, lvl.Size,
GL4PixelFormatClient[format],
GL4PixelFormatClientDataType[format],
data
);
}
void GL4TextureCube::Data(eCubeFace face, UInt16 level, UInt16 x, UInt16 y, UInt16 width, UInt16 height, ePixelFormat format, const void* data)
{
if (level >= m_level.size())
{
return;
}
glTexSubImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + static_cast<GLenum>(face),
level,
x, y,
width, height,
GL4PixelFormatClient[format],
GL4PixelFormatClientDataType[format],
data
);
}
void GL4TextureCube::SetSampler(iSampler* sampler)
{
SPC_SET(m_sampler, sampler);
}
iSampler* GL4TextureCube::GetSampler()
{
return m_sampler;
}
const iSampler* GL4TextureCube::GetSampler() const
{
return m_sampler;
}
ePixelFormat GL4TextureCube::GetFormat() const
{
return m_format;
}
}
| 21.870748
| 143
| 0.660653
|
marcellfischbach
|
4b690e38d0163d380e2cc6a60899ff1122c34528
| 1,382
|
hpp
|
C++
|
src-idgen/mode.hpp
|
bcrist/bengine-idgen
|
33ef597d8ea533485516a212c3213111548a9742
|
[
"MIT"
] | null | null | null |
src-idgen/mode.hpp
|
bcrist/bengine-idgen
|
33ef597d8ea533485516a212c3213111548a9742
|
[
"MIT"
] | null | null | null |
src-idgen/mode.hpp
|
bcrist/bengine-idgen
|
33ef597d8ea533485516a212c3213111548a9742
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef BE_IDGEN_MODE_HPP_
#define BE_IDGEN_MODE_HPP_
#include <be/core/enum_traits.hpp>
/*!! include 'idgen/mode' !! 50 */
/* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */
namespace be::idgen {
///////////////////////////////////////////////////////////////////////////////
enum class Mode : U8 {
fnv0 = 0,
fnv1,
fnv1a
};
bool is_valid(Mode constant) noexcept;
const char* mode_name(Mode constant) noexcept;
std::array<const Mode, 3> mode_values() noexcept;
std::ostream& operator<<(std::ostream& os, Mode constant);
} // be::idgen
namespace be {
///////////////////////////////////////////////////////////////////////////////
template <>
struct EnumTraits<::be::idgen::Mode> {
using type = ::be::idgen::Mode;
using underlying_type = typename std::underlying_type<type>::type;
static constexpr std::size_t count = 3;
static bool is_valid(type value) {
return ::be::idgen::is_valid(value);
}
static const char* name(type value) {
return ::be::idgen::mode_name(value);
}
template <typename C = std::array<const type, count>>
static C values() {
return {
::be::idgen::Mode::fnv0,
::be::idgen::Mode::fnv1,
::be::idgen::Mode::fnv1a,
};
}
};
} // be
/* ######################### END OF GENERATED CODE ######################### */
#endif
| 23.033333
| 79
| 0.517366
|
bcrist
|
4b6a79fb2046884c1984d607d60f2a19147573eb
| 2,381
|
hpp
|
C++
|
include/hydro/utility/terminal_format.hpp
|
hydraate/hydro
|
42037a8278dcfdca68fb5cceaf6988da861f0eff
|
[
"Apache-2.0"
] | null | null | null |
include/hydro/utility/terminal_format.hpp
|
hydraate/hydro
|
42037a8278dcfdca68fb5cceaf6988da861f0eff
|
[
"Apache-2.0"
] | null | null | null |
include/hydro/utility/terminal_format.hpp
|
hydraate/hydro
|
42037a8278dcfdca68fb5cceaf6988da861f0eff
|
[
"Apache-2.0"
] | null | null | null |
//
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#ifndef __h3o_terminal_format__
#define __h3o_terminal_format__
#include <iostream>
#include "../vm/detect.hpp"
//the following are UBUNTU/LINUX, and MacOS ONLY terminal color codes.
namespace hydro
{
class terminal_format
{
public:
terminal_format() {}
terminal_format(const char *value) : m_value{value} {}
terminal_format(std::string value) : m_value{value} {}
terminal_format(const terminal_format &format) : m_value{format.m_value} {}
terminal_format(terminal_format &&format) : m_value{format.m_value} {}
~terminal_format() {}
std::string value() const { return m_value; }
bool empty() const { return m_value.empty(); }
operator bool() const { return !m_value.empty(); }
terminal_format &operator=(const terminal_format &rhs)
{
m_value = rhs.m_value;
return (*this);
}
terminal_format &operator=(terminal_format &&rhs)
{
m_value = rhs.m_value;
return (*this);
}
terminal_format operator+(const terminal_format &rhs) const
{
if(m_value == rhs.m_value)
return rhs;
return m_value + rhs.m_value;
}
static terminal_format txt256(uint8_t code) { return "\u001b[38;5;" + std::to_string(code) + "m"; }
static terminal_format bg256(uint8_t code) { return "\u001b[48;5;" + std::to_string(code) + "m"; }
private:
std::string m_value;
};
const terminal_format NIL_FORMAT;
const terminal_format RESET = "\033[0m";
const terminal_format BLACK = "\033[30m";
const terminal_format RED = "\033[31m";
const terminal_format GREEN = "\033[32m";
const terminal_format YELLOW = "\033[33m";
const terminal_format BLUE = "\033[34m";
const terminal_format MAGENTA = "\033[35m";
const terminal_format CYAN = "\033[36m";
const terminal_format WHITE = "\033[37m";
const terminal_format BOLD = "\u001b[1m";
const terminal_format UNDERLINE = "\u001b[4m";
std::ostream &operator<<(std::ostream &lhs, const terminal_format &rhs);
} // namespace hydro
#endif /* __h3o_terminal_format__ */
| 30.525641
| 103
| 0.616128
|
hydraate
|
4b6ac20c0e87ef1a12f8badc7fd4de80944a19ea
| 7,172
|
hpp
|
C++
|
c++/include/util/cache/icache_cf.hpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 31
|
2016-12-09T04:56:59.000Z
|
2021-12-31T17:19:10.000Z
|
c++/include/util/cache/icache_cf.hpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 6
|
2017-03-10T17:25:13.000Z
|
2021-09-22T15:49:49.000Z
|
c++/include/util/cache/icache_cf.hpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 20
|
2015-01-04T02:15:17.000Z
|
2021-12-03T02:31:43.000Z
|
#ifndef UTIL_ICACHE_CF__HPP
#define UTIL_ICACHE_CF__HPP
/* $Id: icache_cf.hpp 112045 2007-10-10 20:43:07Z ivanovp $
* ===========================================================================
*
* public DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Anatoliy Kuznetsov
*
* File Description:
* Util library ICache class factory assistance functions
*
*/
#include <corelib/ncbistd.hpp>
#include <corelib/ncbistr.hpp>
#include <corelib/plugin_manager.hpp>
#include <corelib/plugin_manager_impl.hpp>
#include <util/cache/icache.hpp>
#include <util/error_codes.hpp>
BEGIN_NCBI_SCOPE
/// Utility class for ICache class factories
///
/// @internal
///
template<class TDriver>
class CICacheCF : public CSimpleClassFactoryImpl<ICache, TDriver>
{
public:
typedef
CSimpleClassFactoryImpl<ICache, TDriver> TParent;
public:
CICacheCF(const string& driver_name, int patch_level = -1)
: TParent(driver_name, patch_level)
{}
/// Utility function, configures common ICache parameters
void ConfigureICache(ICache* icache,
const TPluginManagerParamTree* params) const
{
if (!params) return;
// Timestamp configuration
{{
static const string kCFParam_timestamp = "timestamp";
const string& ts_flags_str =
this->GetParam(params, kCFParam_timestamp, false);
if (!ts_flags_str.empty()) {
ConfigureTimeStamp(icache, params, ts_flags_str);
}
}}
static const string kCFParam_keep_versions = "keep_versions";
const string& keep_versions_str =
this->GetParam(params, kCFParam_keep_versions, false);
if (!keep_versions_str.empty()) {
static const string kCFParam_keep_versions_all = "all";
static const string kCFParam_keep_versions_drop_old = "drop_old";
static const string kCFParam_keep_versions_drop_all = "drop_all";
ICache::EKeepVersions kv_policy = ICache::eKeepAll;
if (NStr::CompareNocase(keep_versions_str,
kCFParam_keep_versions_all)==0) {
kv_policy = ICache::eKeepAll;
} else
if (NStr::CompareNocase(keep_versions_str,
kCFParam_keep_versions_drop_old)==0) {
kv_policy = ICache::eDropOlder;
} else
if (NStr::CompareNocase(keep_versions_str,
kCFParam_keep_versions_drop_all)==0) {
kv_policy = ICache::eDropAll;
} else {
LOG_POST_XX(Util_Cache, 1, Warning
<< "ICache::ClassFactory: Unknown keep_versions"
" policy parameter: "
<< keep_versions_str);
}
icache->SetVersionRetention(kv_policy);
}
}
void ConfigureTimeStamp(ICache* icache,
const TPluginManagerParamTree* params,
const string& options) const
{
static
const string kCFParam_timeout = "timeout";
static
const string kCFParam_max_timeout = "max_timeout";
static
const string kCFParam_timestamp_onread = "onread";
static
const string kCFParam_timestamp_subkey = "subkey";
static
const string kCFParam_timestamp_expire_not_used = "expire_not_used";
static
const string kCFParam_timestamp_purge_on_startup = "purge_on_startup";
static
const string kCFParam_timestamp_check_expiration = "check_expiration";
list<string> opt;
NStr::Split(options, " \t", opt);
ICache::TTimeStampFlags ts_flag = 0;
ITERATE(list<string>, it, opt) {
const string& opt_value = *it;
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_onread)==0) {
ts_flag |= ICache::fTimeStampOnRead;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_subkey)==0) {
ts_flag |= ICache::fTrackSubKey;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_expire_not_used)==0) {
ts_flag |= ICache::fExpireLeastFrequentlyUsed;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_purge_on_startup)==0) {
ts_flag |= ICache::fPurgeOnStartup;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_check_expiration)==0) {
ts_flag |= ICache::fCheckExpirationAlways;
continue;
}
LOG_POST_XX(Util_Cache, 2, Warning
<< "ICache::ClassFactory: Unknown timeout policy parameter: "
<< opt_value);
} // ITERATE
unsigned int timeout = (unsigned int)
this->GetParamInt(params, kCFParam_timeout, false, 60 * 60);
unsigned int max_timeout = (unsigned int)
this->GetParamInt(params, kCFParam_max_timeout, false, 0);
if (max_timeout && max_timeout < timeout)
max_timeout = timeout;
if (ts_flag) {
icache->SetTimeStampPolicy(ts_flag, timeout, max_timeout);
}
}
};
END_NCBI_SCOPE
#endif /* UTIL_EXCEPTION__HPP */
| 37.94709
| 83
| 0.55396
|
OpenHero
|
4b76480e75d23fa51b56931256f6b835a3be8d6a
| 443
|
cpp
|
C++
|
C++ Practice Programs/Example_2.cpp
|
Ahtisham-Shakir/CPP_OOP
|
308e7bdbd1e73c644a17f612fc5b919cb68c171c
|
[
"MIT"
] | null | null | null |
C++ Practice Programs/Example_2.cpp
|
Ahtisham-Shakir/CPP_OOP
|
308e7bdbd1e73c644a17f612fc5b919cb68c171c
|
[
"MIT"
] | null | null | null |
C++ Practice Programs/Example_2.cpp
|
Ahtisham-Shakir/CPP_OOP
|
308e7bdbd1e73c644a17f612fc5b919cb68c171c
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
int main() {
// Complete the code.
int a; long b; char c; float d; double e;
cout<<"Enter int, long, char, float, double: ";
cin >> a >> b >> c >> d >> e;
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << fixed << setprecision(3) << d << endl;
cout << fixed << setprecision(9) << e << endl;
return 0;
}
| 24.611111
| 51
| 0.534989
|
Ahtisham-Shakir
|
4b7819b68b51209a0c8b01327b7735150af1ec0d
| 42
|
cpp
|
C++
|
c++/Test/Naming.cpp
|
taku-xhift/labo
|
89dc28fdb602c7992c6f31920714225f83a11218
|
[
"MIT"
] | null | null | null |
c++/Test/Naming.cpp
|
taku-xhift/labo
|
89dc28fdb602c7992c6f31920714225f83a11218
|
[
"MIT"
] | null | null | null |
c++/Test/Naming.cpp
|
taku-xhift/labo
|
89dc28fdb602c7992c6f31920714225f83a11218
|
[
"MIT"
] | null | null | null |
int main() {
int 1st = 0;
}
| 4.666667
| 14
| 0.333333
|
taku-xhift
|
4b7879257a7d891d99249a431e32191493163496
| 874
|
cpp
|
C++
|
Engine/Renderer/GLES3/src/GLES3UniformBufferManager.cpp
|
LiangYue1981816/AresEngine
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
[
"BSD-2-Clause"
] | 3
|
2018-12-08T16:32:05.000Z
|
2020-06-02T11:07:15.000Z
|
Engine/Renderer/GLES3/src/GLES3UniformBufferManager.cpp
|
LiangYue1981816/AresEngine
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
[
"BSD-2-Clause"
] | null | null | null |
Engine/Renderer/GLES3/src/GLES3UniformBufferManager.cpp
|
LiangYue1981816/AresEngine
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
[
"BSD-2-Clause"
] | 1
|
2019-09-12T00:26:05.000Z
|
2019-09-12T00:26:05.000Z
|
#include "GLES3Renderer.h"
CGLES3UniformBufferManager::CGLES3UniformBufferManager(void)
{
}
CGLES3UniformBufferManager::~CGLES3UniformBufferManager(void)
{
for (const auto& itUniformBuffer : m_pUniformBuffers) {
delete itUniformBuffer.second;
}
}
CGLES3UniformBuffer* CGLES3UniformBufferManager::Create(size_t size)
{
mutex_autolock autolock(&lock);
{
if (CGLES3UniformBuffer* pUniformBuffer = new CGLES3UniformBuffer(this, size)) {
m_pUniformBuffers[pUniformBuffer] = pUniformBuffer;
return pUniformBuffer;
}
else {
return nullptr;
}
}
}
void CGLES3UniformBufferManager::Destroy(CGLES3UniformBuffer* pUniformBuffer)
{
ASSERT(pUniformBuffer);
{
mutex_autolock autolock(&lock);
{
if (m_pUniformBuffers.find(pUniformBuffer) != m_pUniformBuffers.end()) {
m_pUniformBuffers.erase(pUniformBuffer);
}
}
}
delete pUniformBuffer;
}
| 20.325581
| 82
| 0.763158
|
LiangYue1981816
|
4b78b37c7a82626e4f04199ef872148e5cd0d2ff
| 679
|
cpp
|
C++
|
AndroidC++/jni/Sprite.cpp
|
BenjaminNitschke/MobileCourse
|
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
|
[
"Apache-2.0"
] | 1
|
2015-06-20T09:09:29.000Z
|
2015-06-20T09:09:29.000Z
|
AndroidC++/jni/Sprite.cpp
|
BenjaminNitschke/MobileCourse
|
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
|
[
"Apache-2.0"
] | null | null | null |
AndroidC++/jni/Sprite.cpp
|
BenjaminNitschke/MobileCourse
|
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
|
[
"Apache-2.0"
] | null | null | null |
#include "Sprite.h"
#include <GLES/gl.h>
using namespace SpaceInvaders;
void Sprite::Draw(float x, float y)
{
glBindTexture(GL_TEXTURE_2D, texture->GetHandle());
glTexCoordPointer(2, GL_FLOAT, 0, uvBuffer);
vertices[0] = initialX + x - width; vertices[1] = initialY + y + height; // top left
vertices[3] = initialX + x - width; vertices[4] = initialY + y - height; // bottom left
vertices[6] = initialX + x + width; vertices[7] = initialY + y - height; // bottom right
vertices[9] = initialX + x + width; vertices[10] = initialY + y + height; // top right
glVertexPointer(3, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 2 * 3, GL_UNSIGNED_SHORT, indexBuffer);
}
| 42.4375
| 89
| 0.69514
|
BenjaminNitschke
|
4b80011363c33c66c08bae89d4b291682948401f
| 2,911
|
cpp
|
C++
|
t/006_grapheme_iterator.t.cpp
|
pr8x/u5e
|
3b970d5bc251fdef341d039d66c84ec5eaf4cb6a
|
[
"BSD-2-Clause"
] | 19
|
2015-09-18T14:06:40.000Z
|
2021-07-20T19:51:34.000Z
|
t/006_grapheme_iterator.t.cpp
|
pr8x/u5e
|
3b970d5bc251fdef341d039d66c84ec5eaf4cb6a
|
[
"BSD-2-Clause"
] | 6
|
2016-09-04T02:12:07.000Z
|
2017-08-10T10:07:06.000Z
|
t/006_grapheme_iterator.t.cpp
|
pr8x/u5e
|
3b970d5bc251fdef341d039d66c84ec5eaf4cb6a
|
[
"BSD-2-Clause"
] | 7
|
2015-10-12T15:36:34.000Z
|
2021-02-19T05:15:25.000Z
|
#include "gtest/gtest.h"
#include <string>
#include <sstream>
#include <u5e/codepoint.hpp>
#include <u5e/utf8_string.hpp>
#include <u5e/utf8_string_grapheme.hpp>
#include <u5e/utf8_string_grapheme_iterator.hpp>
#include <u5e/utf32ne_string.hpp>
#include <u5e/utf32ne_string_grapheme.hpp>
#include <u5e/utf32ne_string_grapheme_iterator.hpp>
using u5e::codepoint;
using u5e::utf8_string;
using u5e::utf8_string_grapheme;
using u5e::utf8_string_grapheme_iterator;
using u5e::utf32ne_string;
using u5e::utf32ne_string_grapheme;
using u5e::utf32ne_string_grapheme_iterator;
TEST(t_006_utf8_string_grapheme_iterator, utf8) {
// this is a decomposed grapheme
utf8_string str("Ola\xCC\x81!");
// now we get a grapheme iterator from the utf8 iterator
utf8_string_grapheme_iterator gi(str.grapheme_begin());
// the current grapheme
utf8_string_grapheme g(*gi);
// has an inner iterator
utf8_string::const_iterator ci(g.codepoint_begin());
// which points to a codepoint
codepoint c(*ci);
// first grapheme
ASSERT_EQ('O', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// second grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('l', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// third grapheme
// this one has two codepoints
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('a', c);
ci++;
c = *ci;
ASSERT_EQ(769, c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// fourth grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('!', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
ASSERT_TRUE(gi == str.codepoint_cend());
};
TEST(t_006_utf8_string_grapheme_iterator, utf32ne) {
// this is a decomposed grapheme
utf32ne_string str({ 'O', 'l', 'a', 769, '!' });
// now we get a grapheme iterator from the utf32ne iterator
utf32ne_string_grapheme_iterator gi(str.grapheme_begin());
// the current grapheme
utf32ne_string_grapheme g(*gi);
// has an inner iterator
utf32ne_string::const_iterator ci(g.codepoint_begin());
// which points to a codepoint
codepoint c(*ci);
// first grapheme
ASSERT_EQ('O', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// second grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('l', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// third grapheme
// this one has two codepoints
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('a', c);
ci++;
c = *ci;
ASSERT_EQ(769, c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// fourth grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('!', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
ASSERT_TRUE(gi == str.codepoint_cend());
};
| 20.075862
| 61
| 0.655101
|
pr8x
|
4b81a5977bea4e6ed6c6ac939263c7d32fbbf2df
| 121
|
cpp
|
C++
|
MultiMon.cpp
|
SegaraRai/EntisGLS4Build
|
2587390738802394a38b3aaf2adc80295dde7ec4
|
[
"CC0-1.0",
"Unlicense"
] | 3
|
2021-11-05T08:02:17.000Z
|
2022-02-26T18:03:18.000Z
|
MultiMon.cpp
|
SegaraRai/EntisGLS4Build
|
2587390738802394a38b3aaf2adc80295dde7ec4
|
[
"CC0-1.0",
"Unlicense"
] | null | null | null |
MultiMon.cpp
|
SegaraRai/EntisGLS4Build
|
2587390738802394a38b3aaf2adc80295dde7ec4
|
[
"CC0-1.0",
"Unlicense"
] | null | null | null |
#ifdef DISABLE_ENTIS_GLS4_EXPORTS
# include <Windows.h>
# define COMPILE_MULTIMON_STUBS
# include <MultiMon.h>
#endif
| 13.444444
| 33
| 0.785124
|
SegaraRai
|
4b8268f37171d1ffc0aff29e21d11c6bdc320d67
| 2,872
|
cpp
|
C++
|
source/request.cpp
|
kociap/rpp
|
1c0009c1abcd9416c75c75a981b235f2db551e89
|
[
"MIT"
] | null | null | null |
source/request.cpp
|
kociap/rpp
|
1c0009c1abcd9416c75c75a981b235f2db551e89
|
[
"MIT"
] | null | null | null |
source/request.cpp
|
kociap/rpp
|
1c0009c1abcd9416c75c75a981b235f2db551e89
|
[
"MIT"
] | null | null | null |
#include "rpp/request.hpp"
#include "curl/curl.h"
namespace rpp {
Request::Request() : handle(curl_easy_init()), headers(nullptr) {}
Request::Request(Request&& req) : handle(req.handle), headers(req.headers) {
req.handle = nullptr;
req.headers = nullptr;
}
Request& Request::operator=(Request&& req) {
handle = req.handle;
headers = req.headers;
req.handle = nullptr;
req.headers = nullptr;
return *this;
}
Request::~Request() {
if (handle != nullptr) {
curl_easy_cleanup(handle);
}
if (headers != nullptr) {
curl_slist_free_all(headers);
}
}
void Request::set_verbose(bool verbose) {
curl_easy_setopt(handle, CURLOPT_VERBOSE, verbose);
}
void Request::set_verify_ssl(bool verify) {
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, verify);
}
void Request::set_headers(Headers const& hs) {
if (hs.headers.empty()) {
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, NULL);
return;
}
if (headers != nullptr) {
curl_slist_free_all(headers);
headers = NULL;
}
for (auto const& [key, value] : hs.headers) {
if (value.empty()) {
headers = curl_slist_append(headers, (key + ";").data());
} else {
headers = curl_slist_append(headers, (key + ": " + value).data());
}
}
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
}
size_t curl_write_function(char* data, size_t, size_t data_size, std::string* user_data) {
user_data->append(data, data_size);
return data_size;
}
Response Request::get(URL const& url) {
Response res;
std::string full_url = url.get_full_url();
curl_easy_setopt(handle, CURLOPT_URL, full_url.c_str());
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curl_write_function);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &res.text);
curl_easy_perform(handle);
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res.status);
return res;
}
Response Request::post(URL const& url, Body const& body) {
Response res;
std::string data = body.to_string();
std::string full_url = url.get_full_url();
curl_easy_setopt(handle, CURLOPT_URL, full_url.c_str());
curl_easy_setopt(handle, CURLOPT_POST, 1);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curl_write_function);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &res.text);
curl_easy_perform(handle);
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res.status);
return res;
}
} // namespace rpp
| 30.231579
| 94
| 0.60968
|
kociap
|
4b85fba9ab89f08a9661331e0e503d4c95690e88
| 1,928
|
hpp
|
C++
|
include/codegen/include/Zenject/PoolableStaticMemoryPool_1.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/Zenject/PoolableStaticMemoryPool_1.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/Zenject/PoolableStaticMemoryPool_1.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: Zenject.StaticMemoryPool`1
#include "Zenject/StaticMemoryPool_1.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: IPoolable
class IPoolable;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.PoolableStaticMemoryPool`1
template<typename TValue>
class PoolableStaticMemoryPool_1 : public Zenject::StaticMemoryPool_1<TValue> {
public:
// static private System.Void OnSpawned(TValue value)
// Offset: 0x15DB9E8
static void OnSpawned(TValue value) {
CRASH_UNLESS(il2cpp_utils::RunMethod(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PoolableStaticMemoryPool_1<TValue>*>::get(), "OnSpawned", value));
}
// static private System.Void OnDespawned(TValue value)
// Offset: 0x15DBA98
static void OnDespawned(TValue value) {
CRASH_UNLESS(il2cpp_utils::RunMethod(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PoolableStaticMemoryPool_1<TValue>*>::get(), "OnDespawned", value));
}
// public System.Void .ctor()
// Offset: 0x15DB918
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static PoolableStaticMemoryPool_1<TValue>* New_ctor() {
return (PoolableStaticMemoryPool_1<TValue>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PoolableStaticMemoryPool_1<TValue>*>::get()));
}
}; // Zenject.PoolableStaticMemoryPool`1
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::PoolableStaticMemoryPool_1, "Zenject", "PoolableStaticMemoryPool`1");
#pragma pack(pop)
| 42.844444
| 180
| 0.729253
|
Futuremappermydud
|
4b863e877773836ce1b1ce3d02a9bd36ba641089
| 1,816
|
cpp
|
C++
|
src/Events/OE_Event.cpp
|
antsouchlos/OxygenEngine2
|
5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb
|
[
"MIT"
] | null | null | null |
src/Events/OE_Event.cpp
|
antsouchlos/OxygenEngine2
|
5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb
|
[
"MIT"
] | 22
|
2020-05-19T18:18:45.000Z
|
2022-03-31T12:11:08.000Z
|
src/Events/OE_Event.cpp
|
antsouchlos/OxygenEngine2
|
5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb
|
[
"MIT"
] | null | null | null |
#include <OE_Math.h>
#include <Events/OE_Event.h>
#include <Carbon/CSL_Interpreter.h>
using namespace std;
bool OE_Event::finished = false;
OE_Event::OE_Event(){
active_=false;
name_ = "";
}
OE_Event::~OE_Event(){}
void OE_Event::setFunc(const OE_EVENTFUNC a_func){
lockMutex();
func_ = a_func;
unlockMutex();
}
//keyboard
OE_KeyboardEvent::OE_KeyboardEvent(){
type_ = OE_KEYBOARD_EVENT;
keystate = OE_BUTTON::RELEASE;
}
OE_KeyboardEvent::~OE_KeyboardEvent(){}
int OE_KeyboardEvent::call(){
return internal_call();
}
//mouse
int OE_MouseEvent::x = 0;
int OE_MouseEvent::y = 0;
int OE_MouseEvent::delta_x = 0;
int OE_MouseEvent::delta_y = 0;
int OE_MouseEvent::mouse_wheel = 0;
bool OE_MouseEvent::mousemoved = false;
OE_MouseEvent::OE_MouseEvent(){
type_ = OE_MOUSE_EVENT;
mousemoved = false;
keystate = OE_BUTTON::RELEASE;
}
OE_MouseEvent::~OE_MouseEvent(){}
int OE_MouseEvent::call(){
return internal_call();
}
//gamepad
OE_GamepadEvent::OE_GamepadEvent(){
type_ = OE_GAMEPAD_EVENT;
axis=0; axismoved = false;
}
OE_GamepadEvent::~OE_GamepadEvent(){}
int OE_GamepadEvent::call(){
return internal_call();
}
//custom
OE_CustomEvent::OE_CustomEvent(){
type_ = OE_CUSTOM_EVENT;
}
OE_CustomEvent::~OE_CustomEvent(){}
int OE_CustomEvent::call(){
return internal_call();
}
//error
OE_ErrorEvent::OE_ErrorEvent(){
type_ = OE_ERROR_EVENT;
}
OE_ErrorEvent::~OE_ErrorEvent(){}
int OE_ErrorEvent::call(){
/***************************/
///non-generic handling
if( this->importance == OE_FATAL) finished = true;
this->internal_call();
return 0;
}
//multiple events
OE_EventCombo::OE_EventCombo(){
type_ = OE_EVENT_COMBO;
}
OE_EventCombo::~OE_EventCombo(){}
int OE_EventCombo::call(){
return internal_call();
}
| 17.461538
| 51
| 0.69163
|
antsouchlos
|
4b8bbbded467cad466b585b5f59ac99dee81a551
| 1,177
|
cpp
|
C++
|
android-31/android/drm/DrmConvertedStatus.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-28/android/drm/DrmConvertedStatus.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-30/android/drm/DrmConvertedStatus.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../JByteArray.hpp"
#include "./DrmConvertedStatus.hpp"
namespace android::drm
{
// Fields
jint DrmConvertedStatus::STATUS_ERROR()
{
return getStaticField<jint>(
"android.drm.DrmConvertedStatus",
"STATUS_ERROR"
);
}
jint DrmConvertedStatus::STATUS_INPUTDATA_ERROR()
{
return getStaticField<jint>(
"android.drm.DrmConvertedStatus",
"STATUS_INPUTDATA_ERROR"
);
}
jint DrmConvertedStatus::STATUS_OK()
{
return getStaticField<jint>(
"android.drm.DrmConvertedStatus",
"STATUS_OK"
);
}
JByteArray DrmConvertedStatus::convertedData()
{
return getObjectField(
"convertedData",
"[B"
);
}
jint DrmConvertedStatus::offset()
{
return getField<jint>(
"offset"
);
}
jint DrmConvertedStatus::statusCode()
{
return getField<jint>(
"statusCode"
);
}
// QJniObject forward
DrmConvertedStatus::DrmConvertedStatus(QJniObject obj) : JObject(obj) {}
// Constructors
DrmConvertedStatus::DrmConvertedStatus(jint arg0, JByteArray arg1, jint arg2)
: JObject(
"android.drm.DrmConvertedStatus",
"(I[BI)V",
arg0,
arg1.object<jbyteArray>(),
arg2
) {}
// Methods
} // namespace android::drm
| 18.390625
| 78
| 0.692438
|
YJBeetle
|
4b8c0a1a8b99bfff9517b5566b0c5b6d66751cec
| 1,553
|
cpp
|
C++
|
examples/Threads/token.cpp
|
azerothcore/lib-ace
|
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
|
[
"DOC"
] | null | null | null |
examples/Threads/token.cpp
|
azerothcore/lib-ace
|
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
|
[
"DOC"
] | null | null | null |
examples/Threads/token.cpp
|
azerothcore/lib-ace
|
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
|
[
"DOC"
] | 1
|
2020-04-26T03:07:12.000Z
|
2020-04-26T03:07:12.000Z
|
// Test out the ACE Token class.
#include "ace/OS_main.h"
#include "ace/Token.h"
#include "ace/Task.h"
#include "ace/OS_NS_time.h"
#if defined (ACE_HAS_THREADS)
class My_Task : public ACE_Task<ACE_MT_SYNCH>
{
public:
My_Task (int n);
virtual int svc (void);
static void sleep_hook (void *);
private:
ACE_Token token_;
};
My_Task::My_Task (int n)
{
// Make this Task into an Active Object.
this->activate (THR_BOUND | THR_DETACHED, n);
// Wait for all the threads to exit.
this->thr_mgr ()->wait ();
}
void
My_Task::sleep_hook (void *)
{
ACE_DEBUG ((LM_ERROR, "(%u) blocking, My_Task::sleep_hook () called\n",
ACE_Thread::self())) ;
}
// Test out the behavior of the ACE_Token class.
int
My_Task::svc (void)
{
for (size_t i = 0; i < 100; i++)
{
// Wait for up to 1 millisecond past the current time to get the token.
ACE_Time_Value timeout (ACE_OS::time (0), 1000);
if (this->token_.acquire (&My_Task::sleep_hook, 0, &timeout) == 1)
{
this->token_.acquire ();
this->token_.renew ();
this->token_.release ();
this->token_.release ();
}
else
ACE_Thread::yield ();
}
return 0;
}
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
My_Task tasks (argc > 1 ? ACE_OS::atoi (argv[1]) : 4);
return 0;
}
#else
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
ACE_ERROR_RETURN ((LM_ERROR, "your platform doesn't support threads\n"), -1);
}
#endif /* */
| 20.168831
| 80
| 0.584031
|
azerothcore
|
4b91f517f4ea60bcd0000af4532094ca6a4d46e1
| 128,536
|
cc
|
C++
|
protocal/routing/routing.pb.cc
|
racestart/g2r
|
d115ebaab13829d716750eab2ebdcc51d79ff32e
|
[
"Apache-2.0"
] | 1
|
2020-03-05T12:49:21.000Z
|
2020-03-05T12:49:21.000Z
|
protocal/routing/routing.pb.cc
|
gA4ss/g2r
|
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
|
[
"Apache-2.0"
] | null | null | null |
protocal/routing/routing.pb.cc
|
gA4ss/g2r
|
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
|
[
"Apache-2.0"
] | 1
|
2020-03-25T15:06:39.000Z
|
2020-03-25T15:06:39.000Z
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: routing/routing.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "routing/routing.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace apollo {
namespace routing {
namespace {
const ::google::protobuf::Descriptor* LaneWaypoint_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
LaneWaypoint_reflection_ = NULL;
const ::google::protobuf::Descriptor* LaneSegment_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
LaneSegment_reflection_ = NULL;
const ::google::protobuf::Descriptor* RoutingRequest_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
RoutingRequest_reflection_ = NULL;
const ::google::protobuf::Descriptor* Measurement_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
Measurement_reflection_ = NULL;
const ::google::protobuf::Descriptor* Passage_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
Passage_reflection_ = NULL;
const ::google::protobuf::Descriptor* RoadSegment_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
RoadSegment_reflection_ = NULL;
const ::google::protobuf::Descriptor* RoutingResponse_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
RoutingResponse_reflection_ = NULL;
const ::google::protobuf::EnumDescriptor* ChangeLaneType_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_routing_2frouting_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_routing_2frouting_2eproto() {
protobuf_AddDesc_routing_2frouting_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"routing/routing.proto");
GOOGLE_CHECK(file != NULL);
LaneWaypoint_descriptor_ = file->message_type(0);
static const int LaneWaypoint_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneWaypoint, id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneWaypoint, s_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneWaypoint, pose_),
};
LaneWaypoint_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
LaneWaypoint_descriptor_,
LaneWaypoint::default_instance_,
LaneWaypoint_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneWaypoint, _has_bits_[0]),
-1,
-1,
sizeof(LaneWaypoint),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneWaypoint, _internal_metadata_),
-1);
LaneSegment_descriptor_ = file->message_type(1);
static const int LaneSegment_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneSegment, id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneSegment, start_s_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneSegment, end_s_),
};
LaneSegment_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
LaneSegment_descriptor_,
LaneSegment::default_instance_,
LaneSegment_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneSegment, _has_bits_[0]),
-1,
-1,
sizeof(LaneSegment),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LaneSegment, _internal_metadata_),
-1);
RoutingRequest_descriptor_ = file->message_type(2);
static const int RoutingRequest_offsets_[5] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, header_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, waypoint_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, blacklisted_lane_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, blacklisted_road_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, broadcast_),
};
RoutingRequest_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
RoutingRequest_descriptor_,
RoutingRequest::default_instance_,
RoutingRequest_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, _has_bits_[0]),
-1,
-1,
sizeof(RoutingRequest),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingRequest, _internal_metadata_),
-1);
Measurement_descriptor_ = file->message_type(3);
static const int Measurement_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Measurement, distance_),
};
Measurement_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Measurement_descriptor_,
Measurement::default_instance_,
Measurement_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Measurement, _has_bits_[0]),
-1,
-1,
sizeof(Measurement),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Measurement, _internal_metadata_),
-1);
Passage_descriptor_ = file->message_type(4);
static const int Passage_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Passage, segment_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Passage, can_exit_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Passage, change_lane_type_),
};
Passage_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Passage_descriptor_,
Passage::default_instance_,
Passage_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Passage, _has_bits_[0]),
-1,
-1,
sizeof(Passage),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Passage, _internal_metadata_),
-1);
RoadSegment_descriptor_ = file->message_type(5);
static const int RoadSegment_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoadSegment, id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoadSegment, passage_),
};
RoadSegment_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
RoadSegment_descriptor_,
RoadSegment::default_instance_,
RoadSegment_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoadSegment, _has_bits_[0]),
-1,
-1,
sizeof(RoadSegment),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoadSegment, _internal_metadata_),
-1);
RoutingResponse_descriptor_ = file->message_type(6);
static const int RoutingResponse_offsets_[6] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, header_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, road_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, measurement_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, routing_request_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, map_version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, status_),
};
RoutingResponse_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
RoutingResponse_descriptor_,
RoutingResponse::default_instance_,
RoutingResponse_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, _has_bits_[0]),
-1,
-1,
sizeof(RoutingResponse),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RoutingResponse, _internal_metadata_),
-1);
ChangeLaneType_descriptor_ = file->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_routing_2frouting_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
LaneWaypoint_descriptor_, &LaneWaypoint::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
LaneSegment_descriptor_, &LaneSegment::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
RoutingRequest_descriptor_, &RoutingRequest::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
Measurement_descriptor_, &Measurement::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
Passage_descriptor_, &Passage::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
RoadSegment_descriptor_, &RoadSegment::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
RoutingResponse_descriptor_, &RoutingResponse::default_instance());
}
} // namespace
void protobuf_ShutdownFile_routing_2frouting_2eproto() {
delete LaneWaypoint::default_instance_;
delete LaneWaypoint_reflection_;
delete LaneSegment::default_instance_;
delete LaneSegment_reflection_;
delete RoutingRequest::default_instance_;
delete RoutingRequest_reflection_;
delete Measurement::default_instance_;
delete Measurement_reflection_;
delete Passage::default_instance_;
delete Passage_reflection_;
delete RoadSegment::default_instance_;
delete RoadSegment_reflection_;
delete RoutingResponse::default_instance_;
delete RoutingResponse_reflection_;
}
void protobuf_AddDesc_routing_2frouting_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AddDesc_routing_2frouting_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::apollo::common::protobuf_AddDesc_common_2fheader_2eproto();
::apollo::common::protobuf_AddDesc_common_2fgeometry_2eproto();
::apollo::common::protobuf_AddDesc_common_2ferror_5fcode_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\025routing/routing.proto\022\016apollo.routing\032"
"\023common/header.proto\032\025common/geometry.pr"
"oto\032\027common/error_code.proto\"L\n\014LaneWayp"
"oint\022\n\n\002id\030\001 \001(\t\022\t\n\001s\030\002 \001(\001\022%\n\004pose\030\003 \001("
"\0132\027.apollo.common.PointENU\"9\n\013LaneSegmen"
"t\022\n\n\002id\030\001 \001(\t\022\017\n\007start_s\030\002 \001(\001\022\r\n\005end_s\030"
"\003 \001(\001\"\321\001\n\016RoutingRequest\022%\n\006header\030\001 \001(\013"
"2\025.apollo.common.Header\022.\n\010waypoint\030\002 \003("
"\0132\034.apollo.routing.LaneWaypoint\0225\n\020black"
"listed_lane\030\003 \003(\0132\033.apollo.routing.LaneS"
"egment\022\030\n\020blacklisted_road\030\004 \003(\t\022\027\n\tbroa"
"dcast\030\005 \001(\010:\004true\"\037\n\013Measurement\022\020\n\010dist"
"ance\030\001 \001(\001\"\214\001\n\007Passage\022,\n\007segment\030\001 \003(\0132"
"\033.apollo.routing.LaneSegment\022\020\n\010can_exit"
"\030\002 \001(\010\022A\n\020change_lane_type\030\003 \001(\0162\036.apoll"
"o.routing.ChangeLaneType:\007FORWARD\"C\n\013Roa"
"dSegment\022\n\n\002id\030\001 \001(\t\022(\n\007passage\030\002 \003(\0132\027."
"apollo.routing.Passage\"\214\002\n\017RoutingRespon"
"se\022%\n\006header\030\001 \001(\0132\025.apollo.common.Heade"
"r\022)\n\004road\030\002 \003(\0132\033.apollo.routing.RoadSeg"
"ment\0220\n\013measurement\030\003 \001(\0132\033.apollo.routi"
"ng.Measurement\0227\n\017routing_request\030\004 \001(\0132"
"\036.apollo.routing.RoutingRequest\022\023\n\013map_v"
"ersion\030\005 \001(\014\022\'\n\006status\030\006 \001(\0132\027.apollo.co"
"mmon.StatusPb*2\n\016ChangeLaneType\022\013\n\007FORWA"
"RD\020\000\022\010\n\004LEFT\020\001\022\t\n\005RIGHT\020\002", 1025);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"routing/routing.proto", &protobuf_RegisterTypes);
LaneWaypoint::default_instance_ = new LaneWaypoint();
LaneSegment::default_instance_ = new LaneSegment();
RoutingRequest::default_instance_ = new RoutingRequest();
Measurement::default_instance_ = new Measurement();
Passage::default_instance_ = new Passage();
RoadSegment::default_instance_ = new RoadSegment();
RoutingResponse::default_instance_ = new RoutingResponse();
LaneWaypoint::default_instance_->InitAsDefaultInstance();
LaneSegment::default_instance_->InitAsDefaultInstance();
RoutingRequest::default_instance_->InitAsDefaultInstance();
Measurement::default_instance_->InitAsDefaultInstance();
Passage::default_instance_->InitAsDefaultInstance();
RoadSegment::default_instance_->InitAsDefaultInstance();
RoutingResponse::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_routing_2frouting_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_routing_2frouting_2eproto {
StaticDescriptorInitializer_routing_2frouting_2eproto() {
protobuf_AddDesc_routing_2frouting_2eproto();
}
} static_descriptor_initializer_routing_2frouting_2eproto_;
const ::google::protobuf::EnumDescriptor* ChangeLaneType_descriptor() {
protobuf_AssignDescriptorsOnce();
return ChangeLaneType_descriptor_;
}
bool ChangeLaneType_IsValid(int value) {
switch(value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LaneWaypoint::kIdFieldNumber;
const int LaneWaypoint::kSFieldNumber;
const int LaneWaypoint::kPoseFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LaneWaypoint::LaneWaypoint()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.LaneWaypoint)
}
void LaneWaypoint::InitAsDefaultInstance() {
pose_ = const_cast< ::apollo::common::PointENU*>(&::apollo::common::PointENU::default_instance());
}
LaneWaypoint::LaneWaypoint(const LaneWaypoint& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.LaneWaypoint)
}
void LaneWaypoint::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
s_ = 0;
pose_ = NULL;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
LaneWaypoint::~LaneWaypoint() {
// @@protoc_insertion_point(destructor:apollo.routing.LaneWaypoint)
SharedDtor();
}
void LaneWaypoint::SharedDtor() {
id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != default_instance_) {
delete pose_;
}
}
void LaneWaypoint::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* LaneWaypoint::descriptor() {
protobuf_AssignDescriptorsOnce();
return LaneWaypoint_descriptor_;
}
const LaneWaypoint& LaneWaypoint::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
LaneWaypoint* LaneWaypoint::default_instance_ = NULL;
LaneWaypoint* LaneWaypoint::New(::google::protobuf::Arena* arena) const {
LaneWaypoint* n = new LaneWaypoint;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void LaneWaypoint::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.LaneWaypoint)
if (_has_bits_[0 / 32] & 7u) {
if (has_id()) {
id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
s_ = 0;
if (has_pose()) {
if (pose_ != NULL) pose_->::apollo::common::PointENU::Clear();
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool LaneWaypoint::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.LaneWaypoint)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string id = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_id()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::PARSE,
"apollo.routing.LaneWaypoint.id");
} else {
goto handle_unusual;
}
if (input->ExpectTag(17)) goto parse_s;
break;
}
// optional double s = 2;
case 2: {
if (tag == 17) {
parse_s:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &s_)));
set_has_s();
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_pose;
break;
}
// optional .apollo.common.PointENU pose = 3;
case 3: {
if (tag == 26) {
parse_pose:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_pose()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.LaneWaypoint)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.LaneWaypoint)
return false;
#undef DO_
}
void LaneWaypoint::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.LaneWaypoint)
// optional string id = 1;
if (has_id()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.LaneWaypoint.id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->id(), output);
}
// optional double s = 2;
if (has_s()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->s(), output);
}
// optional .apollo.common.PointENU pose = 3;
if (has_pose()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->pose_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.LaneWaypoint)
}
::google::protobuf::uint8* LaneWaypoint::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.LaneWaypoint)
// optional string id = 1;
if (has_id()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.LaneWaypoint.id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->id(), target);
}
// optional double s = 2;
if (has_s()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->s(), target);
}
// optional .apollo.common.PointENU pose = 3;
if (has_pose()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->pose_, false, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.LaneWaypoint)
return target;
}
int LaneWaypoint::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.LaneWaypoint)
int total_size = 0;
if (_has_bits_[0 / 32] & 7u) {
// optional string id = 1;
if (has_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->id());
}
// optional double s = 2;
if (has_s()) {
total_size += 1 + 8;
}
// optional .apollo.common.PointENU pose = 3;
if (has_pose()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->pose_);
}
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void LaneWaypoint::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.LaneWaypoint)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const LaneWaypoint* source =
::google::protobuf::internal::DynamicCastToGenerated<const LaneWaypoint>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.LaneWaypoint)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.LaneWaypoint)
MergeFrom(*source);
}
}
void LaneWaypoint::MergeFrom(const LaneWaypoint& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.LaneWaypoint)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_id()) {
set_has_id();
id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.id_);
}
if (from.has_s()) {
set_s(from.s());
}
if (from.has_pose()) {
mutable_pose()->::apollo::common::PointENU::MergeFrom(from.pose());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void LaneWaypoint::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.LaneWaypoint)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LaneWaypoint::CopyFrom(const LaneWaypoint& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.LaneWaypoint)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LaneWaypoint::IsInitialized() const {
return true;
}
void LaneWaypoint::Swap(LaneWaypoint* other) {
if (other == this) return;
InternalSwap(other);
}
void LaneWaypoint::InternalSwap(LaneWaypoint* other) {
id_.Swap(&other->id_);
std::swap(s_, other->s_);
std::swap(pose_, other->pose_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata LaneWaypoint::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = LaneWaypoint_descriptor_;
metadata.reflection = LaneWaypoint_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// LaneWaypoint
// optional string id = 1;
bool LaneWaypoint::has_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void LaneWaypoint::set_has_id() {
_has_bits_[0] |= 0x00000001u;
}
void LaneWaypoint::clear_has_id() {
_has_bits_[0] &= ~0x00000001u;
}
void LaneWaypoint::clear_id() {
id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_id();
}
const ::std::string& LaneWaypoint::id() const {
// @@protoc_insertion_point(field_get:apollo.routing.LaneWaypoint.id)
return id_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void LaneWaypoint::set_id(const ::std::string& value) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:apollo.routing.LaneWaypoint.id)
}
void LaneWaypoint::set_id(const char* value) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:apollo.routing.LaneWaypoint.id)
}
void LaneWaypoint::set_id(const char* value, size_t size) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:apollo.routing.LaneWaypoint.id)
}
::std::string* LaneWaypoint::mutable_id() {
set_has_id();
// @@protoc_insertion_point(field_mutable:apollo.routing.LaneWaypoint.id)
return id_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* LaneWaypoint::release_id() {
// @@protoc_insertion_point(field_release:apollo.routing.LaneWaypoint.id)
clear_has_id();
return id_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void LaneWaypoint::set_allocated_id(::std::string* id) {
if (id != NULL) {
set_has_id();
} else {
clear_has_id();
}
id_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), id);
// @@protoc_insertion_point(field_set_allocated:apollo.routing.LaneWaypoint.id)
}
// optional double s = 2;
bool LaneWaypoint::has_s() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
void LaneWaypoint::set_has_s() {
_has_bits_[0] |= 0x00000002u;
}
void LaneWaypoint::clear_has_s() {
_has_bits_[0] &= ~0x00000002u;
}
void LaneWaypoint::clear_s() {
s_ = 0;
clear_has_s();
}
double LaneWaypoint::s() const {
// @@protoc_insertion_point(field_get:apollo.routing.LaneWaypoint.s)
return s_;
}
void LaneWaypoint::set_s(double value) {
set_has_s();
s_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.LaneWaypoint.s)
}
// optional .apollo.common.PointENU pose = 3;
bool LaneWaypoint::has_pose() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
void LaneWaypoint::set_has_pose() {
_has_bits_[0] |= 0x00000004u;
}
void LaneWaypoint::clear_has_pose() {
_has_bits_[0] &= ~0x00000004u;
}
void LaneWaypoint::clear_pose() {
if (pose_ != NULL) pose_->::apollo::common::PointENU::Clear();
clear_has_pose();
}
const ::apollo::common::PointENU& LaneWaypoint::pose() const {
// @@protoc_insertion_point(field_get:apollo.routing.LaneWaypoint.pose)
return pose_ != NULL ? *pose_ : *default_instance_->pose_;
}
::apollo::common::PointENU* LaneWaypoint::mutable_pose() {
set_has_pose();
if (pose_ == NULL) {
pose_ = new ::apollo::common::PointENU;
}
// @@protoc_insertion_point(field_mutable:apollo.routing.LaneWaypoint.pose)
return pose_;
}
::apollo::common::PointENU* LaneWaypoint::release_pose() {
// @@protoc_insertion_point(field_release:apollo.routing.LaneWaypoint.pose)
clear_has_pose();
::apollo::common::PointENU* temp = pose_;
pose_ = NULL;
return temp;
}
void LaneWaypoint::set_allocated_pose(::apollo::common::PointENU* pose) {
delete pose_;
pose_ = pose;
if (pose) {
set_has_pose();
} else {
clear_has_pose();
}
// @@protoc_insertion_point(field_set_allocated:apollo.routing.LaneWaypoint.pose)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LaneSegment::kIdFieldNumber;
const int LaneSegment::kStartSFieldNumber;
const int LaneSegment::kEndSFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LaneSegment::LaneSegment()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.LaneSegment)
}
void LaneSegment::InitAsDefaultInstance() {
}
LaneSegment::LaneSegment(const LaneSegment& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.LaneSegment)
}
void LaneSegment::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
start_s_ = 0;
end_s_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
LaneSegment::~LaneSegment() {
// @@protoc_insertion_point(destructor:apollo.routing.LaneSegment)
SharedDtor();
}
void LaneSegment::SharedDtor() {
id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != default_instance_) {
}
}
void LaneSegment::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* LaneSegment::descriptor() {
protobuf_AssignDescriptorsOnce();
return LaneSegment_descriptor_;
}
const LaneSegment& LaneSegment::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
LaneSegment* LaneSegment::default_instance_ = NULL;
LaneSegment* LaneSegment::New(::google::protobuf::Arena* arena) const {
LaneSegment* n = new LaneSegment;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void LaneSegment::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.LaneSegment)
#if defined(__clang__)
#define ZR_HELPER_(f) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(LaneSegment, f) \
_Pragma("clang diagnostic pop")
#else
#define ZR_HELPER_(f) reinterpret_cast<char*>(\
&reinterpret_cast<LaneSegment*>(16)->f)
#endif
#define ZR_(first, last) do {\
::memset(&first, 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
if (_has_bits_[0 / 32] & 7u) {
ZR_(start_s_, end_s_);
if (has_id()) {
id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
}
#undef ZR_HELPER_
#undef ZR_
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool LaneSegment::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.LaneSegment)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string id = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_id()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::PARSE,
"apollo.routing.LaneSegment.id");
} else {
goto handle_unusual;
}
if (input->ExpectTag(17)) goto parse_start_s;
break;
}
// optional double start_s = 2;
case 2: {
if (tag == 17) {
parse_start_s:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &start_s_)));
set_has_start_s();
} else {
goto handle_unusual;
}
if (input->ExpectTag(25)) goto parse_end_s;
break;
}
// optional double end_s = 3;
case 3: {
if (tag == 25) {
parse_end_s:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &end_s_)));
set_has_end_s();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.LaneSegment)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.LaneSegment)
return false;
#undef DO_
}
void LaneSegment::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.LaneSegment)
// optional string id = 1;
if (has_id()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.LaneSegment.id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->id(), output);
}
// optional double start_s = 2;
if (has_start_s()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->start_s(), output);
}
// optional double end_s = 3;
if (has_end_s()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->end_s(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.LaneSegment)
}
::google::protobuf::uint8* LaneSegment::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.LaneSegment)
// optional string id = 1;
if (has_id()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.LaneSegment.id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->id(), target);
}
// optional double start_s = 2;
if (has_start_s()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->start_s(), target);
}
// optional double end_s = 3;
if (has_end_s()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->end_s(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.LaneSegment)
return target;
}
int LaneSegment::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.LaneSegment)
int total_size = 0;
if (_has_bits_[0 / 32] & 7u) {
// optional string id = 1;
if (has_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->id());
}
// optional double start_s = 2;
if (has_start_s()) {
total_size += 1 + 8;
}
// optional double end_s = 3;
if (has_end_s()) {
total_size += 1 + 8;
}
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void LaneSegment::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.LaneSegment)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const LaneSegment* source =
::google::protobuf::internal::DynamicCastToGenerated<const LaneSegment>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.LaneSegment)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.LaneSegment)
MergeFrom(*source);
}
}
void LaneSegment::MergeFrom(const LaneSegment& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.LaneSegment)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_id()) {
set_has_id();
id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.id_);
}
if (from.has_start_s()) {
set_start_s(from.start_s());
}
if (from.has_end_s()) {
set_end_s(from.end_s());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void LaneSegment::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.LaneSegment)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LaneSegment::CopyFrom(const LaneSegment& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.LaneSegment)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LaneSegment::IsInitialized() const {
return true;
}
void LaneSegment::Swap(LaneSegment* other) {
if (other == this) return;
InternalSwap(other);
}
void LaneSegment::InternalSwap(LaneSegment* other) {
id_.Swap(&other->id_);
std::swap(start_s_, other->start_s_);
std::swap(end_s_, other->end_s_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata LaneSegment::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = LaneSegment_descriptor_;
metadata.reflection = LaneSegment_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// LaneSegment
// optional string id = 1;
bool LaneSegment::has_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void LaneSegment::set_has_id() {
_has_bits_[0] |= 0x00000001u;
}
void LaneSegment::clear_has_id() {
_has_bits_[0] &= ~0x00000001u;
}
void LaneSegment::clear_id() {
id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_id();
}
const ::std::string& LaneSegment::id() const {
// @@protoc_insertion_point(field_get:apollo.routing.LaneSegment.id)
return id_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void LaneSegment::set_id(const ::std::string& value) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:apollo.routing.LaneSegment.id)
}
void LaneSegment::set_id(const char* value) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:apollo.routing.LaneSegment.id)
}
void LaneSegment::set_id(const char* value, size_t size) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:apollo.routing.LaneSegment.id)
}
::std::string* LaneSegment::mutable_id() {
set_has_id();
// @@protoc_insertion_point(field_mutable:apollo.routing.LaneSegment.id)
return id_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* LaneSegment::release_id() {
// @@protoc_insertion_point(field_release:apollo.routing.LaneSegment.id)
clear_has_id();
return id_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void LaneSegment::set_allocated_id(::std::string* id) {
if (id != NULL) {
set_has_id();
} else {
clear_has_id();
}
id_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), id);
// @@protoc_insertion_point(field_set_allocated:apollo.routing.LaneSegment.id)
}
// optional double start_s = 2;
bool LaneSegment::has_start_s() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
void LaneSegment::set_has_start_s() {
_has_bits_[0] |= 0x00000002u;
}
void LaneSegment::clear_has_start_s() {
_has_bits_[0] &= ~0x00000002u;
}
void LaneSegment::clear_start_s() {
start_s_ = 0;
clear_has_start_s();
}
double LaneSegment::start_s() const {
// @@protoc_insertion_point(field_get:apollo.routing.LaneSegment.start_s)
return start_s_;
}
void LaneSegment::set_start_s(double value) {
set_has_start_s();
start_s_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.LaneSegment.start_s)
}
// optional double end_s = 3;
bool LaneSegment::has_end_s() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
void LaneSegment::set_has_end_s() {
_has_bits_[0] |= 0x00000004u;
}
void LaneSegment::clear_has_end_s() {
_has_bits_[0] &= ~0x00000004u;
}
void LaneSegment::clear_end_s() {
end_s_ = 0;
clear_has_end_s();
}
double LaneSegment::end_s() const {
// @@protoc_insertion_point(field_get:apollo.routing.LaneSegment.end_s)
return end_s_;
}
void LaneSegment::set_end_s(double value) {
set_has_end_s();
end_s_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.LaneSegment.end_s)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RoutingRequest::kHeaderFieldNumber;
const int RoutingRequest::kWaypointFieldNumber;
const int RoutingRequest::kBlacklistedLaneFieldNumber;
const int RoutingRequest::kBlacklistedRoadFieldNumber;
const int RoutingRequest::kBroadcastFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RoutingRequest::RoutingRequest()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.RoutingRequest)
}
void RoutingRequest::InitAsDefaultInstance() {
header_ = const_cast< ::apollo::common::Header*>(&::apollo::common::Header::default_instance());
}
RoutingRequest::RoutingRequest(const RoutingRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.RoutingRequest)
}
void RoutingRequest::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
header_ = NULL;
broadcast_ = true;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
RoutingRequest::~RoutingRequest() {
// @@protoc_insertion_point(destructor:apollo.routing.RoutingRequest)
SharedDtor();
}
void RoutingRequest::SharedDtor() {
if (this != default_instance_) {
delete header_;
}
}
void RoutingRequest::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* RoutingRequest::descriptor() {
protobuf_AssignDescriptorsOnce();
return RoutingRequest_descriptor_;
}
const RoutingRequest& RoutingRequest::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
RoutingRequest* RoutingRequest::default_instance_ = NULL;
RoutingRequest* RoutingRequest::New(::google::protobuf::Arena* arena) const {
RoutingRequest* n = new RoutingRequest;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void RoutingRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.RoutingRequest)
if (_has_bits_[0 / 32] & 17u) {
if (has_header()) {
if (header_ != NULL) header_->::apollo::common::Header::Clear();
}
broadcast_ = true;
}
waypoint_.Clear();
blacklisted_lane_.Clear();
blacklisted_road_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool RoutingRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.RoutingRequest)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .apollo.common.Header header = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_header()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_waypoint;
break;
}
// repeated .apollo.routing.LaneWaypoint waypoint = 2;
case 2: {
if (tag == 18) {
parse_waypoint:
DO_(input->IncrementRecursionDepth());
parse_loop_waypoint:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_waypoint()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_waypoint;
if (input->ExpectTag(26)) goto parse_loop_blacklisted_lane;
input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .apollo.routing.LaneSegment blacklisted_lane = 3;
case 3: {
if (tag == 26) {
DO_(input->IncrementRecursionDepth());
parse_loop_blacklisted_lane:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_blacklisted_lane()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_loop_blacklisted_lane;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectTag(34)) goto parse_blacklisted_road;
break;
}
// repeated string blacklisted_road = 4;
case 4: {
if (tag == 34) {
parse_blacklisted_road:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_blacklisted_road()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->blacklisted_road(this->blacklisted_road_size() - 1).data(),
this->blacklisted_road(this->blacklisted_road_size() - 1).length(),
::google::protobuf::internal::WireFormat::PARSE,
"apollo.routing.RoutingRequest.blacklisted_road");
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_blacklisted_road;
if (input->ExpectTag(40)) goto parse_broadcast;
break;
}
// optional bool broadcast = 5 [default = true];
case 5: {
if (tag == 40) {
parse_broadcast:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &broadcast_)));
set_has_broadcast();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.RoutingRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.RoutingRequest)
return false;
#undef DO_
}
void RoutingRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.RoutingRequest)
// optional .apollo.common.Header header = 1;
if (has_header()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->header_, output);
}
// repeated .apollo.routing.LaneWaypoint waypoint = 2;
for (unsigned int i = 0, n = this->waypoint_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->waypoint(i), output);
}
// repeated .apollo.routing.LaneSegment blacklisted_lane = 3;
for (unsigned int i = 0, n = this->blacklisted_lane_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->blacklisted_lane(i), output);
}
// repeated string blacklisted_road = 4;
for (int i = 0; i < this->blacklisted_road_size(); i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->blacklisted_road(i).data(), this->blacklisted_road(i).length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.RoutingRequest.blacklisted_road");
::google::protobuf::internal::WireFormatLite::WriteString(
4, this->blacklisted_road(i), output);
}
// optional bool broadcast = 5 [default = true];
if (has_broadcast()) {
::google::protobuf::internal::WireFormatLite::WriteBool(5, this->broadcast(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.RoutingRequest)
}
::google::protobuf::uint8* RoutingRequest::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.RoutingRequest)
// optional .apollo.common.Header header = 1;
if (has_header()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->header_, false, target);
}
// repeated .apollo.routing.LaneWaypoint waypoint = 2;
for (unsigned int i = 0, n = this->waypoint_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, this->waypoint(i), false, target);
}
// repeated .apollo.routing.LaneSegment blacklisted_lane = 3;
for (unsigned int i = 0, n = this->blacklisted_lane_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, this->blacklisted_lane(i), false, target);
}
// repeated string blacklisted_road = 4;
for (int i = 0; i < this->blacklisted_road_size(); i++) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->blacklisted_road(i).data(), this->blacklisted_road(i).length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.RoutingRequest.blacklisted_road");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(4, this->blacklisted_road(i), target);
}
// optional bool broadcast = 5 [default = true];
if (has_broadcast()) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->broadcast(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.RoutingRequest)
return target;
}
int RoutingRequest::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.RoutingRequest)
int total_size = 0;
if (_has_bits_[0 / 32] & 17u) {
// optional .apollo.common.Header header = 1;
if (has_header()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->header_);
}
// optional bool broadcast = 5 [default = true];
if (has_broadcast()) {
total_size += 1 + 1;
}
}
// repeated .apollo.routing.LaneWaypoint waypoint = 2;
total_size += 1 * this->waypoint_size();
for (int i = 0; i < this->waypoint_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->waypoint(i));
}
// repeated .apollo.routing.LaneSegment blacklisted_lane = 3;
total_size += 1 * this->blacklisted_lane_size();
for (int i = 0; i < this->blacklisted_lane_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->blacklisted_lane(i));
}
// repeated string blacklisted_road = 4;
total_size += 1 * this->blacklisted_road_size();
for (int i = 0; i < this->blacklisted_road_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->blacklisted_road(i));
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void RoutingRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.RoutingRequest)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const RoutingRequest* source =
::google::protobuf::internal::DynamicCastToGenerated<const RoutingRequest>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.RoutingRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.RoutingRequest)
MergeFrom(*source);
}
}
void RoutingRequest::MergeFrom(const RoutingRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.RoutingRequest)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
waypoint_.MergeFrom(from.waypoint_);
blacklisted_lane_.MergeFrom(from.blacklisted_lane_);
blacklisted_road_.MergeFrom(from.blacklisted_road_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_header()) {
mutable_header()->::apollo::common::Header::MergeFrom(from.header());
}
if (from.has_broadcast()) {
set_broadcast(from.broadcast());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void RoutingRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.RoutingRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RoutingRequest::CopyFrom(const RoutingRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.RoutingRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RoutingRequest::IsInitialized() const {
return true;
}
void RoutingRequest::Swap(RoutingRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void RoutingRequest::InternalSwap(RoutingRequest* other) {
std::swap(header_, other->header_);
waypoint_.UnsafeArenaSwap(&other->waypoint_);
blacklisted_lane_.UnsafeArenaSwap(&other->blacklisted_lane_);
blacklisted_road_.UnsafeArenaSwap(&other->blacklisted_road_);
std::swap(broadcast_, other->broadcast_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata RoutingRequest::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = RoutingRequest_descriptor_;
metadata.reflection = RoutingRequest_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// RoutingRequest
// optional .apollo.common.Header header = 1;
bool RoutingRequest::has_header() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void RoutingRequest::set_has_header() {
_has_bits_[0] |= 0x00000001u;
}
void RoutingRequest::clear_has_header() {
_has_bits_[0] &= ~0x00000001u;
}
void RoutingRequest::clear_header() {
if (header_ != NULL) header_->::apollo::common::Header::Clear();
clear_has_header();
}
const ::apollo::common::Header& RoutingRequest::header() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingRequest.header)
return header_ != NULL ? *header_ : *default_instance_->header_;
}
::apollo::common::Header* RoutingRequest::mutable_header() {
set_has_header();
if (header_ == NULL) {
header_ = new ::apollo::common::Header;
}
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingRequest.header)
return header_;
}
::apollo::common::Header* RoutingRequest::release_header() {
// @@protoc_insertion_point(field_release:apollo.routing.RoutingRequest.header)
clear_has_header();
::apollo::common::Header* temp = header_;
header_ = NULL;
return temp;
}
void RoutingRequest::set_allocated_header(::apollo::common::Header* header) {
delete header_;
header_ = header;
if (header) {
set_has_header();
} else {
clear_has_header();
}
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoutingRequest.header)
}
// repeated .apollo.routing.LaneWaypoint waypoint = 2;
int RoutingRequest::waypoint_size() const {
return waypoint_.size();
}
void RoutingRequest::clear_waypoint() {
waypoint_.Clear();
}
const ::apollo::routing::LaneWaypoint& RoutingRequest::waypoint(int index) const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingRequest.waypoint)
return waypoint_.Get(index);
}
::apollo::routing::LaneWaypoint* RoutingRequest::mutable_waypoint(int index) {
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingRequest.waypoint)
return waypoint_.Mutable(index);
}
::apollo::routing::LaneWaypoint* RoutingRequest::add_waypoint() {
// @@protoc_insertion_point(field_add:apollo.routing.RoutingRequest.waypoint)
return waypoint_.Add();
}
::google::protobuf::RepeatedPtrField< ::apollo::routing::LaneWaypoint >*
RoutingRequest::mutable_waypoint() {
// @@protoc_insertion_point(field_mutable_list:apollo.routing.RoutingRequest.waypoint)
return &waypoint_;
}
const ::google::protobuf::RepeatedPtrField< ::apollo::routing::LaneWaypoint >&
RoutingRequest::waypoint() const {
// @@protoc_insertion_point(field_list:apollo.routing.RoutingRequest.waypoint)
return waypoint_;
}
// repeated .apollo.routing.LaneSegment blacklisted_lane = 3;
int RoutingRequest::blacklisted_lane_size() const {
return blacklisted_lane_.size();
}
void RoutingRequest::clear_blacklisted_lane() {
blacklisted_lane_.Clear();
}
const ::apollo::routing::LaneSegment& RoutingRequest::blacklisted_lane(int index) const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingRequest.blacklisted_lane)
return blacklisted_lane_.Get(index);
}
::apollo::routing::LaneSegment* RoutingRequest::mutable_blacklisted_lane(int index) {
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingRequest.blacklisted_lane)
return blacklisted_lane_.Mutable(index);
}
::apollo::routing::LaneSegment* RoutingRequest::add_blacklisted_lane() {
// @@protoc_insertion_point(field_add:apollo.routing.RoutingRequest.blacklisted_lane)
return blacklisted_lane_.Add();
}
::google::protobuf::RepeatedPtrField< ::apollo::routing::LaneSegment >*
RoutingRequest::mutable_blacklisted_lane() {
// @@protoc_insertion_point(field_mutable_list:apollo.routing.RoutingRequest.blacklisted_lane)
return &blacklisted_lane_;
}
const ::google::protobuf::RepeatedPtrField< ::apollo::routing::LaneSegment >&
RoutingRequest::blacklisted_lane() const {
// @@protoc_insertion_point(field_list:apollo.routing.RoutingRequest.blacklisted_lane)
return blacklisted_lane_;
}
// repeated string blacklisted_road = 4;
int RoutingRequest::blacklisted_road_size() const {
return blacklisted_road_.size();
}
void RoutingRequest::clear_blacklisted_road() {
blacklisted_road_.Clear();
}
const ::std::string& RoutingRequest::blacklisted_road(int index) const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingRequest.blacklisted_road)
return blacklisted_road_.Get(index);
}
::std::string* RoutingRequest::mutable_blacklisted_road(int index) {
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingRequest.blacklisted_road)
return blacklisted_road_.Mutable(index);
}
void RoutingRequest::set_blacklisted_road(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:apollo.routing.RoutingRequest.blacklisted_road)
blacklisted_road_.Mutable(index)->assign(value);
}
void RoutingRequest::set_blacklisted_road(int index, const char* value) {
blacklisted_road_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:apollo.routing.RoutingRequest.blacklisted_road)
}
void RoutingRequest::set_blacklisted_road(int index, const char* value, size_t size) {
blacklisted_road_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:apollo.routing.RoutingRequest.blacklisted_road)
}
::std::string* RoutingRequest::add_blacklisted_road() {
// @@protoc_insertion_point(field_add_mutable:apollo.routing.RoutingRequest.blacklisted_road)
return blacklisted_road_.Add();
}
void RoutingRequest::add_blacklisted_road(const ::std::string& value) {
blacklisted_road_.Add()->assign(value);
// @@protoc_insertion_point(field_add:apollo.routing.RoutingRequest.blacklisted_road)
}
void RoutingRequest::add_blacklisted_road(const char* value) {
blacklisted_road_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:apollo.routing.RoutingRequest.blacklisted_road)
}
void RoutingRequest::add_blacklisted_road(const char* value, size_t size) {
blacklisted_road_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:apollo.routing.RoutingRequest.blacklisted_road)
}
const ::google::protobuf::RepeatedPtrField< ::std::string>&
RoutingRequest::blacklisted_road() const {
// @@protoc_insertion_point(field_list:apollo.routing.RoutingRequest.blacklisted_road)
return blacklisted_road_;
}
::google::protobuf::RepeatedPtrField< ::std::string>*
RoutingRequest::mutable_blacklisted_road() {
// @@protoc_insertion_point(field_mutable_list:apollo.routing.RoutingRequest.blacklisted_road)
return &blacklisted_road_;
}
// optional bool broadcast = 5 [default = true];
bool RoutingRequest::has_broadcast() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
void RoutingRequest::set_has_broadcast() {
_has_bits_[0] |= 0x00000010u;
}
void RoutingRequest::clear_has_broadcast() {
_has_bits_[0] &= ~0x00000010u;
}
void RoutingRequest::clear_broadcast() {
broadcast_ = true;
clear_has_broadcast();
}
bool RoutingRequest::broadcast() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingRequest.broadcast)
return broadcast_;
}
void RoutingRequest::set_broadcast(bool value) {
set_has_broadcast();
broadcast_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.RoutingRequest.broadcast)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Measurement::kDistanceFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Measurement::Measurement()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.Measurement)
}
void Measurement::InitAsDefaultInstance() {
}
Measurement::Measurement(const Measurement& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.Measurement)
}
void Measurement::SharedCtor() {
_cached_size_ = 0;
distance_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
Measurement::~Measurement() {
// @@protoc_insertion_point(destructor:apollo.routing.Measurement)
SharedDtor();
}
void Measurement::SharedDtor() {
if (this != default_instance_) {
}
}
void Measurement::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Measurement::descriptor() {
protobuf_AssignDescriptorsOnce();
return Measurement_descriptor_;
}
const Measurement& Measurement::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
Measurement* Measurement::default_instance_ = NULL;
Measurement* Measurement::New(::google::protobuf::Arena* arena) const {
Measurement* n = new Measurement;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Measurement::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.Measurement)
distance_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool Measurement::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.Measurement)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional double distance = 1;
case 1: {
if (tag == 9) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &distance_)));
set_has_distance();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.Measurement)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.Measurement)
return false;
#undef DO_
}
void Measurement::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.Measurement)
// optional double distance = 1;
if (has_distance()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->distance(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.Measurement)
}
::google::protobuf::uint8* Measurement::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.Measurement)
// optional double distance = 1;
if (has_distance()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->distance(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.Measurement)
return target;
}
int Measurement::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.Measurement)
int total_size = 0;
// optional double distance = 1;
if (has_distance()) {
total_size += 1 + 8;
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Measurement::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.Measurement)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const Measurement* source =
::google::protobuf::internal::DynamicCastToGenerated<const Measurement>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.Measurement)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.Measurement)
MergeFrom(*source);
}
}
void Measurement::MergeFrom(const Measurement& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.Measurement)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_distance()) {
set_distance(from.distance());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void Measurement::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.Measurement)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Measurement::CopyFrom(const Measurement& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.Measurement)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Measurement::IsInitialized() const {
return true;
}
void Measurement::Swap(Measurement* other) {
if (other == this) return;
InternalSwap(other);
}
void Measurement::InternalSwap(Measurement* other) {
std::swap(distance_, other->distance_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Measurement::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = Measurement_descriptor_;
metadata.reflection = Measurement_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Measurement
// optional double distance = 1;
bool Measurement::has_distance() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void Measurement::set_has_distance() {
_has_bits_[0] |= 0x00000001u;
}
void Measurement::clear_has_distance() {
_has_bits_[0] &= ~0x00000001u;
}
void Measurement::clear_distance() {
distance_ = 0;
clear_has_distance();
}
double Measurement::distance() const {
// @@protoc_insertion_point(field_get:apollo.routing.Measurement.distance)
return distance_;
}
void Measurement::set_distance(double value) {
set_has_distance();
distance_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.Measurement.distance)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Passage::kSegmentFieldNumber;
const int Passage::kCanExitFieldNumber;
const int Passage::kChangeLaneTypeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Passage::Passage()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.Passage)
}
void Passage::InitAsDefaultInstance() {
}
Passage::Passage(const Passage& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.Passage)
}
void Passage::SharedCtor() {
_cached_size_ = 0;
can_exit_ = false;
change_lane_type_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
Passage::~Passage() {
// @@protoc_insertion_point(destructor:apollo.routing.Passage)
SharedDtor();
}
void Passage::SharedDtor() {
if (this != default_instance_) {
}
}
void Passage::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Passage::descriptor() {
protobuf_AssignDescriptorsOnce();
return Passage_descriptor_;
}
const Passage& Passage::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
Passage* Passage::default_instance_ = NULL;
Passage* Passage::New(::google::protobuf::Arena* arena) const {
Passage* n = new Passage;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Passage::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.Passage)
#if defined(__clang__)
#define ZR_HELPER_(f) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(Passage, f) \
_Pragma("clang diagnostic pop")
#else
#define ZR_HELPER_(f) reinterpret_cast<char*>(\
&reinterpret_cast<Passage*>(16)->f)
#endif
#define ZR_(first, last) do {\
::memset(&first, 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
ZR_(can_exit_, change_lane_type_);
#undef ZR_HELPER_
#undef ZR_
segment_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool Passage::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.Passage)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .apollo.routing.LaneSegment segment = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_segment:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_segment()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_segment;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectTag(16)) goto parse_can_exit;
break;
}
// optional bool can_exit = 2;
case 2: {
if (tag == 16) {
parse_can_exit:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &can_exit_)));
set_has_can_exit();
} else {
goto handle_unusual;
}
if (input->ExpectTag(24)) goto parse_change_lane_type;
break;
}
// optional .apollo.routing.ChangeLaneType change_lane_type = 3 [default = FORWARD];
case 3: {
if (tag == 24) {
parse_change_lane_type:
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
if (::apollo::routing::ChangeLaneType_IsValid(value)) {
set_change_lane_type(static_cast< ::apollo::routing::ChangeLaneType >(value));
} else {
mutable_unknown_fields()->AddVarint(3, value);
}
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.Passage)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.Passage)
return false;
#undef DO_
}
void Passage::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.Passage)
// repeated .apollo.routing.LaneSegment segment = 1;
for (unsigned int i = 0, n = this->segment_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->segment(i), output);
}
// optional bool can_exit = 2;
if (has_can_exit()) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->can_exit(), output);
}
// optional .apollo.routing.ChangeLaneType change_lane_type = 3 [default = FORWARD];
if (has_change_lane_type()) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
3, this->change_lane_type(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.Passage)
}
::google::protobuf::uint8* Passage::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.Passage)
// repeated .apollo.routing.LaneSegment segment = 1;
for (unsigned int i = 0, n = this->segment_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, this->segment(i), false, target);
}
// optional bool can_exit = 2;
if (has_can_exit()) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->can_exit(), target);
}
// optional .apollo.routing.ChangeLaneType change_lane_type = 3 [default = FORWARD];
if (has_change_lane_type()) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
3, this->change_lane_type(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.Passage)
return target;
}
int Passage::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.Passage)
int total_size = 0;
if (_has_bits_[1 / 32] & 6u) {
// optional bool can_exit = 2;
if (has_can_exit()) {
total_size += 1 + 1;
}
// optional .apollo.routing.ChangeLaneType change_lane_type = 3 [default = FORWARD];
if (has_change_lane_type()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->change_lane_type());
}
}
// repeated .apollo.routing.LaneSegment segment = 1;
total_size += 1 * this->segment_size();
for (int i = 0; i < this->segment_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->segment(i));
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Passage::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.Passage)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const Passage* source =
::google::protobuf::internal::DynamicCastToGenerated<const Passage>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.Passage)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.Passage)
MergeFrom(*source);
}
}
void Passage::MergeFrom(const Passage& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.Passage)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
segment_.MergeFrom(from.segment_);
if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) {
if (from.has_can_exit()) {
set_can_exit(from.can_exit());
}
if (from.has_change_lane_type()) {
set_change_lane_type(from.change_lane_type());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void Passage::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.Passage)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Passage::CopyFrom(const Passage& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.Passage)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Passage::IsInitialized() const {
return true;
}
void Passage::Swap(Passage* other) {
if (other == this) return;
InternalSwap(other);
}
void Passage::InternalSwap(Passage* other) {
segment_.UnsafeArenaSwap(&other->segment_);
std::swap(can_exit_, other->can_exit_);
std::swap(change_lane_type_, other->change_lane_type_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Passage::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = Passage_descriptor_;
metadata.reflection = Passage_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Passage
// repeated .apollo.routing.LaneSegment segment = 1;
int Passage::segment_size() const {
return segment_.size();
}
void Passage::clear_segment() {
segment_.Clear();
}
const ::apollo::routing::LaneSegment& Passage::segment(int index) const {
// @@protoc_insertion_point(field_get:apollo.routing.Passage.segment)
return segment_.Get(index);
}
::apollo::routing::LaneSegment* Passage::mutable_segment(int index) {
// @@protoc_insertion_point(field_mutable:apollo.routing.Passage.segment)
return segment_.Mutable(index);
}
::apollo::routing::LaneSegment* Passage::add_segment() {
// @@protoc_insertion_point(field_add:apollo.routing.Passage.segment)
return segment_.Add();
}
::google::protobuf::RepeatedPtrField< ::apollo::routing::LaneSegment >*
Passage::mutable_segment() {
// @@protoc_insertion_point(field_mutable_list:apollo.routing.Passage.segment)
return &segment_;
}
const ::google::protobuf::RepeatedPtrField< ::apollo::routing::LaneSegment >&
Passage::segment() const {
// @@protoc_insertion_point(field_list:apollo.routing.Passage.segment)
return segment_;
}
// optional bool can_exit = 2;
bool Passage::has_can_exit() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
void Passage::set_has_can_exit() {
_has_bits_[0] |= 0x00000002u;
}
void Passage::clear_has_can_exit() {
_has_bits_[0] &= ~0x00000002u;
}
void Passage::clear_can_exit() {
can_exit_ = false;
clear_has_can_exit();
}
bool Passage::can_exit() const {
// @@protoc_insertion_point(field_get:apollo.routing.Passage.can_exit)
return can_exit_;
}
void Passage::set_can_exit(bool value) {
set_has_can_exit();
can_exit_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.Passage.can_exit)
}
// optional .apollo.routing.ChangeLaneType change_lane_type = 3 [default = FORWARD];
bool Passage::has_change_lane_type() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
void Passage::set_has_change_lane_type() {
_has_bits_[0] |= 0x00000004u;
}
void Passage::clear_has_change_lane_type() {
_has_bits_[0] &= ~0x00000004u;
}
void Passage::clear_change_lane_type() {
change_lane_type_ = 0;
clear_has_change_lane_type();
}
::apollo::routing::ChangeLaneType Passage::change_lane_type() const {
// @@protoc_insertion_point(field_get:apollo.routing.Passage.change_lane_type)
return static_cast< ::apollo::routing::ChangeLaneType >(change_lane_type_);
}
void Passage::set_change_lane_type(::apollo::routing::ChangeLaneType value) {
assert(::apollo::routing::ChangeLaneType_IsValid(value));
set_has_change_lane_type();
change_lane_type_ = value;
// @@protoc_insertion_point(field_set:apollo.routing.Passage.change_lane_type)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RoadSegment::kIdFieldNumber;
const int RoadSegment::kPassageFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RoadSegment::RoadSegment()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.RoadSegment)
}
void RoadSegment::InitAsDefaultInstance() {
}
RoadSegment::RoadSegment(const RoadSegment& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.RoadSegment)
}
void RoadSegment::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
RoadSegment::~RoadSegment() {
// @@protoc_insertion_point(destructor:apollo.routing.RoadSegment)
SharedDtor();
}
void RoadSegment::SharedDtor() {
id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != default_instance_) {
}
}
void RoadSegment::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* RoadSegment::descriptor() {
protobuf_AssignDescriptorsOnce();
return RoadSegment_descriptor_;
}
const RoadSegment& RoadSegment::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
RoadSegment* RoadSegment::default_instance_ = NULL;
RoadSegment* RoadSegment::New(::google::protobuf::Arena* arena) const {
RoadSegment* n = new RoadSegment;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void RoadSegment::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.RoadSegment)
if (has_id()) {
id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
passage_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool RoadSegment::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.RoadSegment)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string id = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_id()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::PARSE,
"apollo.routing.RoadSegment.id");
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_passage;
break;
}
// repeated .apollo.routing.Passage passage = 2;
case 2: {
if (tag == 18) {
parse_passage:
DO_(input->IncrementRecursionDepth());
parse_loop_passage:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_passage()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_passage;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.RoadSegment)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.RoadSegment)
return false;
#undef DO_
}
void RoadSegment::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.RoadSegment)
// optional string id = 1;
if (has_id()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.RoadSegment.id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->id(), output);
}
// repeated .apollo.routing.Passage passage = 2;
for (unsigned int i = 0, n = this->passage_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->passage(i), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.RoadSegment)
}
::google::protobuf::uint8* RoadSegment::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.RoadSegment)
// optional string id = 1;
if (has_id()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->id().data(), this->id().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"apollo.routing.RoadSegment.id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->id(), target);
}
// repeated .apollo.routing.Passage passage = 2;
for (unsigned int i = 0, n = this->passage_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, this->passage(i), false, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.RoadSegment)
return target;
}
int RoadSegment::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.RoadSegment)
int total_size = 0;
// optional string id = 1;
if (has_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->id());
}
// repeated .apollo.routing.Passage passage = 2;
total_size += 1 * this->passage_size();
for (int i = 0; i < this->passage_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->passage(i));
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void RoadSegment::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.RoadSegment)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const RoadSegment* source =
::google::protobuf::internal::DynamicCastToGenerated<const RoadSegment>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.RoadSegment)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.RoadSegment)
MergeFrom(*source);
}
}
void RoadSegment::MergeFrom(const RoadSegment& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.RoadSegment)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
passage_.MergeFrom(from.passage_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_id()) {
set_has_id();
id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.id_);
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void RoadSegment::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.RoadSegment)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RoadSegment::CopyFrom(const RoadSegment& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.RoadSegment)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RoadSegment::IsInitialized() const {
return true;
}
void RoadSegment::Swap(RoadSegment* other) {
if (other == this) return;
InternalSwap(other);
}
void RoadSegment::InternalSwap(RoadSegment* other) {
id_.Swap(&other->id_);
passage_.UnsafeArenaSwap(&other->passage_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata RoadSegment::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = RoadSegment_descriptor_;
metadata.reflection = RoadSegment_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// RoadSegment
// optional string id = 1;
bool RoadSegment::has_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void RoadSegment::set_has_id() {
_has_bits_[0] |= 0x00000001u;
}
void RoadSegment::clear_has_id() {
_has_bits_[0] &= ~0x00000001u;
}
void RoadSegment::clear_id() {
id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_id();
}
const ::std::string& RoadSegment::id() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoadSegment.id)
return id_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void RoadSegment::set_id(const ::std::string& value) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:apollo.routing.RoadSegment.id)
}
void RoadSegment::set_id(const char* value) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:apollo.routing.RoadSegment.id)
}
void RoadSegment::set_id(const char* value, size_t size) {
set_has_id();
id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:apollo.routing.RoadSegment.id)
}
::std::string* RoadSegment::mutable_id() {
set_has_id();
// @@protoc_insertion_point(field_mutable:apollo.routing.RoadSegment.id)
return id_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* RoadSegment::release_id() {
// @@protoc_insertion_point(field_release:apollo.routing.RoadSegment.id)
clear_has_id();
return id_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void RoadSegment::set_allocated_id(::std::string* id) {
if (id != NULL) {
set_has_id();
} else {
clear_has_id();
}
id_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), id);
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoadSegment.id)
}
// repeated .apollo.routing.Passage passage = 2;
int RoadSegment::passage_size() const {
return passage_.size();
}
void RoadSegment::clear_passage() {
passage_.Clear();
}
const ::apollo::routing::Passage& RoadSegment::passage(int index) const {
// @@protoc_insertion_point(field_get:apollo.routing.RoadSegment.passage)
return passage_.Get(index);
}
::apollo::routing::Passage* RoadSegment::mutable_passage(int index) {
// @@protoc_insertion_point(field_mutable:apollo.routing.RoadSegment.passage)
return passage_.Mutable(index);
}
::apollo::routing::Passage* RoadSegment::add_passage() {
// @@protoc_insertion_point(field_add:apollo.routing.RoadSegment.passage)
return passage_.Add();
}
::google::protobuf::RepeatedPtrField< ::apollo::routing::Passage >*
RoadSegment::mutable_passage() {
// @@protoc_insertion_point(field_mutable_list:apollo.routing.RoadSegment.passage)
return &passage_;
}
const ::google::protobuf::RepeatedPtrField< ::apollo::routing::Passage >&
RoadSegment::passage() const {
// @@protoc_insertion_point(field_list:apollo.routing.RoadSegment.passage)
return passage_;
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RoutingResponse::kHeaderFieldNumber;
const int RoutingResponse::kRoadFieldNumber;
const int RoutingResponse::kMeasurementFieldNumber;
const int RoutingResponse::kRoutingRequestFieldNumber;
const int RoutingResponse::kMapVersionFieldNumber;
const int RoutingResponse::kStatusFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RoutingResponse::RoutingResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:apollo.routing.RoutingResponse)
}
void RoutingResponse::InitAsDefaultInstance() {
header_ = const_cast< ::apollo::common::Header*>(&::apollo::common::Header::default_instance());
measurement_ = const_cast< ::apollo::routing::Measurement*>(&::apollo::routing::Measurement::default_instance());
routing_request_ = const_cast< ::apollo::routing::RoutingRequest*>(&::apollo::routing::RoutingRequest::default_instance());
status_ = const_cast< ::apollo::common::StatusPb*>(&::apollo::common::StatusPb::default_instance());
}
RoutingResponse::RoutingResponse(const RoutingResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:apollo.routing.RoutingResponse)
}
void RoutingResponse::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
header_ = NULL;
measurement_ = NULL;
routing_request_ = NULL;
map_version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
status_ = NULL;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
RoutingResponse::~RoutingResponse() {
// @@protoc_insertion_point(destructor:apollo.routing.RoutingResponse)
SharedDtor();
}
void RoutingResponse::SharedDtor() {
map_version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != default_instance_) {
delete header_;
delete measurement_;
delete routing_request_;
delete status_;
}
}
void RoutingResponse::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* RoutingResponse::descriptor() {
protobuf_AssignDescriptorsOnce();
return RoutingResponse_descriptor_;
}
const RoutingResponse& RoutingResponse::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_routing_2frouting_2eproto();
return *default_instance_;
}
RoutingResponse* RoutingResponse::default_instance_ = NULL;
RoutingResponse* RoutingResponse::New(::google::protobuf::Arena* arena) const {
RoutingResponse* n = new RoutingResponse;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void RoutingResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:apollo.routing.RoutingResponse)
if (_has_bits_[0 / 32] & 61u) {
if (has_header()) {
if (header_ != NULL) header_->::apollo::common::Header::Clear();
}
if (has_measurement()) {
if (measurement_ != NULL) measurement_->::apollo::routing::Measurement::Clear();
}
if (has_routing_request()) {
if (routing_request_ != NULL) routing_request_->::apollo::routing::RoutingRequest::Clear();
}
if (has_map_version()) {
map_version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
if (has_status()) {
if (status_ != NULL) status_->::apollo::common::StatusPb::Clear();
}
}
road_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool RoutingResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:apollo.routing.RoutingResponse)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .apollo.common.Header header = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_header()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_road;
break;
}
// repeated .apollo.routing.RoadSegment road = 2;
case 2: {
if (tag == 18) {
parse_road:
DO_(input->IncrementRecursionDepth());
parse_loop_road:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_road()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_road;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectTag(26)) goto parse_measurement;
break;
}
// optional .apollo.routing.Measurement measurement = 3;
case 3: {
if (tag == 26) {
parse_measurement:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_measurement()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_routing_request;
break;
}
// optional .apollo.routing.RoutingRequest routing_request = 4;
case 4: {
if (tag == 34) {
parse_routing_request:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_routing_request()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(42)) goto parse_map_version;
break;
}
// optional bytes map_version = 5;
case 5: {
if (tag == 42) {
parse_map_version:
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_map_version()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(50)) goto parse_status;
break;
}
// optional .apollo.common.StatusPb status = 6;
case 6: {
if (tag == 50) {
parse_status:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_status()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:apollo.routing.RoutingResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:apollo.routing.RoutingResponse)
return false;
#undef DO_
}
void RoutingResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:apollo.routing.RoutingResponse)
// optional .apollo.common.Header header = 1;
if (has_header()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->header_, output);
}
// repeated .apollo.routing.RoadSegment road = 2;
for (unsigned int i = 0, n = this->road_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->road(i), output);
}
// optional .apollo.routing.Measurement measurement = 3;
if (has_measurement()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->measurement_, output);
}
// optional .apollo.routing.RoutingRequest routing_request = 4;
if (has_routing_request()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *this->routing_request_, output);
}
// optional bytes map_version = 5;
if (has_map_version()) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
5, this->map_version(), output);
}
// optional .apollo.common.StatusPb status = 6;
if (has_status()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, *this->status_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:apollo.routing.RoutingResponse)
}
::google::protobuf::uint8* RoutingResponse::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:apollo.routing.RoutingResponse)
// optional .apollo.common.Header header = 1;
if (has_header()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->header_, false, target);
}
// repeated .apollo.routing.RoadSegment road = 2;
for (unsigned int i = 0, n = this->road_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, this->road(i), false, target);
}
// optional .apollo.routing.Measurement measurement = 3;
if (has_measurement()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->measurement_, false, target);
}
// optional .apollo.routing.RoutingRequest routing_request = 4;
if (has_routing_request()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, *this->routing_request_, false, target);
}
// optional bytes map_version = 5;
if (has_map_version()) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
5, this->map_version(), target);
}
// optional .apollo.common.StatusPb status = 6;
if (has_status()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
6, *this->status_, false, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:apollo.routing.RoutingResponse)
return target;
}
int RoutingResponse::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:apollo.routing.RoutingResponse)
int total_size = 0;
if (_has_bits_[0 / 32] & 61u) {
// optional .apollo.common.Header header = 1;
if (has_header()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->header_);
}
// optional .apollo.routing.Measurement measurement = 3;
if (has_measurement()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->measurement_);
}
// optional .apollo.routing.RoutingRequest routing_request = 4;
if (has_routing_request()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->routing_request_);
}
// optional bytes map_version = 5;
if (has_map_version()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->map_version());
}
// optional .apollo.common.StatusPb status = 6;
if (has_status()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->status_);
}
}
// repeated .apollo.routing.RoadSegment road = 2;
total_size += 1 * this->road_size();
for (int i = 0; i < this->road_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->road(i));
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void RoutingResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:apollo.routing.RoutingResponse)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const RoutingResponse* source =
::google::protobuf::internal::DynamicCastToGenerated<const RoutingResponse>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.routing.RoutingResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.routing.RoutingResponse)
MergeFrom(*source);
}
}
void RoutingResponse::MergeFrom(const RoutingResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:apollo.routing.RoutingResponse)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
road_.MergeFrom(from.road_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_header()) {
mutable_header()->::apollo::common::Header::MergeFrom(from.header());
}
if (from.has_measurement()) {
mutable_measurement()->::apollo::routing::Measurement::MergeFrom(from.measurement());
}
if (from.has_routing_request()) {
mutable_routing_request()->::apollo::routing::RoutingRequest::MergeFrom(from.routing_request());
}
if (from.has_map_version()) {
set_has_map_version();
map_version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.map_version_);
}
if (from.has_status()) {
mutable_status()->::apollo::common::StatusPb::MergeFrom(from.status());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void RoutingResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:apollo.routing.RoutingResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RoutingResponse::CopyFrom(const RoutingResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:apollo.routing.RoutingResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RoutingResponse::IsInitialized() const {
return true;
}
void RoutingResponse::Swap(RoutingResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void RoutingResponse::InternalSwap(RoutingResponse* other) {
std::swap(header_, other->header_);
road_.UnsafeArenaSwap(&other->road_);
std::swap(measurement_, other->measurement_);
std::swap(routing_request_, other->routing_request_);
map_version_.Swap(&other->map_version_);
std::swap(status_, other->status_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata RoutingResponse::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = RoutingResponse_descriptor_;
metadata.reflection = RoutingResponse_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// RoutingResponse
// optional .apollo.common.Header header = 1;
bool RoutingResponse::has_header() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void RoutingResponse::set_has_header() {
_has_bits_[0] |= 0x00000001u;
}
void RoutingResponse::clear_has_header() {
_has_bits_[0] &= ~0x00000001u;
}
void RoutingResponse::clear_header() {
if (header_ != NULL) header_->::apollo::common::Header::Clear();
clear_has_header();
}
const ::apollo::common::Header& RoutingResponse::header() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingResponse.header)
return header_ != NULL ? *header_ : *default_instance_->header_;
}
::apollo::common::Header* RoutingResponse::mutable_header() {
set_has_header();
if (header_ == NULL) {
header_ = new ::apollo::common::Header;
}
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingResponse.header)
return header_;
}
::apollo::common::Header* RoutingResponse::release_header() {
// @@protoc_insertion_point(field_release:apollo.routing.RoutingResponse.header)
clear_has_header();
::apollo::common::Header* temp = header_;
header_ = NULL;
return temp;
}
void RoutingResponse::set_allocated_header(::apollo::common::Header* header) {
delete header_;
header_ = header;
if (header) {
set_has_header();
} else {
clear_has_header();
}
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoutingResponse.header)
}
// repeated .apollo.routing.RoadSegment road = 2;
int RoutingResponse::road_size() const {
return road_.size();
}
void RoutingResponse::clear_road() {
road_.Clear();
}
const ::apollo::routing::RoadSegment& RoutingResponse::road(int index) const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingResponse.road)
return road_.Get(index);
}
::apollo::routing::RoadSegment* RoutingResponse::mutable_road(int index) {
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingResponse.road)
return road_.Mutable(index);
}
::apollo::routing::RoadSegment* RoutingResponse::add_road() {
// @@protoc_insertion_point(field_add:apollo.routing.RoutingResponse.road)
return road_.Add();
}
::google::protobuf::RepeatedPtrField< ::apollo::routing::RoadSegment >*
RoutingResponse::mutable_road() {
// @@protoc_insertion_point(field_mutable_list:apollo.routing.RoutingResponse.road)
return &road_;
}
const ::google::protobuf::RepeatedPtrField< ::apollo::routing::RoadSegment >&
RoutingResponse::road() const {
// @@protoc_insertion_point(field_list:apollo.routing.RoutingResponse.road)
return road_;
}
// optional .apollo.routing.Measurement measurement = 3;
bool RoutingResponse::has_measurement() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
void RoutingResponse::set_has_measurement() {
_has_bits_[0] |= 0x00000004u;
}
void RoutingResponse::clear_has_measurement() {
_has_bits_[0] &= ~0x00000004u;
}
void RoutingResponse::clear_measurement() {
if (measurement_ != NULL) measurement_->::apollo::routing::Measurement::Clear();
clear_has_measurement();
}
const ::apollo::routing::Measurement& RoutingResponse::measurement() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingResponse.measurement)
return measurement_ != NULL ? *measurement_ : *default_instance_->measurement_;
}
::apollo::routing::Measurement* RoutingResponse::mutable_measurement() {
set_has_measurement();
if (measurement_ == NULL) {
measurement_ = new ::apollo::routing::Measurement;
}
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingResponse.measurement)
return measurement_;
}
::apollo::routing::Measurement* RoutingResponse::release_measurement() {
// @@protoc_insertion_point(field_release:apollo.routing.RoutingResponse.measurement)
clear_has_measurement();
::apollo::routing::Measurement* temp = measurement_;
measurement_ = NULL;
return temp;
}
void RoutingResponse::set_allocated_measurement(::apollo::routing::Measurement* measurement) {
delete measurement_;
measurement_ = measurement;
if (measurement) {
set_has_measurement();
} else {
clear_has_measurement();
}
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoutingResponse.measurement)
}
// optional .apollo.routing.RoutingRequest routing_request = 4;
bool RoutingResponse::has_routing_request() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
void RoutingResponse::set_has_routing_request() {
_has_bits_[0] |= 0x00000008u;
}
void RoutingResponse::clear_has_routing_request() {
_has_bits_[0] &= ~0x00000008u;
}
void RoutingResponse::clear_routing_request() {
if (routing_request_ != NULL) routing_request_->::apollo::routing::RoutingRequest::Clear();
clear_has_routing_request();
}
const ::apollo::routing::RoutingRequest& RoutingResponse::routing_request() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingResponse.routing_request)
return routing_request_ != NULL ? *routing_request_ : *default_instance_->routing_request_;
}
::apollo::routing::RoutingRequest* RoutingResponse::mutable_routing_request() {
set_has_routing_request();
if (routing_request_ == NULL) {
routing_request_ = new ::apollo::routing::RoutingRequest;
}
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingResponse.routing_request)
return routing_request_;
}
::apollo::routing::RoutingRequest* RoutingResponse::release_routing_request() {
// @@protoc_insertion_point(field_release:apollo.routing.RoutingResponse.routing_request)
clear_has_routing_request();
::apollo::routing::RoutingRequest* temp = routing_request_;
routing_request_ = NULL;
return temp;
}
void RoutingResponse::set_allocated_routing_request(::apollo::routing::RoutingRequest* routing_request) {
delete routing_request_;
routing_request_ = routing_request;
if (routing_request) {
set_has_routing_request();
} else {
clear_has_routing_request();
}
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoutingResponse.routing_request)
}
// optional bytes map_version = 5;
bool RoutingResponse::has_map_version() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
void RoutingResponse::set_has_map_version() {
_has_bits_[0] |= 0x00000010u;
}
void RoutingResponse::clear_has_map_version() {
_has_bits_[0] &= ~0x00000010u;
}
void RoutingResponse::clear_map_version() {
map_version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_map_version();
}
const ::std::string& RoutingResponse::map_version() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingResponse.map_version)
return map_version_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void RoutingResponse::set_map_version(const ::std::string& value) {
set_has_map_version();
map_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:apollo.routing.RoutingResponse.map_version)
}
void RoutingResponse::set_map_version(const char* value) {
set_has_map_version();
map_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:apollo.routing.RoutingResponse.map_version)
}
void RoutingResponse::set_map_version(const void* value, size_t size) {
set_has_map_version();
map_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:apollo.routing.RoutingResponse.map_version)
}
::std::string* RoutingResponse::mutable_map_version() {
set_has_map_version();
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingResponse.map_version)
return map_version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* RoutingResponse::release_map_version() {
// @@protoc_insertion_point(field_release:apollo.routing.RoutingResponse.map_version)
clear_has_map_version();
return map_version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void RoutingResponse::set_allocated_map_version(::std::string* map_version) {
if (map_version != NULL) {
set_has_map_version();
} else {
clear_has_map_version();
}
map_version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), map_version);
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoutingResponse.map_version)
}
// optional .apollo.common.StatusPb status = 6;
bool RoutingResponse::has_status() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
void RoutingResponse::set_has_status() {
_has_bits_[0] |= 0x00000020u;
}
void RoutingResponse::clear_has_status() {
_has_bits_[0] &= ~0x00000020u;
}
void RoutingResponse::clear_status() {
if (status_ != NULL) status_->::apollo::common::StatusPb::Clear();
clear_has_status();
}
const ::apollo::common::StatusPb& RoutingResponse::status() const {
// @@protoc_insertion_point(field_get:apollo.routing.RoutingResponse.status)
return status_ != NULL ? *status_ : *default_instance_->status_;
}
::apollo::common::StatusPb* RoutingResponse::mutable_status() {
set_has_status();
if (status_ == NULL) {
status_ = new ::apollo::common::StatusPb;
}
// @@protoc_insertion_point(field_mutable:apollo.routing.RoutingResponse.status)
return status_;
}
::apollo::common::StatusPb* RoutingResponse::release_status() {
// @@protoc_insertion_point(field_release:apollo.routing.RoutingResponse.status)
clear_has_status();
::apollo::common::StatusPb* temp = status_;
status_ = NULL;
return temp;
}
void RoutingResponse::set_allocated_status(::apollo::common::StatusPb* status) {
delete status_;
status_ = status;
if (status) {
set_has_status();
} else {
clear_has_status();
}
// @@protoc_insertion_point(field_set_allocated:apollo.routing.RoutingResponse.status)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace routing
} // namespace apollo
// @@protoc_insertion_point(global_scope)
| 34.880868
| 125
| 0.711731
|
racestart
|
4b9686a3e5a95572d2db9aa9018c540c4c34bdef
| 3,505
|
hpp
|
C++
|
lib/audiodev/AudioSubmix.hpp
|
Austint30/boo
|
e9b2c5f96c4d48e57ca5b8eb0aa41504f4a81672
|
[
"MIT"
] | 7
|
2016-04-16T04:37:59.000Z
|
2022-02-01T12:39:04.000Z
|
lib/audiodev/AudioSubmix.hpp
|
Jcw87/boo
|
c4bb325d059eb032c48a72a99a0b3f0a419d8017
|
[
"MIT"
] | 8
|
2016-07-13T03:20:04.000Z
|
2021-06-30T05:07:10.000Z
|
lib/audiodev/AudioSubmix.hpp
|
Jcw87/boo
|
c4bb325d059eb032c48a72a99a0b3f0a419d8017
|
[
"MIT"
] | 11
|
2016-04-16T04:40:46.000Z
|
2022-02-06T04:23:17.000Z
|
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <list>
#include <mutex>
#include <unordered_map>
#include <vector>
#include "boo/audiodev/IAudioSubmix.hpp"
#include "lib/audiodev/Common.hpp"
#if defined(__x86_64__) || defined(_M_AMD64)
#include <immintrin.h>
#elif defined(__aarch64__) || defined(_M_ARM64)
#define __SSE__ 1
#include "sse2neon.h"
#endif
struct AudioUnitVoiceEngine;
struct VSTVoiceEngine;
struct WAVOutVoiceEngine;
namespace boo {
class BaseAudioVoiceEngine;
class AudioVoice;
struct AudioVoiceEngineMixInfo;
/* Output gains for each mix-send/channel */
class AudioSubmix : public ListNode<AudioSubmix, BaseAudioVoiceEngine*, IAudioSubmix> {
friend class BaseAudioVoiceEngine;
friend class AudioVoiceMono;
friend class AudioVoiceStereo;
friend struct WASAPIAudioVoiceEngine;
friend struct ::AudioUnitVoiceEngine;
friend struct ::VSTVoiceEngine;
friend struct ::WAVOutVoiceEngine;
/* Mixer-engine relationships */
int m_busId;
bool m_mainOut;
/* Callback (effect source, optional) */
IAudioSubmixCallback* m_cb;
/* Slew state for output gains */
size_t m_slewFrames = 0;
size_t m_curSlewFrame = 0;
/* Output gains for each mix-send/channel */
std::unordered_map<IAudioSubmix*, std::array<float, 2>> m_sendGains;
/* Temporary scratch buffers for accumulating submix audio */
std::vector<int16_t> m_scratch16;
std::vector<int32_t> m_scratch32;
std::vector<float> m_scratchFlt;
template <typename T>
std::vector<T>& _getScratch();
/* Override scratch buffers with alternate destination */
int16_t* m_redirect16 = nullptr;
int32_t* m_redirect32 = nullptr;
float* m_redirectFlt = nullptr;
template <typename T>
T*& _getRedirect();
/* C3-linearization support (to mitigate a potential diamond problem on 'clever' submix routes) */
bool _isDirectDependencyOf(AudioSubmix* send);
std::list<AudioSubmix*> _linearizeC3();
static bool _mergeC3(std::list<AudioSubmix*>& output, std::vector<std::list<AudioSubmix*>>& lists);
/* Fill scratch buffers with silence for new mix cycle */
template <typename T>
void _zeroFill();
/* Receive audio from a single voice / submix */
template <typename T>
T* _getMergeBuf(size_t frames);
/* Mix scratch buffers into sends */
template <typename T>
size_t _pumpAndMix(size_t frames);
void _resetOutputSampleRate();
public:
static AudioSubmix*& _getHeadPtr(BaseAudioVoiceEngine* head);
static std::unique_lock<std::recursive_mutex> _getHeadLock(BaseAudioVoiceEngine* head);
AudioSubmix(BaseAudioVoiceEngine& root, IAudioSubmixCallback* cb, int busId, bool mainOut);
~AudioSubmix() override;
void resetSendLevels() override;
void setSendLevel(IAudioSubmix* submix, float level, bool slew) override;
const AudioVoiceEngineMixInfo& mixInfo() const;
double getSampleRate() const override;
SubmixFormat getSampleFormat() const override;
};
template <>
inline std::vector<int16_t>& AudioSubmix::_getScratch() {
return m_scratch16;
}
template <>
inline std::vector<int32_t>& AudioSubmix::_getScratch() {
return m_scratch32;
}
template <>
inline std::vector<float>& AudioSubmix::_getScratch() {
return m_scratchFlt;
}
template <>
inline int16_t*& AudioSubmix::_getRedirect<int16_t>() {
return m_redirect16;
}
template <>
inline int32_t*& AudioSubmix::_getRedirect<int32_t>() {
return m_redirect32;
}
template <>
inline float*& AudioSubmix::_getRedirect<float>() {
return m_redirectFlt;
}
} // namespace boo
| 27.382813
| 101
| 0.750357
|
Austint30
|
4b976d2fcb1f0c18c51c96b07f21b0b3e0cd673f
| 6,711
|
cpp
|
C++
|
tests/stress_block_in.cpp
|
zsummer/fn_log
|
bc06f15c1b1500684dbe556ee36f10f5caad32a8
|
[
"MIT"
] | 4
|
2019-05-26T14:23:09.000Z
|
2019-05-31T08:19:54.000Z
|
tests/stress_block_in.cpp
|
zsummer/fn_log
|
bc06f15c1b1500684dbe556ee36f10f5caad32a8
|
[
"MIT"
] | null | null | null |
tests/stress_block_in.cpp
|
zsummer/fn_log
|
bc06f15c1b1500684dbe556ee36f10f5caad32a8
|
[
"MIT"
] | 1
|
2019-05-27T13:07:36.000Z
|
2019-05-27T13:07:36.000Z
|
#define FN_LOG_MAX_CHANNEL_SIZE 4
#define FN_LOG_MAX_LOG_SIZE 1000
#define FN_LOG_MAX_LOG_QUEUE_SIZE 100000
#include "fn_log.h"
static const std::string example_config_text =
R"----(
# 压测配表
# 0通道为异步模式写文件, info多线程文件输出和一个CATEGORY筛选的屏显输出
- channel: 0
sync: null
priority: trace
category: 0
category_extend: 0
-device: 0
disable: false
out_type: screen
priority: trace
category: 0
category_extend: 1
path: "./log/"
file: "$PNAME_00"
rollback: 4
limit_size: 100 m #only support M byte
-device: 1
disable: false
out_type: file
priority: debug
category: 1
category_extend: 1
path: "./log/"
file: "$PNAME_01"
rollback: 4
limit_size: 100 m #only support M byte
-device: 2
disable: false
out_type: file
priority: trace
category: 8
category_extend: 9
path: "./log/"
file: "$PNAME_02"
rollback: 4
limit_size: 100 m #only support M byte
-device: 3
disable: false
out_type: file
priority: trace
category: 3
category_extend: 3
path: "./log/"
file: "$PNAME_03"
rollback: 4
limit_size: 100 m #only support M byte
-device: 4
disable: false
out_type: file
priority: trace
category_filter: 0, 4,5
path: "./log/"
file: "$PNAME_04"
rollback: 4
limit_size: 100 m #only support M byte
-device: 5
disable: false
out_type: file
priority: trace
category_filter: 4,5
identify_filter: 0,1,4,7,16,36,46
path: "./log/"
file: "$PNAME_05"
rollback: 4
limit_size: 100 m #only support M byte
-device: 6
disable: false
out_type: file
priority: trace
category_filter: 4,8
identify_filter: 0,1,4,7,16,36,46
path: "./log/"
file: "$PNAME_06"
rollback: 4
limit_size: 100 m #only support M byte
-device: 7
disable: false
out_type: file
priority: trace
identify: 6
identify_extend: 1
path: "./log/"
file: "$PNAME_07"
rollback: 4
limit_size: 100 m #only support M byte
-device: 8
disable: false
out_type: file
priority: trace
category: 0
category_extend: 1
identify: 6
identify_extend: 1
path: "./log/"
file: "$PNAME_08"
rollback: 4
limit_size: 100 m #only support M byte
-device: 9
disable: false
out_type: file
priority: trace
category: 9
category_extend: 10
identify: 9
identify_extend: 10
path: "./log/"
file: "$PNAME_09"
rollback: 4
limit_size: 100 m #only support M byte
-device: 10
disable: false
out_type: file
priority: trace
category: 9
category_extend: 10
identify: 69
identify_extend: 10
path: "./log/"
file: "$PNAME_10"
rollback: 4
limit_size: 100 m #only support M byte
-device: 11
disable: false
out_type: file
priority: trace
category: 9
category_extend: 10
identify: 19
identify_extend: 10
path: "./log/"
file: "$PNAME_11"
rollback: 4
limit_size: 100 m #only support M byte
-device: 12
disable: false
out_type: file
priority: debug
category: 9
category_extend: 10
identify: 999
identify_extend: 10
path: "./log/"
file: "$PNAME_12"
rollback: 4
limit_size: 100 m #only support M byte
-device: 13
disable: false
out_type: file
priority: trace
category: 9
category_extend: 10
identify: 9999
identify_extend: 10
path: "./log/"
file: "$PNAME_13"
rollback: 4
limit_size: 100 m #only support M byte
-device: 14
disable: false
out_type: file
priority: trace
category: 9
category_extend: 10
identify: 79
identify_extend: 10
path: "./log/"
file: "$PNAME_14"
rollback: 4
limit_size: 100 m #only support M byte
-device: 15
disable: false
out_type: file
priority: trace
category: 69
category_extend: 10
identify: 9
identify_extend: 10
path: "./log/"
file: "$PNAME_15"
rollback: 4
limit_size: 100 m #only support M byte
-device: 16
disable: false
out_type: file
priority: trace
category: 59
category_extend: 10
identify: 9
identify_extend: 10
path: "./log/"
file: "$PNAME_16"
rollback: 4
limit_size: 100 m #only support M byte
# 1 异步空
- channel: 1
# 2通道为同步写文件
- channel: 2
sync: sync #only support single thread
-device: 0
disable: false
out_type: file
file: "$PNAME_$YEAR"
rollback: 4
limit_size: 100 m #only support M byte
# 3通道为同步空
- channel: 3
sync: sync #only support single thread
)----";
std::string ChannelDesc(int channel_type)
{
switch (channel_type)
{
case FNLog::CHANNEL_ASYNC:
return "async thread write";
case FNLog::CHANNEL_SYNC:
return "sync write";
}
return "invalid channel";
}
#define Now() std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count()
int main(int argc, char *argv[])
{
int ret = FNLog::FastStartDefaultLogger(example_config_text);
if (ret != 0)
{
return ret;
}
//base test
if (true)
{
long long loop_count = 1000000;
double now = Now();
for (long long i = 0; i < loop_count; i++)
{
LogInfoStream(0, 1, 0) << "asdf" << i << ", " << 2.3 << "asdfasdffffffffffffffffffffffffffffffffffffffff";
}
LogAlarmStream(0, 0, 0) << "per log used " << (Now() - now) * 1000 * 1000 * 1000 / loop_count << "ns";
loop_count = 10000000;
now = Now();
for (long long i = 0; i < loop_count; i++)
{
LogTraceStream(0, 567, 986) << "asdf" << i << ", " << 2.3 << "asdfasdffffffffffffffffffffffffffffffffffffffff";
}
LogAlarmStream(0, 0, 0) << "per empty log used " << (Now() - now) * 1000 * 1000 * 1000 / loop_count << "ns";
}
LogAlarmStream(0, 0, 0) << "finish";
return 0;
}
| 24.582418
| 123
| 0.539711
|
zsummer
|
4b986d6e2451f9ffa3f6e16c208b0675734d5c4a
| 848
|
hpp
|
C++
|
tools/lib/completion_context_finder.hpp
|
stryku/cmakesl
|
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
|
[
"BSD-3-Clause"
] | 51
|
2019-05-06T01:33:34.000Z
|
2021-11-17T11:44:54.000Z
|
tools/lib/completion_context_finder.hpp
|
stryku/cmakesl
|
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
|
[
"BSD-3-Clause"
] | 191
|
2019-05-06T18:31:24.000Z
|
2020-06-19T06:48:06.000Z
|
tools/lib/completion_context_finder.hpp
|
stryku/cmakesl
|
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
|
[
"BSD-3-Clause"
] | 3
|
2019-10-12T21:03:29.000Z
|
2020-06-19T06:22:25.000Z
|
#pragma once
#include "common/source_location.hpp"
#include "completion_contextes.hpp"
#include "sema/sema_node_visitor.hpp"
#include <variant>
namespace cmsl::tools {
class completion_context_finder : public sema::empty_sema_node_visitor
{
public:
explicit completion_context_finder(unsigned absolute_position);
void visit(const sema::translation_unit_node& node) override;
void visit(const sema::function_node& node) override;
void visit(const sema::block_node& node) override;
void visit(const sema::class_node& node) override;
completion_context_t result() const;
private:
bool is_inside(const sema::sema_node& node) const;
bool is_before(const sema::sema_node& node) const;
bool is_pos_before_node_begin(const sema::sema_node& node) const;
private:
const source_location m_pos;
completion_context_t m_result;
};
}
| 26.5
| 70
| 0.787736
|
stryku
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.