blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
57728193633a6c999df24c20328ff6c9230d4e08
|
02286031c902ec71ac466d80e8bd58860eb7e2f2
|
/testing/client/helloworld_server.cc
|
1b7fe7d7b402e7193e3abd4048c4c3b63f300aa3
|
[
"MIT"
] |
permissive
|
hxzrx/grpc
|
0ced89977bc8eb142dc47c900da6c401e6638b3a
|
efa76f22e7782b27bce7885cad2b9d791d26449f
|
refs/heads/master
| 2023-08-12T00:06:24.682490
| 2021-10-12T19:57:29
| 2021-10-12T19:57:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,787
|
cc
|
helloworld_server.cc
|
// Copyright 2021 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <third_party/absl/flags/parse.h>
#include <absl/flags/flag.h>
#include <absl/strings/ascii.h>
#include <absl/strings/str_cat.h>
#include <grpc/grpc.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "testing/client/helloworld.grpc.pb.h"
using grpc::InsecureServerCredentials;
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::SslServerCredentials;
using grpc::SslServerCredentialsOptions;
using grpc::Status;
using testing::HelloReply;
using testing::HelloRequest;
using testing::grpc_gen::Greeter;
ABSL_FLAG(int32, port, 0 , "Port server listening on.");
ABSL_FLAG(std::string, auth_mechanism, "", "Authentication mechanism.");
ABSL_FLAG(std::string, root_cert_path, "", "Path to root certificates.");
ABSL_FLAG(std::string, private_key_path, "", "Path to private key.");
ABSL_FLAG(std::string, certificate_chain_path, "",
"Path to certificate chain.");
class GreeterServiceImpl final : public Greeter::Service {
Status SayHello(ServerContext* context, const HelloRequest* request,
HelloReply* reply) override {
reply->set_message(absl::StrCat("Hello ", request->name()));
return Status::OK;
}
Status SayHelloServerStream(ServerContext* context,
const HelloRequest* request,
ServerWriter<HelloReply>* stream)
override {
HelloReply reply = HelloReply();
for(int i = 0; i < request->num_responses(); i++) {
reply.set_message(absl::StrCat("Hello ", request->name(), i));
stream->Write(reply);
}
return ::grpc::Status::OK;
}
Status SayHelloClientStream(ServerContext* context,
ServerReader<HelloRequest>* stream,
HelloReply* reply)
override {
std::string reply_string = "Hello ";
HelloRequest request;
while (stream->Read(&request)) {
absl::StrAppend(&reply_string, request.name());
}
reply->set_message(reply_string);
return ::grpc::Status::OK;
}
Status SayHelloBidirectionalStream(
ServerContext* context,
ServerReaderWriter<HelloReply, HelloRequest>* stream)
override {
HelloRequest request;
while (stream->Read(&request)) {
HelloReply reply = HelloReply();
for(int i = 0; i < request.num_responses(); i++) {
reply.set_message(absl::StrCat("Hello ", request.name(), i));
stream->Write(reply);
}
}
return ::grpc::Status::OK;
}
};
std::string readFileIntoString(const std::string& path) {
std::ifstream input_file(path);
if (!input_file.is_open()) {
std::cerr << "Could not open the file - '" << path << "'" << std::endl;
}
return std::string((std::istreambuf_iterator<char>(input_file)),
std::istreambuf_iterator<char>());
}
bool fileExists(const std::string& path) {
std::ifstream f(path.c_str());
return f.good();
}
void RunServer() {
const int port = absl::GetFlag(FLAGS_port);
QCHECK(port > 0) << "Please specify a valid server port";
std::string server_address = absl::StrCat("localhost:", port);
GreeterServiceImpl service;
ServerBuilder builder;
std::shared_ptr<grpc::ServerCredentials> creds;
// Set up authentication mechanism (or lack therof) for the server.
std::string auth_mechanism = absl::GetFlag(FLAGS_auth_mechanism);
absl::AsciiStrToLower(&auth_mechanism);
absl::RemoveExtraAsciiWhitespace(&auth_mechanism);
if (auth_mechanism == "insecure") {
creds = grpc::InsecureServerCredentials();
} else if (auth_mechanism == "ssl") {
const std::string root_cert_path = absl::GetFlag(FLAGS_root_cert_path);
if (root_cert_path.empty() || !fileExists(root_cert_path)) {
std::cout << "A valid root certificate must be specified, got: '"
<< root_cert_path << "'" << std::endl;
return;
}
const std::string private_key_path = absl::GetFlag(FLAGS_private_key_path);
if (private_key_path.empty() || !fileExists(private_key_path)) {
std::cout << "A valid private key must be specified, got: '"
<< private_key_path << "'" << std::endl;
return;
}
const std::string cert_chain_path =
absl::GetFlag(FLAGS_certificate_chain_path);
if (cert_chain_path.empty() || !fileExists(cert_chain_path)) {
std::cout << "A valid certificate chain must be specified, got: '"
<< cert_chain_path << "'" << std::endl;
return;
}
grpc::SslServerCredentialsOptions ssl_opts;
ssl_opts.pem_root_certs = readFileIntoString(root_cert_path);
grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {
readFileIntoString(private_key_path),
readFileIntoString(cert_chain_path),
};
ssl_opts.pem_key_cert_pairs.push_back(pkcp);
creds = grpc::SslServerCredentials(ssl_opts);
} else {
std::cout << "A valid authentication mechanism must be specified, got: '"
<< auth_mechanism << "'" << std::endl;
return;
}
builder.AddListeningPort(server_address, creds);
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
RunServer();
return 0;
}
|
e128f2e552609f560d5966a988686ddcc0dad5ca
|
4c527fc7081ca81f55b4164bc2e423a2fe31f52d
|
/Person.h
|
a99f46f43fe45bedff526b3ccc56b439713869a0
|
[] |
no_license
|
hyunatic/yj
|
d2289bbe6cec2046fbe946d634f5d32a64d1bb8e
|
9abadb402700f1a03ef04001a39b5b1dcc4e9df9
|
refs/heads/master
| 2020-08-08T02:00:51.397841
| 2019-10-08T14:41:52
| 2019-10-08T14:41:52
| 213,669,518
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 245
|
h
|
Person.h
|
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#include <string>
class Person{
private:
std::string name;
int age;
public:
Person();
std::string getName();
void setName(std::string n);
};
#endif // PERSON_H_INCLUDED
|
e30d3c50ef6753e6d54ab383118e4d37f0372a1d
|
2a1b9b869bcd8596b9540e54a2b6efc827974fcf
|
/header/actor-zeta/make_message.hpp
|
4a5e815d4e5c740245a758eaed24232640e3bbf4
|
[] |
no_license
|
SergeiNA/actor-zeta
|
b8fffc4b26e88c18ebc2684319cedf85dac37561
|
d81d4cb484c9e4b43a93425ac1e8d204166620a6
|
refs/heads/master
| 2023-08-07T05:22:04.758151
| 2021-10-10T04:51:21
| 2021-10-10T04:51:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,936
|
hpp
|
make_message.hpp
|
#pragma once
// clang-format off
#include <actor-zeta/base/handler.hpp>
#include <actor-zeta/base/address.hpp>
#include <actor-zeta/base/message.hpp>
#include <actor-zeta/base/basic_actor.hpp>
#include <actor-zeta/base/supervisor.hpp>
#include <actor-zeta/impl/handler.ipp>
// clang-format on
namespace actor_zeta {
template<class T>
auto make_message_ptr(base::address_t sender_, T name) -> base::message* {
return new base::message(std::move(sender_), std::forward<T>(name));
}
template<class T, typename Arg>
auto make_message_ptr(base::address_t sender_, T name, Arg&& arg) -> base::message* {
return new base::message(std::move(sender_), std::forward<T>(name), std::move(detail::any(std::forward<type_traits::decay_t<Arg>>(arg))));
}
template<class T, typename... Args>
auto make_message_ptr(base::address_t sender_, T name, Args&&... args) -> base::message* {
return new base::message(sender_, std::forward<T>(name), std::move(detail::any(std::tuple<type_traits::decay_t<Args>...>{std::forward<Args>(args)...})));
}
template<class T>
auto make_message(base::address_t sender_, T name) -> base::message_ptr {
return base::message_ptr(new base::message(std::move(sender_), std::forward<T>(name)));
}
template<class T, typename Arg>
auto make_message(base::address_t sender_, T name, Arg&& arg) -> base::message_ptr {
return base::message_ptr(new base::message(std::move(sender_), std::forward<T>(name), std::move(detail::any(std::forward<type_traits::decay_t<Arg>>(arg)))));
}
template<class T, typename... Args>
auto make_message(base::address_t sender_, T name, Args&&... args) -> base::message_ptr {
return base::message_ptr(new base::message(sender_, std::forward<T>(name), std::move(detail::any(std::tuple<type_traits::decay_t<Args>...>{std::forward<Args>(args)...}))));
}
} // namespace actor_zeta
|
2c3486bdb3cc30ce816c2407ea0ca052e377b5b9
|
7dde7a1fcf136635f5c90cbd82f565ef02d52516
|
/4_3.cpp
|
efbeba43f3a95d8c26d5786a99d3abe370365ae6
|
[] |
no_license
|
kimnahee1529/CppPracticalProblem
|
b49f8d540eeec181730cd7d714f4573a18fe12ed
|
14343c7fd4d2ced7036bc5a0994766f7cd937e94
|
refs/heads/master
| 2023-01-21T18:45:54.710856
| 2020-12-04T06:43:34
| 2020-12-04T06:43:34
| 274,610,900
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 479
|
cpp
|
4_3.cpp
|
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "문자열 입력>>";
string s;
getline(cin, s, '\n');
int index = s.find('a');
int num = 0;
for (int i = 0; i < s.length(); i++) {
if (s.at(i) == 'a')
num++;
}
cout << num;
}
/*int main() {
cout << "문자열 입력>>";
string s;
getline(cin, s, '\n');
int index = 0;
int num = 0;
for (int i= 0; index =='\n'; i++) {
if (s.find('a', index)==0)
num++;
}
cout << num;
}*/
|
d44bd8367e4fde5ee66ccd193a2437dccf57b206
|
a2e9639153e71dcf84d34b7349d69aa31b2eb678
|
/zBTLC/zBTLC/game_sa/List_c.h
|
306a4b4a8dfe889eed26691626ed5c2dcdcf723e
|
[] |
no_license
|
DaDj/GTA-BTLC
|
ade014b3d8dbb1ecce6422328be95631226cd6f4
|
15d60cb5d5f14291317235066d64a639fffaf3ea
|
refs/heads/master
| 2023-08-16T23:12:57.867204
| 2023-08-13T21:45:06
| 2023-08-13T21:45:06
| 83,485,003
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,484
|
h
|
List_c.h
|
#pragma once
#include "plbase/PluginBase_SA.h"
#include "ListItem_c.h"
class List_c
{
public:
ListItem_c *last;
ListItem_c *first;
unsigned int count;
List_c(void);
~List_c(void);
public:
/**
* Add new item to the head
*/
void AddItem(ListItem_c * pItem);
/**
* Remove given item from the list and decrease counter
*/
void RemoveItem(ListItem_c * pItem);
/**
* Get list head
*/
ListItem_c * GetHead(void);
/**
* Remove heading item and return it's pointer
*/
ListItem_c * RemoveHead(void);
/**
* Get next item in a list
*/
ListItem_c * GetNext(ListItem_c * pItem);
/**
* Get previous item
*/
ListItem_c * GetPrev(ListItem_c * pItem);
/**
* Get N-th item from list head/tail
*/
ListItem_c * GetItemOffset(bool bFromHead, int iOffset);
};
template <
typename ItemType
>
class TList_c : public List_c
{
public:
ItemType * GetHead(void) {
return static_cast<ItemType *>(List_c::GetHead());
}
ItemType * RemoveHead(void) {
return static_cast<ItemType *>(List_c::RemoveHead());
}
ItemType * GetNext(ItemType * pItem) {
return static_cast<ItemType *>(List_c::GetNext(pItem));
}
ItemType * GetPrev(ItemType * pItem) {
return static_cast<ItemType *>(List_c::GetPrev(pItem));
}
ItemType * GetItemOffset(bool bFromHead, int iOffset) {
return static_cast<ItemType *>(List_c::GetItemOffset(bFromHead, iOffset));
}
};
VALIDATE_SIZE(List_c, 0xC);
|
3f6697fd187c13b0fa82b8ac751e7458ab8c78a7
|
84f087b61e354c1ae22629b2f6d559fc45019316
|
/BJXTGU-NHF/Product.h
|
ddaf954bbcd93c36817482337949cb826cd3f5f4
|
[] |
no_license
|
annadudas/Groceries
|
fb3a928173dff0a7797ec2f7eab02f76841b0038
|
23d1ea43206dc99ac0f2e8db494d68d78c78b99e
|
refs/heads/main
| 2023-06-08T19:38:55.231938
| 2021-06-25T18:08:55
| 2021-06-25T18:08:55
| 380,311,530
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 592
|
h
|
Product.h
|
#pragma once
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Product
{
protected:
string productName_;
string label_;
int price_;
int rating_;
int isle_;
public:
string getProductName() { return productName_; }
int getPrice() { return price_; }
int getRating() { return rating_; }
int getIsle() { return isle_; }
Product(string productName, string label, int price, int rating, int isle) : productName_(productName), label_(label), price_(price), rating_(rating), isle_(isle) {};
virtual void print(std::ostream& os) = 0;
~Product();
};
|
d84e2cbaab9ce11107368139a2836438916db746
|
215cfe900d3fb8ccf6240989ad7c3a741708a926
|
/Renderer/Source/ResourceTypes/Lines.cpp
|
1d985a9b1285bb11d7d7639ef55f698a0d3c1c98
|
[] |
no_license
|
Jofuleous/Gyro
|
d6044072f7555f6f8f1c476655206bc246ed4472
|
84068ce88e1486d4d92d5702c230ce1dd4fa54ab
|
refs/heads/master
| 2021-01-01T19:42:16.543064
| 2015-08-11T02:36:38
| 2015-08-11T02:36:38
| 27,047,635
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,635
|
cpp
|
Lines.cpp
|
#include "Lines.h"
#include "../RenderDevices.h"
#include "../VertexDeclarations.h"
#include "../RenderManager.h"
#include "../Camera.h"
Lines::Lines( int i_maxLines )
{
m_maxVertices = i_maxLines * 4; // 8 vertices per line.
m_bufferSize = sizeof( g3DLineVertex ) * m_maxVertices;
m_currentVertices = 0;
m_currentLines = 0;
m_maxLines = i_maxLines;
m_lineVertices = (g3DLineVertex*) malloc( m_bufferSize );
//m_orthoLineVertices = (g3DLineVertex*) malloc( m_bufferSize );
m_maxIndices = i_maxLines * 6;
}
Lines::~Lines()
{
Cleanse( );
}
// todo: convert to shared matrix class?
bool Lines::AddLine( D3DXVECTOR3 p0, D3DXVECTOR3 p1, float startRadius, float endRadius, float aspect, D3DXCOLOR i_color )
{
// Check for overflow.
if ( m_currentVertices + 4 >= m_maxVertices )
return false;
m_lineVertices[m_currentVertices + 0] = g3DLineVertex(p0, p1, startRadius, endRadius, aspect, 1.0f, 0.0f, -1.0f, -1.0f, i_color);
m_lineVertices[m_currentVertices + 1] = g3DLineVertex(p0, p1, startRadius, endRadius, aspect, 1.0f, 0.0f, -1.0f, 1.0f, i_color);
m_lineVertices[m_currentVertices + 2] = g3DLineVertex(p0, p1, startRadius, endRadius, aspect, 0.0f, 1.0f, 0.0f, -1.0f, i_color);
m_lineVertices[m_currentVertices + 3] = g3DLineVertex(p0, p1, startRadius, endRadius, aspect, 0.0f, 1.0f, 0.0f, 1.0f, i_color);
m_currentVertices += 4; //8;
m_dirty = true; // we need to do a new memcpy.
return true;
}
bool Lines::Render( const D3DXMATRIX& matProj, const D3DXMATRIX& matView, const D3DXMATRIX& matWorld, int bZenable )
{
#ifdef _DEBUG
D3DPERF_EndEvent( );
D3DPERF_BeginEvent( D3DCOLOR_XRGB(255, 0, 0 ), L"DRAWING LINES");
#endif
if( m_currentVertices <= 0 )
return true;
if (m_dirty ) // Copy local vertex data into VB if it is new.
{
g3DLineVertex *pVerts = NULL;
m_pVBuff->Lock(0, 0, (void**)&pVerts, 0);
memcpy(pVerts, m_lineVertices, m_currentVertices * sizeof(g3DLineVertex));
m_pVBuff->Unlock();
m_dirty = false; //vert data isn't new anymore
}
HRESULT hr;
hr = g_RenderDevices.GetDevice()->SetVertexShader( m_vertexShader->rm_Reference.m_vertexShader );
//assert( SUCCEEDED( result ) );
hr = g_RenderDevices.GetDevice()->SetPixelShader( m_pixelShader->rm_Reference.m_pixelShader );
//assert( SUCCEEDED( result )
// Draw the lines.
//hr = g_RenderDevices.GetDevice()->SetIndices(m_pIBuff);
hr = g_RenderDevices.GetDevice()->SetIndices( m_pIBuff );
hr = g_RenderDevices.GetDevice()->SetStreamSource(0, m_pVBuff, 0, sizeof(g3DLineVertex));
hr = g_RenderDevices.GetDevice()->SetVertexDeclaration( m_vertexDeclaration );
//g_RenderDevices.GetDevice()->SetStreamSource( 0, 0, 0, 0 );
//g_RenderDevices.GetDevice()->SetVertexDeclaration( 0 );
// we're already in world coords, just pass in the view * projection
D3DXMATRIX matWorldViewProjection = g_RenderManager.GetCurrentScene()->GetCamera()->ViewTransform() * g_RenderManager.GetCurrentScene()->GetCamera()->ProjectionTransform();
D3DXHANDLE hTemp = m_vertexShader->rm_Reference.m_vertexShaderConstantTable->GetConstantByName( 0, "gWVP" );
if( hTemp != NULL )
hr = m_vertexShader->rm_Reference.m_vertexShaderConstantTable->SetMatrix(g_RenderDevices.GetDevice(), hTemp, &matWorldViewProjection);
else
assert( 0 );
//hr = g_RenderDevices.GetDevice()->SetRenderState(D3DRS_ZENABLE, false);
//m_pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); //this was just for debugging to make sure the tri's draw correctly
//Render
hr = g_RenderDevices.GetDevice()->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_currentVertices, 0, m_currentVertices / 2 );
//m_pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
return true;
}
void Lines::Cleanse( )
{
free( m_lineIndices );
free( m_lineVertices );
m_pVBuff->Release();
m_pIBuff->Release();
}
bool Lines::Reset( )
{
// set numbert of verts to zero and mark the buffer as dirty.
m_currentVertices = 0;
m_dirty = true;
return true;
}
bool Lines::OnResetDevice( )
{
//DebugBreak();
PixelShaderLoader pLoader;
m_pixelShader = ResourceManager<PixelShaderReference>::Load( "debugLinesPS.fp", &pLoader, false );
VertexShaderLoader loader;
m_vertexShader = ResourceManager<VertexShaderReference>::Load( "debugLinesVS.vp", &loader, false );
m_lineIndices = (unsigned __int16*) malloc( m_maxIndices * sizeof( unsigned __int16));
int index = 0;
for( int i = 0; i < m_maxLines; i++ )
{
m_lineIndices[ index++ ] = i * 4;
m_lineIndices[ index++ ] = i * 4 + 2;
m_lineIndices[ index++ ] = i * 4 + 3;
m_lineIndices[ index++ ] = i * 4;
m_lineIndices[ index++ ] = i * 4 + 3;
m_lineIndices[ index++ ] = i * 4 + 1;
}
//INITIALIZE INDEX BUFFER
D3DFORMAT format = D3DFMT_INDEX16;
HRESULT result = g_RenderDevices.GetDevice()->CreateIndexBuffer( m_maxIndices * sizeof( unsigned __int16), 0, format, D3DPOOL_DEFAULT,
&m_pIBuff, 0 );
//BEGIN INDEX READING PROCESS
UINT16* indices;
//LOCK INDEX BUFFER
unsigned int lockEntireBuffer = 0;
DWORD useDefaultLockingBehavior = 0;
result = m_pIBuff->Lock( lockEntireBuffer, lockEntireBuffer,
reinterpret_cast<void**>( &indices ), useDefaultLockingBehavior );
if ( FAILED( result ) )
{
//cs6963::LogMessage( "Failed to lock the index buffer" );
assert( 0 );
}
//FILL INDEX BUFFER
//indices = (UINT16*) malloc( indexBufferSize );
memcpy( indices, m_lineIndices, m_maxIndices );
//UNLOCK INDEX BUFFER
result = m_pIBuff->Unlock();
if ( FAILED( result ) )
{
// cs6963::LogMessage( "Failed to unlock the index buffer" );
assert( 0 );
}
DWORD usage = 0;
{
// Our code will only ever write to the buffer
usage |= D3DUSAGE_WRITEONLY;
// The type of vertex processing should match what was specified when the device interface was created
{
D3DDEVICE_CREATION_PARAMETERS deviceCreationParameters;
HRESULT result = g_RenderDevices.GetDevice()->GetCreationParameters( &deviceCreationParameters );
if ( SUCCEEDED( result ) )
{
DWORD vertexProcessingType = deviceCreationParameters.BehaviorFlags &
( D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MIXED_VERTEXPROCESSING | D3DCREATE_SOFTWARE_VERTEXPROCESSING );
usage |= ( vertexProcessingType != D3DCREATE_SOFTWARE_VERTEXPROCESSING ) ?
0 : D3DUSAGE_SOFTWAREPROCESSING;
}
else
{
assert( 0 );
return false;
}
}
}
result = g_RenderDevices.GetDevice()->CreateVertexBuffer( m_maxVertices * sizeof( g3DLineVertex ), usage, 0, D3DPOOL_DEFAULT,
&m_pVBuff, 0 );
result = g_RenderDevices.GetDevice()->CreateVertexDeclaration( s_gDebugLineVertexDecl, &m_vertexDeclaration );
if( !SUCCEEDED( result ) )
assert( 0 );
return true;
}
|
83315c5034d82d892a293dfeac5aaecf1ef85492
|
db1acaba57f9dfff34b175e808518a5ad0fb3d29
|
/LdFileManager/About.h
|
2b4b307e828bf5b2801af69e499b0e3c4aa8e43d
|
[] |
no_license
|
locustwei/Leadow
|
20157ed7141916361abe85b1a92206821b5a8509
|
c9fab13b67e3cc5219e1319adfb603a311bca863
|
refs/heads/master
| 2021-06-11T16:08:25.524759
| 2019-10-05T08:46:48
| 2019-10-05T08:46:48
| 140,794,910
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 510
|
h
|
About.h
|
#pragma once
class CAbout : public WindowImplBase
{
public:
CAbout(TCHAR* xmlSkin);
~CAbout();
DUI_DECLARE_MESSAGE_MAP()
protected:
LPCTSTR GetWindowClassName() const override;
void Notify(TNotifyUI& msg) override;
CDuiString GetSkinFile() override;
CDuiString GetSkinFolder() override;
void OnClick(TNotifyUI& msg) override;
void InitWindow() override;
private:
TCHAR* m_Skin;
virtual void OnSelectChanged(TNotifyUI &msg);
virtual void OnItemClick(TNotifyUI &msg);
};
|
7b0f7d91db578608a8c856054ea2e5f41eb5ca08
|
d634971e2c6b81d93090af1a66aa6f8f82e602d1
|
/include/easi/util/FunctionWrapper.h
|
376790c93f63b0d6bd1458c920ed605c17f0798f
|
[
"BSD-3-Clause"
] |
permissive
|
SeisSol/easi
|
5879278e39b5b0993ab476cf175be5d23a6b03d3
|
6c48c182609be681e896c37333ec98f997c0ac18
|
refs/heads/master
| 2023-08-31T14:44:41.975067
| 2023-08-22T07:59:41
| 2023-08-22T07:59:41
| 95,791,181
| 1
| 7
|
BSD-3-Clause
| 2023-08-22T07:59:42
| 2017-06-29T15:21:04
|
C++
|
UTF-8
|
C++
| false
| false
| 390
|
h
|
FunctionWrapper.h
|
#ifndef EASI_UTIL_FUNCTIONWRAPPER_H_
#define EASI_UTIL_FUNCTIONWRAPPER_H_
#ifdef EASI_USE_IMPALAJIT
#include <impalajit/types.hh>
namespace easi {
template <typename T> class Matrix;
typedef double (*function_wrapper_t)(dasm_gen_func, Matrix<double> const&, unsigned);
function_wrapper_t getFunctionWrapper(unsigned dimDomain);
} // namespace easi
#endif // EASI_USE_IMPALAJIT
#endif
|
510eeb107608d61232f252e66e093083f2bd2841
|
306c007e3b07f70b38d51edb34a885e176b64366
|
/Crystal.h
|
d83b0536ebba9010454e9177d1af952eed12ef75
|
[] |
no_license
|
raggimr/AnnProdAnn
|
a144b0e22ddcad54e7c9f8f2ca5128d01da31a9f
|
0be6978bb99879d711ecb02f508b07ec9cc19ab2
|
refs/heads/master
| 2021-01-10T18:31:10.350260
| 2015-10-20T15:37:05
| 2015-10-20T15:37:05
| 34,965,216
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,239
|
h
|
Crystal.h
|
#ifndef Crystal_h
#define Crystal_h
#define CRYSTAL_STATUS_BIT_USED 0
#define CRYSTAL_STATUS_BIT_SEED 1
class Crystal {
public :
Crystal(int ,int);
~Crystal();
public :
double GetEnergy() {return fEnergy;};
double GetTime() {return fTime;};
double GetCharge() {return fCharge;};
double SetEnergy(double e) { fEnergy=e; };
double SetTime(double t) { fTime=t; };
double SetCharge(double cha) { fCharge=cha; };
double GetXCenter() {return fXCenter;};
double GetYCenter() {return fYCenter;};
double GetZCenter() {return fZCenter;};
int GetXi() {return fXi;};
int GetYi() {return fYi;};
bool IsUsed() {return fStatus & (1 << CRYSTAL_STATUS_BIT_USED);};
bool IsSeed() {return fStatus & (1 << CRYSTAL_STATUS_BIT_SEED);};
void SetUsed() { fStatus |= (1 << CRYSTAL_STATUS_BIT_USED); };
void ResetUsed() { fStatus &= ~(1 << CRYSTAL_STATUS_BIT_USED); };
void SetSeed() { fStatus |= (1 << CRYSTAL_STATUS_BIT_SEED); };
void ResetSeed() { fStatus &= ~(1 << CRYSTAL_STATUS_BIT_SEED); };
void Print();
private:
int fXi;
int fYi;
int fStatus;
double fXCenter;
double fYCenter;
double fZCenter;
double fEnergy;
double fTime;
double fCharge;
};
#endif
|
67586e2de6e0113dc0875d850a77c92eca1f82ae
|
7e03cbf0d6e75ca4f0c3001d9976b6184eb7233d
|
/src/scene/vcI3S.cpp
|
a611c3e5736f533814574839c4408792c07d779b
|
[
"MIT"
] |
permissive
|
5l1v3r1/vaultclient
|
f946bb1f5e67653036bc0003aaf54bdf7dd5cc65
|
1c4213317a77a3a06a3de0fab3a329bf41de2550
|
refs/heads/master
| 2022-11-14T06:09:45.166681
| 2020-07-13T15:55:39
| 2020-07-13T15:55:39
| 279,716,508
| 1
| 0
|
MIT
| 2020-07-14T23:42:12
| 2020-07-14T23:42:11
| null |
UTF-8
|
C++
| false
| false
| 3,152
|
cpp
|
vcI3S.cpp
|
#include "vcI3S.h"
#include "vcState.h"
#include "vcStrings.h"
#include "vcRender.h"
#include "udPlatform.h"
#include "udStringUtil.h"
#include "imgui.h"
#include "imgui_ex/vcImGuiSimpleWidgets.h"
vcI3S::vcI3S(vcProject *pProject, vdkProjectNode *pNode, vcState *pProgramState) :
vcSceneItem(pProject, pNode, pProgramState),
m_pSceneRenderer(nullptr)
{
m_sceneMatrix = udDouble4x4::identity();
udResult result = vcSceneLayerRenderer_Create(&m_pSceneRenderer, pProgramState->pWorkerPool, pNode->pURI);
if (result == udR_OpenFailure)
result = vcSceneLayerRenderer_Create(&m_pSceneRenderer, pProgramState->pWorkerPool, udTempStr("%s%s", pProgramState->activeProject.pRelativeBase, pNode->pURI));
if (result == udR_Success)
{
m_loadStatus = vcSLS_Loaded;
udGeoZone *pInternalZone = vcSceneLayer_GetPreferredZone(m_pSceneRenderer->pSceneLayer);
if (pInternalZone != nullptr)
{
m_pPreferredProjection = udAllocType(udGeoZone, 1, udAF_Zero);
memcpy(m_pPreferredProjection, pInternalZone, sizeof(udGeoZone));
}
}
else
{
m_loadStatus = vcSLS_Failed;
}
}
vcI3S::~vcI3S()
{
vcSceneLayerRenderer_Destroy(&m_pSceneRenderer);
}
void vcI3S::OnNodeUpdate(vcState * /*pProgramState*/)
{
//TODO: This should come from m_pNode
}
void vcI3S::AddToScene(vcState * /*pProgramState*/, vcRenderData *pRenderData)
{
if (!m_visible || m_pSceneRenderer == nullptr) // Nothing to render
return;
vcRenderPolyInstance instance = {};
instance.renderType = vcRenderPolyInstance::RenderType_SceneLayer;
instance.pSceneLayer = m_pSceneRenderer;
instance.worldMat = m_sceneMatrix;
instance.pSceneItem = this;
instance.sceneItemInternalId = 0; // TODO: individual node picking
instance.selectable = true;
pRenderData->polyModels.PushBack(instance);
}
void vcI3S::ApplyDelta(vcState * /*pProgramState*/, const udDouble4x4 &delta)
{
m_sceneMatrix = delta * m_sceneMatrix;
}
void vcI3S::HandleSceneExplorerUI(vcState * /*pProgramState*/, size_t * /*pItemID*/)
{
ImGui::TextWrapped("Path: %s", m_pNode->pURI);
}
void vcI3S::HandleContextMenu(vcState * /*pProgramState*/)
{
ImGui::Separator();
if (ImGui::Selectable(vcString::Get("sceneExplorerResetPosition"), false))
{
m_sceneMatrix = udDouble4x4::identity();
}
}
void vcI3S::Cleanup(vcState * /*pProgramState*/)
{
vcSceneLayerRenderer_Destroy(&m_pSceneRenderer);
}
void vcI3S::ChangeProjection(const udGeoZone &newZone)
{
if (m_pSceneRenderer == nullptr)
return;
udGeoZone *pInternalZone = vcSceneLayer_GetPreferredZone(m_pSceneRenderer->pSceneLayer);
if (pInternalZone == nullptr)
return;
udDouble4x4 prevOrigin = udDouble4x4::translation(GetLocalSpacePivot());
udDouble4x4 newOffset = udGeoZone_TransformMatrix(prevOrigin, *pInternalZone, newZone);
m_sceneMatrix = newOffset * udInverse(prevOrigin);
}
udDouble3 vcI3S::GetLocalSpacePivot()
{
if (m_pSceneRenderer == nullptr)
return udDouble3::zero();
return vcSceneLayer_GetCenter(m_pSceneRenderer->pSceneLayer);
}
udDouble4x4 vcI3S::GetWorldSpaceMatrix()
{
return m_pSceneRenderer ? m_sceneMatrix : udDouble4x4::identity();
}
|
ed1c18e5af51b79d6e5cc24296e2020c51d407b7
|
bee278c871d76f1eebdabbf1de8fa11431873ca7
|
/ReENGINE/Source/Math/Rotator.hpp
|
7a8cd6d55ffa894b198de9aa284c47565472c31e
|
[] |
no_license
|
giovgiac/ReENGINE
|
cf48dbde50055b68fc22efd50343da25e528ab3b
|
70ab413b7a06d8750d636c9e1342267d2e911e8b
|
refs/heads/master
| 2023-04-17T20:46:19.572209
| 2021-04-26T02:00:28
| 2021-04-26T02:00:28
| 361,588,141
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 713
|
hpp
|
Rotator.hpp
|
/**
* Rotator.h
*
* Copyright (c) Giovanni Giacomo. All Rights Reserved.
*
*/
#pragma once
#include "Core/Debug/Assert.hpp"
namespace Re
{
namespace Math
{
/**
* @brief
*
*/
struct Rotator
{
f32 _pitch;
f32 _roll;
f32 _yaw;
/**
* @brief
*
*/
inline Rotator()
: _pitch(0.0f), _roll(0.0f), _yaw(0.0f) {}
/**
* @brief
*
* @param f32 InF:
*
*/
explicit inline Rotator(f32 f)
: _pitch(f), _roll(f), _yaw(f) {}
/**
* @brief
*
* @param f32 InX:
* @param f32 InY:
* @param f32 InZ:
*
*/
explicit inline Rotator(f32 pitch, f32 roll, f32 yaw)
: _pitch(pitch), _roll(roll), _yaw(yaw) {}
};
}
}
|
7abad5b472ae4a21157015d7471e0cf0b210b18d
|
f3f960032cfeb3c0909aecd4b06c544622fe0b75
|
/Spline/image.h
|
72096095d388cd3561de7bc1a34bea7cdec022b9
|
[] |
no_license
|
bulat2960/OlemskoyProgs
|
1678706c29b0b9c2067a2e4b778897a79411d1c1
|
3cf6dd74aec7472b7d620f05c840f695aaec1785
|
refs/heads/master
| 2020-06-09T06:56:27.058158
| 2019-06-23T21:06:45
| 2019-06-23T21:06:45
| 193,395,429
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,087
|
h
|
image.h
|
#ifndef IMAGE_H
#define IMAGE_H
#include <QtWidgets>
#include "computer.h"
class Image : public QWidget
{
Q_OBJECT
private:
int zoom = 1;
int prec = 100;
private:
QCheckBox* sp10button;
QCheckBox* sp21button;
QCheckBox* sp32button;
QTextBrowser* polyBrowser;
QTextBrowser* dataBrowser;
QTableWidget* table;
Computer* computer;
QVector<QVector<QPointF>> sp10data;
QVector<QVector<QPointF>> sp21data;
QVector<QVector<QPointF>> sp32data;
QVector<QPointF> funcData;
double sp10max;
double sp21max;
double sp32max;
public:
Image(QCheckBox* sp10button, QCheckBox* sp21button, QCheckBox* sp32button, QTextBrowser* polyBrowser, QTextBrowser* dataBrowser,
QTableWidget* table, Computer* computer);
void updateBrowserData();
public slots:
void paintEvent(QPaintEvent* event);
void fillErrorTable();
void clearErrorTable();
void doWork();
void changeZoom(int value);
void changePrec(int value);
};
#endif // IMAGE_H
|
d8a2d2d67656a7c1b209c116dbbf39ca08f88dd1
|
53487542f1d068b817b877d6b8f672c82e2bab96
|
/RtspServer/rtsp/h264_source.cpp
|
034cddd07796719da4ec5e106dc5fa4fdb63266f
|
[] |
no_license
|
z-h-s/NetworkThirdParty
|
e071c6b8e1fd6a9df9ffc403e77d11798ca38aaf
|
0169cb63756801d84c07ee91dd3614ef01700d88
|
refs/heads/master
| 2023-03-19T18:13:51.584510
| 2021-03-11T09:00:24
| 2021-03-11T09:00:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,959
|
cpp
|
h264_source.cpp
|
#if defined(WIN32) || defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "h264_source.h"
#include <cstdio>
#include <chrono>
#include "Base64.h"
#if defined(__linux) || defined(__linux__)
#include <sys/time.h>
#endif
using namespace micagent;
using namespace std;
h264_source::h264_source(uint32_t frameRate)
: m_frameRate(frameRate),m_send_counts(0)
{
m_payload = 96; // rtp负载类型
m_mediaType = H264;
m_clockRate = 90000;
}
media_frame_type h264_source::get_frame_type(uint8_t byte)
{
media_frame_type ret=FRAME_UNKNOWN;
int nalu_type=byte&0x1f;
switch (nalu_type) {
case 1:
ret=FRAME_P;
break;
case 5:
ret=FRAME_I;
break;
case 6:
ret=FRAME_SEI;
break;
case 7:
ret=FRAME_SPS;
break;
case 8:
ret=FRAME_PPS;
break;
default:
break;
}
return ret;
}
bool h264_source::check_frames(media_frame_type type, AVFrame frame,uint32_t offset,uint32_t frame_len)
{
bool ret=false;
do{
if(type==FRAME_UNKNOWN||frame_len==0)break;
auto frame_begin_ptr=frame.buffer.get()+offset;
if(type==FRAME_I){
//i
m_last_iframe.reset(new AVFrame(frame_len));
m_last_iframe->type=frame.type;
memcpy(m_last_iframe.get()->buffer.get(),frame_begin_ptr,frame_len);
m_send_counts=m_frameRate*2+2;
}
else if (type==FRAME_SPS) {
m_frame_sps.reset(new AVFrame(frame_len));
m_frame_sps->type=frame.type;
memcpy(m_frame_sps.get()->buffer.get(),frame_begin_ptr,frame_len);
m_send_counts=m_frameRate*2+2;
}
else if (type==FRAME_PPS) {
m_frame_pps.reset(new AVFrame(frame_len));
m_frame_pps->type=frame.type;
memcpy(m_frame_pps.get()->buffer.get(),frame_begin_ptr,frame_len);
}
else if (type==FRAME_SEI) {
m_last_sei.reset(new AVFrame(frame_len));
m_last_sei->type=frame.type;
memcpy(m_last_sei.get()->buffer.get(),frame_begin_ptr,frame_len);
}
else {
if(m_send_counts!=0)m_send_counts--;
if(m_send_counts==0){
break;
}
}
ret=true;
}while(0);
return ret;
}
shared_ptr<h264_source> h264_source::createNew(uint32_t frameRate)
{
return make_shared<h264_source>(frameRate);
}
h264_source::~h264_source()
{
}
string h264_source::getMediaDescription(uint16_t port)
{
char buf[100] = {0};
sprintf(buf, "m=video %hu RTP/AVP 96", port); // \r\nb=AS:2000
return string(buf);
}
string h264_source::getAttribute()
{
return string("a=rtpmap:96 H264/90000");
}
std::string h264_source::getAttributeFmtp()
{
string ret("");
do{
if(!m_frame_sps||!m_frame_pps)break;
// Set up the "a=fmtp:" SDP line for this stream:
shared_ptr<uint8_t>spsWEB(new uint8_t[m_frame_sps->size],std::default_delete<uint8_t[]>());
auto spsWEBSize = removeH264or5EmulationBytes(spsWEB, m_frame_sps->size, m_frame_sps->buffer, m_frame_sps->size);
if (spsWEBSize < 4) break;
uint32_t profileLevelId = (spsWEB.get()[1]<<16) | (spsWEB.get()[2]<<8) | spsWEB.get()[3];
auto sps_base64 = micagent::base64Encode(m_frame_sps->buffer.get() ,m_frame_sps->size);
auto pps_base64 = micagent::base64Encode(m_frame_pps->buffer.get() ,m_frame_pps->size);
char const* fmtpFmt =
"a=fmtp:%d packetization-mode=1"
";profile-level-id=%06X"
";sprop-parameter-sets=%s,%s\r\n";
unsigned fmtpFmtSize = strlen(fmtpFmt)
+ 3 /* max char len */
+ 6 /* 3 bytes in hex */
+ sps_base64.size() + pps_base64.size();
shared_ptr<char>fmtp(new char[fmtpFmtSize],std::default_delete<char[]>());
sprintf(fmtp.get(), fmtpFmt,
m_payload,
profileLevelId,
sps_base64.c_str(), pps_base64.c_str());
ret=fmtp.get();
}while(0);
return ret;
}
bool h264_source::handleFrame(MediaChannelId channelId, AVFrame frame)
{
auto start_pos=find_next_video_nal_pos(frame.buffer.get(),frame.size,0);
if(start_pos==frame.size)return false;
int safty_counts=6;
while ((safty_counts--)>0) {
auto type=this->get_frame_type(frame.buffer.get()[start_pos]);
uint32_t next_pos=frame.size;
if(type==FRAME_I||type==FRAME_P||type==FRAME_B){
}else {
next_pos=find_next_video_nal_pos(frame.buffer.get(),frame.size,start_pos+1);
}
frame.type=type;
uint8_t *frameBuf = frame.buffer.get()+start_pos;
uint32_t frameSize = next_pos-start_pos;
if(next_pos!=frame.size&&frameSize>=4)frameSize-=4;
if(!check_frames(type,frame,start_pos,frameSize))return true;
auto timestamp=getTimeStamp(frame.timestamp);
if (frameSize <= MAX_RTP_PAYLOAD_SIZE)
{
RtpPacket rtpPkt;
rtpPkt.type = frame.type;
rtpPkt.timestamp = timestamp;
rtpPkt.size = frameSize + 4 + RTP_HEADER_SIZE;
rtpPkt.last = 1;
memcpy(rtpPkt.data.get()+4+RTP_HEADER_SIZE, frameBuf, frameSize); // 预留12字节 rtp header
if (m_sendFrameCallback)
{
if(!m_sendFrameCallback(channelId, rtpPkt))return false;
}
}
else
{
char FU_A[2] = {0};
// 分包参考live555
FU_A[0] = (frameBuf[0] & 0xE0) | 28;
FU_A[1] = 0x80 | (frameBuf[0] & 0x1f);
frameBuf += 1;
frameSize -= 1;
while (frameSize + 2 > MAX_RTP_PAYLOAD_SIZE)
{
RtpPacket rtpPkt;
rtpPkt.type = frame.type;
rtpPkt.timestamp = timestamp;
rtpPkt.size = 4 + RTP_HEADER_SIZE + MAX_RTP_PAYLOAD_SIZE;
rtpPkt.last = 0;
rtpPkt.data.get()[RTP_HEADER_SIZE+4] = FU_A[0];
rtpPkt.data.get()[RTP_HEADER_SIZE+5] = FU_A[1];
memcpy(rtpPkt.data.get()+4+RTP_HEADER_SIZE+2, frameBuf, MAX_RTP_PAYLOAD_SIZE-2);
if (m_sendFrameCallback)
{
if(!m_sendFrameCallback(channelId, rtpPkt))return false;
}
frameBuf += MAX_RTP_PAYLOAD_SIZE - 2;
frameSize -= MAX_RTP_PAYLOAD_SIZE - 2;
FU_A[1] &= ~0x80;
}
{
RtpPacket rtpPkt;
rtpPkt.type = frame.type;
rtpPkt.timestamp = timestamp;
rtpPkt.size = 4 + RTP_HEADER_SIZE + 2 + frameSize;
rtpPkt.last = 1;
FU_A[1] |= 0x40;
rtpPkt.data.get()[RTP_HEADER_SIZE+4] = FU_A[0];
rtpPkt.data.get()[RTP_HEADER_SIZE+5] = FU_A[1];
memcpy(rtpPkt.data.get()+4+RTP_HEADER_SIZE+2, frameBuf, frameSize);
if (m_sendFrameCallback)
{
if(!m_sendFrameCallback(channelId, rtpPkt))return false;
}
}
}
if(next_pos>=frame.size)break;
start_pos=next_pos;
}
return true;
}
bool h264_source::handleGopCache(MediaChannelId channelid,shared_ptr<rtp_connection>connection)
{
if(m_frame_sps)
{
connection->set_got_gop();
queue<shared_ptr<AVFrame>>m_frame_queue;
if(m_frame_sps)m_frame_queue.push(m_frame_sps);
if(m_frame_pps)m_frame_queue.push(m_frame_pps);
if(m_last_sei)m_frame_queue.push(m_last_sei);
if(m_last_iframe)m_frame_queue.push(m_last_iframe);
auto timestamp=getTimeStamp(m_last_mill_recv_time);
while(!m_frame_queue.empty())
{
auto front=m_frame_queue.front();
uint8_t *frameBuf = front.get()->buffer.get();
uint32_t frameSize = front.get()->size;
if (frameSize <= MAX_RTP_PAYLOAD_SIZE)
{
RtpPacket rtpPkt;
rtpPkt.type = front->type;
rtpPkt.timestamp = timestamp;
rtpPkt.size = frameSize + 4 + RTP_HEADER_SIZE;
rtpPkt.last = 1;
memcpy(rtpPkt.data.get()+4+RTP_HEADER_SIZE, frameBuf, frameSize); // 预留 4字节TCP Header, 12字节 RTP Header
if(!connection->sendRtpPacket(channelid,rtpPkt))continue;
}
else
{
char FU_A[2] = {0};
// 分包参考live555
FU_A[0] = (frameBuf[0] & 0xE0) | 28;
FU_A[1] = 0x80 | (frameBuf[0] & 0x1f);
frameBuf += 1;
frameSize -= 1;
while (frameSize + 2 > MAX_RTP_PAYLOAD_SIZE)
{
RtpPacket rtpPkt;
rtpPkt.type = front->type;
rtpPkt.timestamp = timestamp;
rtpPkt.size = 4 + RTP_HEADER_SIZE + MAX_RTP_PAYLOAD_SIZE;
rtpPkt.last = 0;
rtpPkt.data.get()[RTP_HEADER_SIZE+4] = FU_A[0];
rtpPkt.data.get()[RTP_HEADER_SIZE+5] = FU_A[1];
memcpy(rtpPkt.data.get()+4+RTP_HEADER_SIZE+2, frameBuf, MAX_RTP_PAYLOAD_SIZE-2);
if(!connection->sendRtpPacket(channelid,rtpPkt))continue;
frameBuf += MAX_RTP_PAYLOAD_SIZE - 2;
frameSize -= MAX_RTP_PAYLOAD_SIZE - 2;
FU_A[1] &= ~0x80;
}
{
RtpPacket rtpPkt;
rtpPkt.type = front->type;
rtpPkt.timestamp = timestamp;
rtpPkt.size = 4 + RTP_HEADER_SIZE + 2 + frameSize;
rtpPkt.last = 1;
FU_A[1] |= 0x40;
rtpPkt.data.get()[RTP_HEADER_SIZE+4] = FU_A[0];
rtpPkt.data.get()[RTP_HEADER_SIZE+5] = FU_A[1];
memcpy(rtpPkt.data.get()+4+RTP_HEADER_SIZE+2, frameBuf, frameSize);
if(!connection->sendRtpPacket(channelid,rtpPkt))continue;
}
}
m_frame_queue.pop();
}
return true;
}
else {
return false;
}
}
uint32_t h264_source::getTimeStamp(int64_t mill_second)
{
if(m_last_mill_recv_time==0||mill_second==0)
{
auto timePoint = chrono::time_point_cast<chrono::milliseconds>(chrono::steady_clock::now());
m_last_mill_send_time=timePoint.time_since_epoch().count();
m_last_mill_recv_time=mill_second;
return (uint32_t)((m_last_mill_send_time) * 90);
}
else {
m_last_mill_send_time+=(mill_second-m_last_mill_recv_time);
m_last_mill_recv_time=mill_second;
return (uint32_t)((m_last_mill_send_time ) * 90);
}
}
|
51b3c9e2ae3769d63990e130503f46ce9b81b288
|
906aa4c5db4c63fbd7919fe86fb82a25e89d3a35
|
/src/SimpleHash.cpp
|
c33cc25c4b865753866eeb0f35af79ec7cbd1e88
|
[] |
no_license
|
khalefa-ow/indexing_prerelease
|
9a8f4d1bc7d8b7c6dc4f362a2d0ca26f3564d908
|
6aea650fccb001602d3300082c609cea539ce2ab
|
refs/heads/master
| 2022-01-30T10:05:21.473228
| 2016-09-29T19:21:09
| 2016-09-29T19:21:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,464
|
cpp
|
SimpleHash.cpp
|
/*
* Copyright 2012 Cornell Database Group
* 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 "SimpleHash.h"
using namespace PSimIndex;
const int SimpleHash::DEFAULT_TABLE_SIZE = 100;
void SimpleHash::insert(Point2D* key) {
// std::cout << "In insert: " << *key << " k = " << (key->id % tableSize) << std::endl;
// std::cout << "mySize: " << mySize << std::endl;
//vector<Point2D*>::iterator it;
mySize++;
//std::vector<Point2D*>* vec = vArray[(key->id % tableSize)];
int k = (key->id % tableSize);
Bucket* b = &(vArray[k]);
if(!setArray[k]) {
b->data = key;
b->next = NULL;
setArray[k] = true;
}
else {
Bucket* prev = b;
// std::cout << "Bucket b data "<< *b->data << std::endl;
while(b != NULL) {
// std::cout << "b->data" << *b->data << std::endl;
if(b->data->id == key->id) {
// std::cout << "in if" << std::endl;
b->data = key;
return;
}
prev = b;
b = b->next;
}
prev->next = new Bucket(key);
// std::cout << "allocating ";
// if(prev->next->next != NULL) {
// std::cout << " NOT NULL" << std::endl;
// }
// else {
// std::cout << " NULL" << std::endl;
// }
}
// std::cout << "After loops" << std::endl;
// for(int i = 0; i < vec->size(); i++) {
// if(key->id == vec->at(i)->id) {
// (*vec)[i] = key;
// return;
// }
// }
// vec->push_back(key);
}
void SimpleHash::erase(Point2D* key) {
// std::cout << "in erase" << std::endl;
int k = (key->id % tableSize);
Bucket* b = &vArray[k];
Bucket* prev = b;
if(!setArray[k]) {
return;
}
//Head matches
else if(key->id == b->data->id) {
Bucket* b2 = b->next;
b->data = b2->data;
b->next = b2->next;
delete b2;
mySize--;
return;
}
b = b->next;
while(b != NULL) {
if(key->id == b->data->id) {
if(b->next != NULL) {
prev->next = b->next;
}
else {
prev->next = NULL;
}
delete b;
mySize--;
return;
}
prev = b;
b = b->next;
}
// std::vector<Point2D*>* vec = vArray[(key->id % tableSize)];
// for(int i = 0; i < vec->size(); i++) {
// if(vec->at(i)->id == key->id) {
// //Point2D* tmp = vec->at(i);
// (*vec)[i] = vec->at(vec->size() - 1);
// vec->pop_back();
// mySize--;
// return;
// }
// }
}
bool SimpleHash::contains(Point2D* key) {
int k = (key->id % tableSize);
Bucket* b = &vArray[k];
//Bucket* prev = b;
if(!setArray[k]) {
return false;
}
while(b != NULL) {
if(key->id == b->data->id) {
return true;
}
b = b->next;
}
return false;
// std::vector<Point2D*>* vec = vArray[(key->id % tableSize)];
// for(int i = 0; i < vec->size(); i++) {
// if(key->id == vec->at(i)->id) {
// return true;
// }
// }
// return false;
}
int SimpleHash::size() {
return mySize;
}
SimpleHash::SimpleHash() {
// std::cout << "in SimpleHash" << std::endl;
tableSize = DEFAULT_TABLE_SIZE;
setArray = (bool*) calloc(sizeof(bool), tableSize);
vArray = new Bucket[tableSize];
for(int i = 0; i < tableSize; i++) {
if(vArray[i].next != NULL) {
std::cout << "NOT NULL!!!" << std::endl;
}
}
//vArray = new std::vector<Point2D*>*[tableSize];
// for(int i = 0; i < tableSize; i++) {
// vArray[i] = new std::vector<Point2D*>();
// }
mySize = 0;
}
void SimpleHash::clear() {
//std::cout << "in clear" << std::endl;
double avgSize = 0;
int maxSize = -1;
int minSize = std::numeric_limits<int>::max();
for(int i = 0; i < tableSize; i++) {
Bucket* b = &vArray[i];
// int vSize = vArray[i]->size();
// if(vSize > maxSize) {
// maxSize = vSize;
// }
// if(vSize < minSize) {
// minSize = vSize;
// }
// avgSize += vSize;
while(b->next != NULL) {
Bucket* b2 = b->next;
b->next = b2->next;
delete b2;
}
//vArray[i]->clear();
}
memset(setArray, 0, tableSize * sizeof(bool));
//std::cout << "Avg Size / Bucket: " << (avgSize / tableSize) << " minSize: " << minSize
//<< " maxSize: " << maxSize << std::endl;
mySize = 0;
}
SimpleHash::~SimpleHash() {
// std::cout << "in destructor" << std::endl;
clear();
// for(int i = 0; i < tableSize; i++) {
// delete vArray[i];
// }
delete [] vArray;
}
|
be0aa45e94cecc51557e80384f9093906a0d7ce1
|
b32bb708c4b7aa34275e8715c6e6f12028757355
|
/SurgSim/Input/InputComponent.cpp
|
a49314804e72e7382df03d755207bb2a75f4e69e
|
[
"Bitstream-Vera",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
paulnovo/opensurgsim
|
b3fdad8b53a772dc6e8d2dad7492120a8d502f4c
|
39ff317a59afe9ccc81c1884b81916d4612cc3d4
|
refs/heads/master
| 2020-12-13T20:54:45.571406
| 2016-01-05T14:04:20
| 2016-01-05T14:04:20
| 47,847,864
| 0
| 0
| null | 2015-12-11T19:53:57
| 2015-12-11T19:53:57
| null |
UTF-8
|
C++
| false
| false
| 3,731
|
cpp
|
InputComponent.cpp
|
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Framework/LockedContainer.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Input/InputConsumerInterface.h"
namespace SurgSim
{
namespace Input
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Input::InputComponent, InputComponent);
/// An input consumer monitors device and signal state update
class InputConsumer: public InputConsumerInterface
{
public:
/// Constructor
InputConsumer()
{
}
/// Destructor
virtual ~InputConsumer()
{
}
/// Handle the input coming from device.
/// \param device The name of the device that is producing the input.
/// \param inputData The input data coming from the device.
void handleInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) override
{
m_lastInput.set(inputData);
}
/// Initialize the input data information stored in this input consumer.
/// \param device The name of the device that is producing the input.
/// \param initialData Initial input data of the device.
void initializeInput(const std::string& device, const SurgSim::DataStructures::DataGroup& initialData) override
{
m_lastInput.set(initialData);
}
/// Retrieve input data information stored in this input consumer
/// \param [out] dataGroup Used to accept the retrieved input data information
void getData(SurgSim::DataStructures::DataGroup* dataGroup)
{
m_lastInput.get(dataGroup);
}
private:
/// Used to store input data information passed in from device
SurgSim::Framework::LockedContainer<SurgSim::DataStructures::DataGroup> m_lastInput;
};
InputComponent::InputComponent(const std::string& name) :
Representation(name),
m_deviceConnected(false),
m_deviceName(),
m_input(std::make_shared<InputConsumer>())
{
SURGSIM_ADD_SERIALIZABLE_PROPERTY(InputComponent, std::string, DeviceName,
getDeviceName, setDeviceName);
}
InputComponent::~InputComponent()
{
}
void InputComponent::setDeviceName(const std::string& deviceName)
{
m_deviceName = deviceName;
}
bool InputComponent::isDeviceConnected()
{
return m_deviceConnected;
}
void InputComponent::getData(SurgSim::DataStructures::DataGroup* dataGroup)
{
SURGSIM_ASSERT(m_deviceConnected) << "No device connected to InputComponent named '" << getName() <<
"'. Unable to getData.";
m_input->getData(dataGroup);
}
bool InputComponent::doInitialize()
{
return true;
}
bool InputComponent::doWakeUp()
{
return true;
}
std::string InputComponent::getDeviceName() const
{
return m_deviceName;
}
void InputComponent::connectDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device)
{
device->addInputConsumer(m_input);
m_deviceConnected = true;
}
void InputComponent::disconnectDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device)
{
device->removeInputConsumer(m_input);
m_deviceConnected = false;
}
std::shared_ptr<InputConsumerInterface> InputComponent::getConsumer()
{
return m_input;
}
}; // namespace Input
}; // namespace SurgSim
|
f37b29236326dcffb62f48175c9c1072b50172dd
|
3ee83e5b767c0bc4fdf7c215e37673c56bc6b6ef
|
/src/render/camera.cpp
|
2d00d65108aadeb587990fb33a5cea092cfb3840
|
[
"Apache-2.0"
] |
permissive
|
mcneel/cycles
|
1873e931563f763f49e26506f15e2643f8b25f1e
|
0a3866af513acb771f2e30d51bf05dec69394074
|
refs/heads/master_rhino_20170613
| 2023-09-01T20:00:58.001153
| 2017-08-24T12:55:32
| 2017-08-24T12:55:32
| 58,046,507
| 34
| 14
| null | 2017-08-24T13:12:34
| 2016-05-04T11:20:24
|
C++
|
UTF-8
|
C++
| false
| false
| 19,497
|
cpp
|
camera.cpp
|
/*
* Copyright 2011-2013 Blender Foundation
*
* 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 "render/camera.h"
#include "render/mesh.h"
#include "render/object.h"
#include "render/scene.h"
#include "render/tables.h"
#include "device/device.h"
#include "util/util_foreach.h"
#include "util/util_function.h"
#include "util/util_math_cdf.h"
#include "util/util_vector.h"
CCL_NAMESPACE_BEGIN
static float shutter_curve_eval(float x,
array<float>& shutter_curve)
{
if(shutter_curve.size() == 0) {
return 1.0f;
}
x *= shutter_curve.size();
int index = (int)x;
float frac = x - index;
if(index < shutter_curve.size() - 1) {
return lerp(shutter_curve[index], shutter_curve[index + 1], frac);
}
else {
return shutter_curve[shutter_curve.size() - 1];
}
}
NODE_DEFINE(Camera)
{
NodeType* type = NodeType::add("camera", create);
SOCKET_FLOAT(shuttertime, "Shutter Time", 1.0f);
static NodeEnum motion_position_enum;
motion_position_enum.insert("start", MOTION_POSITION_START);
motion_position_enum.insert("center", MOTION_POSITION_CENTER);
motion_position_enum.insert("end", MOTION_POSITION_END);
SOCKET_ENUM(motion_position, "Motion Position", motion_position_enum, MOTION_POSITION_CENTER);
static NodeEnum rolling_shutter_type_enum;
rolling_shutter_type_enum.insert("none", ROLLING_SHUTTER_NONE);
rolling_shutter_type_enum.insert("top", ROLLING_SHUTTER_TOP);
SOCKET_ENUM(rolling_shutter_type, "Rolling Shutter Type", rolling_shutter_type_enum, ROLLING_SHUTTER_NONE);
SOCKET_FLOAT(rolling_shutter_duration, "Rolling Shutter Duration", 0.1f);
SOCKET_FLOAT_ARRAY(shutter_curve, "Shutter Curve", array<float>());
SOCKET_FLOAT(aperturesize, "Aperture Size", 0.0f);
SOCKET_FLOAT(focaldistance, "Focal Distance", 10.0f);
SOCKET_UINT(blades, "Blades", 0);
SOCKET_FLOAT(bladesrotation, "Blades Rotation", 0.0f);
SOCKET_TRANSFORM(matrix, "Matrix", transform_identity());
SOCKET_FLOAT(aperture_ratio, "Aperture Ratio", 1.0f);
static NodeEnum type_enum;
type_enum.insert("perspective", CAMERA_PERSPECTIVE);
type_enum.insert("orthograph", CAMERA_ORTHOGRAPHIC);
type_enum.insert("panorama", CAMERA_PANORAMA);
SOCKET_ENUM(type, "Type", type_enum, CAMERA_PERSPECTIVE);
static NodeEnum panorama_type_enum;
panorama_type_enum.insert("equirectangular", PANORAMA_EQUIRECTANGULAR);
panorama_type_enum.insert("mirrorball", PANORAMA_MIRRORBALL);
panorama_type_enum.insert("fisheye_equidistant", PANORAMA_FISHEYE_EQUIDISTANT);
panorama_type_enum.insert("fisheye_equisolid", PANORAMA_FISHEYE_EQUISOLID);
SOCKET_ENUM(panorama_type, "Panorama Type", panorama_type_enum, PANORAMA_EQUIRECTANGULAR);
SOCKET_FLOAT(fisheye_fov, "Fisheye FOV", M_PI_F);
SOCKET_FLOAT(fisheye_lens, "Fisheye Lens", 10.5f);
SOCKET_FLOAT(latitude_min, "Latitude Min", -M_PI_2_F);
SOCKET_FLOAT(latitude_max, "Latitude Max", M_PI_2_F);
SOCKET_FLOAT(longitude_min, "Longitude Min", -M_PI_F);
SOCKET_FLOAT(longitude_max, "Longitude Max", M_PI_F);
SOCKET_FLOAT(fov, "FOV", M_PI_4_F);
SOCKET_FLOAT(fov_pre, "FOV Pre", M_PI_4_F);
SOCKET_FLOAT(fov_post, "FOV Post", M_PI_4_F);
static NodeEnum stereo_eye_enum;
stereo_eye_enum.insert("none", STEREO_NONE);
stereo_eye_enum.insert("left", STEREO_LEFT);
stereo_eye_enum.insert("right", STEREO_RIGHT);
SOCKET_ENUM(stereo_eye, "Stereo Eye", stereo_eye_enum, STEREO_NONE);
SOCKET_FLOAT(interocular_distance, "Interocular Distance", 0.065f);
SOCKET_FLOAT(convergence_distance, "Convergence Distance", 30.0f * 0.065f);
SOCKET_BOOLEAN(use_pole_merge, "Use Pole Merge", false);
SOCKET_FLOAT(pole_merge_angle_from, "Pole Merge Angle From", 60.0f * M_PI_F / 180.0f);
SOCKET_FLOAT(pole_merge_angle_to, "Pole Merge Angle To", 75.0f * M_PI_F / 180.0f);
SOCKET_FLOAT(sensorwidth, "Sensor Width", 0.036f);
SOCKET_FLOAT(sensorheight, "Sensor Height", 0.024f);
SOCKET_FLOAT(nearclip, "Near Clip", 1e-5f);
SOCKET_FLOAT(farclip, "Far Clip", 1e5f);
SOCKET_FLOAT(viewplane.left, "Viewplane Left", 0);
SOCKET_FLOAT(viewplane.right, "Viewplane Right", 0);
SOCKET_FLOAT(viewplane.bottom, "Viewplane Bottom", 0);
SOCKET_FLOAT(viewplane.top, "Viewplane Top", 0);
SOCKET_FLOAT(border.left, "Border Left", 0);
SOCKET_FLOAT(border.right, "Border Right", 0);
SOCKET_FLOAT(border.bottom, "Border Bottom", 0);
SOCKET_FLOAT(border.top, "Border Top", 0);
return type;
}
Camera::Camera()
: Node(node_type)
{
shutter_table_offset = TABLE_OFFSET_INVALID;
width = 1024;
height = 512;
resolution = 1;
motion.pre = transform_identity();
motion.post = transform_identity();
use_motion = false;
use_perspective_motion = false;
shutter_curve.resize(RAMP_TABLE_SIZE);
for(int i = 0; i < shutter_curve.size(); ++i) {
shutter_curve[i] = 1.0f;
}
compute_auto_viewplane();
screentoworld = transform_identity();
rastertoworld = transform_identity();
ndctoworld = transform_identity();
rastertocamera = transform_identity();
cameratoworld = transform_identity();
worldtoraster = transform_identity();
dx = make_float3(0.0f, 0.0f, 0.0f);
dy = make_float3(0.0f, 0.0f, 0.0f);
need_update = true;
need_device_update = true;
need_flags_update = true;
previous_need_motion = -1;
}
Camera::~Camera()
{
}
void Camera::compute_auto_viewplane()
{
if(type == CAMERA_PANORAMA) {
viewplane.left = 0.0f;
viewplane.right = 1.0f;
viewplane.bottom = 0.0f;
viewplane.top = 1.0f;
}
else {
float aspect = (float)width/(float)height;
if(width >= height) {
viewplane.left = -aspect;
viewplane.right = aspect;
viewplane.bottom = -1.0f;
viewplane.top = 1.0f;
}
else {
viewplane.left = -1.0f;
viewplane.right = 1.0f;
viewplane.bottom = -1.0f/aspect;
viewplane.top = 1.0f/aspect;
}
}
}
void Camera::update()
{
if(!need_update)
return;
/* Full viewport to camera border in the viewport. */
Transform fulltoborder = transform_from_viewplane(viewport_camera_border);
Transform bordertofull = transform_inverse(fulltoborder);
/* ndc to raster */
Transform ndctoraster = transform_scale(width, height, 1.0f) * bordertofull;
Transform full_ndctoraster = transform_scale(full_width, full_height, 1.0f) * bordertofull;
/* raster to screen */
Transform screentondc = fulltoborder * transform_from_viewplane(viewplane);
Transform screentoraster = ndctoraster * screentondc;
Transform rastertoscreen = transform_inverse(screentoraster);
Transform full_screentoraster = full_ndctoraster * screentondc;
Transform full_rastertoscreen = transform_inverse(full_screentoraster);
/* screen to camera */
Transform cameratoscreen;
if(type == CAMERA_PERSPECTIVE)
cameratoscreen = transform_perspective(fov, nearclip, farclip);
else if(type == CAMERA_ORTHOGRAPHIC)
cameratoscreen = transform_orthographic(nearclip, farclip);
else
cameratoscreen = transform_identity();
Transform screentocamera = transform_inverse(cameratoscreen);
rastertocamera = screentocamera * rastertoscreen;
Transform full_rastertocamera = screentocamera * full_rastertoscreen;
cameratoraster = screentoraster * cameratoscreen;
cameratoworld = matrix;
screentoworld = cameratoworld * screentocamera;
rastertoworld = cameratoworld * rastertocamera;
ndctoworld = rastertoworld * ndctoraster;
/* note we recompose matrices instead of taking inverses of the above, this
* is needed to avoid inverting near degenerate matrices that happen due to
* precision issues with large scenes */
worldtocamera = transform_inverse(matrix);
worldtoscreen = cameratoscreen * worldtocamera;
worldtondc = screentondc * worldtoscreen;
worldtoraster = ndctoraster * worldtondc;
cameratondc = screentondc * cameratoscreen;
/* differentials */
if(type == CAMERA_ORTHOGRAPHIC) {
dx = transform_direction(&rastertocamera, make_float3(1, 0, 0));
dy = transform_direction(&rastertocamera, make_float3(0, 1, 0));
full_dx = transform_direction(&full_rastertocamera, make_float3(1, 0, 0));
full_dy = transform_direction(&full_rastertocamera, make_float3(0, 1, 0));
}
else if(type == CAMERA_PERSPECTIVE) {
dx = transform_perspective(&rastertocamera, make_float3(1, 0, 0)) -
transform_perspective(&rastertocamera, make_float3(0, 0, 0));
dy = transform_perspective(&rastertocamera, make_float3(0, 1, 0)) -
transform_perspective(&rastertocamera, make_float3(0, 0, 0));
full_dx = transform_perspective(&full_rastertocamera, make_float3(1, 0, 0)) -
transform_perspective(&full_rastertocamera, make_float3(0, 0, 0));
full_dy = transform_perspective(&full_rastertocamera, make_float3(0, 1, 0)) -
transform_perspective(&full_rastertocamera, make_float3(0, 0, 0));
}
else {
dx = make_float3(0.0f, 0.0f, 0.0f);
dy = make_float3(0.0f, 0.0f, 0.0f);
}
dx = transform_direction(&cameratoworld, dx);
dy = transform_direction(&cameratoworld, dy);
full_dx = transform_direction(&cameratoworld, full_dx);
full_dy = transform_direction(&cameratoworld, full_dy);
/* TODO(sergey): Support other types of camera. */
if(type == CAMERA_PERSPECTIVE) {
/* TODO(sergey): Move to an utility function and de-duplicate with
* calculation above.
*/
Transform screentocamera_pre =
transform_inverse(transform_perspective(fov_pre,
nearclip,
farclip));
Transform screentocamera_post =
transform_inverse(transform_perspective(fov_post,
nearclip,
farclip));
perspective_motion.pre = screentocamera_pre * rastertoscreen;
perspective_motion.post = screentocamera_post * rastertoscreen;
}
need_update = false;
need_device_update = true;
need_flags_update = true;
}
void Camera::device_update(Device *device, DeviceScene *dscene, Scene *scene)
{
Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
update();
if(previous_need_motion != need_motion) {
/* scene's motion model could have been changed since previous device
* camera update this could happen for example in case when one render
* layer has got motion pass and another not */
need_device_update = true;
}
if(!need_device_update)
return;
KernelCamera *kcam = &dscene->data.cam;
/* store matrices */
kcam->screentoworld = screentoworld;
kcam->rastertoworld = rastertoworld;
kcam->rastertocamera = rastertocamera;
kcam->cameratoworld = cameratoworld;
kcam->worldtocamera = worldtocamera;
kcam->worldtoscreen = worldtoscreen;
kcam->worldtoraster = worldtoraster;
kcam->worldtondc = worldtondc;
kcam->cameratondc = cameratondc;
/* camera motion */
kcam->have_motion = 0;
kcam->have_perspective_motion = 0;
if(need_motion == Scene::MOTION_PASS) {
/* TODO(sergey): Support perspective (zoom, fov) motion. */
if(type == CAMERA_PANORAMA) {
if(use_motion) {
kcam->motion.pre = transform_inverse(motion.pre);
kcam->motion.post = transform_inverse(motion.post);
}
else {
kcam->motion.pre = kcam->worldtocamera;
kcam->motion.post = kcam->worldtocamera;
}
}
else {
if(use_motion) {
kcam->motion.pre = cameratoraster * transform_inverse(motion.pre);
kcam->motion.post = cameratoraster * transform_inverse(motion.post);
}
else {
kcam->motion.pre = worldtoraster;
kcam->motion.post = worldtoraster;
}
}
}
#ifdef __CAMERA_MOTION__
else if(need_motion == Scene::MOTION_BLUR) {
if(use_motion) {
transform_motion_decompose((DecompMotionTransform*)&kcam->motion, &motion, &matrix);
kcam->have_motion = 1;
}
if(use_perspective_motion) {
kcam->perspective_motion = perspective_motion;
kcam->have_perspective_motion = 1;
}
}
#endif
/* depth of field */
kcam->aperturesize = aperturesize;
kcam->focaldistance = focaldistance;
kcam->blades = (blades < 3)? 0.0f: blades;
kcam->bladesrotation = bladesrotation;
/* motion blur */
#ifdef __CAMERA_MOTION__
kcam->shuttertime = (need_motion == Scene::MOTION_BLUR) ? shuttertime: -1.0f;
scene->lookup_tables->remove_table(&shutter_table_offset);
if(need_motion == Scene::MOTION_BLUR) {
vector<float> shutter_table;
util_cdf_inverted(SHUTTER_TABLE_SIZE,
0.0f,
1.0f,
function_bind(shutter_curve_eval, _1, shutter_curve),
false,
shutter_table);
shutter_table_offset = scene->lookup_tables->add_table(dscene,
shutter_table);
kcam->shutter_table_offset = (int)shutter_table_offset;
}
#else
kcam->shuttertime = -1.0f;
#endif
/* type */
kcam->type = type;
/* anamorphic lens bokeh */
kcam->inv_aperture_ratio = 1.0f / aperture_ratio;
/* panorama */
kcam->panorama_type = panorama_type;
kcam->fisheye_fov = fisheye_fov;
kcam->fisheye_lens = fisheye_lens;
kcam->equirectangular_range = make_float4(longitude_min - longitude_max, -longitude_min,
latitude_min - latitude_max, -latitude_min + M_PI_2_F);
switch(stereo_eye) {
case STEREO_LEFT:
kcam->interocular_offset = -interocular_distance * 0.5f;
break;
case STEREO_RIGHT:
kcam->interocular_offset = interocular_distance * 0.5f;
break;
case STEREO_NONE:
default:
kcam->interocular_offset = 0.0f;
break;
}
kcam->convergence_distance = convergence_distance;
if(use_pole_merge) {
kcam->pole_merge_angle_from = pole_merge_angle_from;
kcam->pole_merge_angle_to = pole_merge_angle_to;
}
else {
kcam->pole_merge_angle_from = -1.0f;
kcam->pole_merge_angle_to = -1.0f;
}
/* sensor size */
kcam->sensorwidth = sensorwidth;
kcam->sensorheight = sensorheight;
/* render size */
kcam->width = width;
kcam->height = height;
kcam->resolution = resolution;
/* store differentials */
kcam->dx = float3_to_float4(dx);
kcam->dy = float3_to_float4(dy);
/* clipping */
kcam->nearclip = nearclip;
kcam->cliplength = (farclip == FLT_MAX)? FLT_MAX: farclip - nearclip;
/* Camera in volume. */
kcam->is_inside_volume = 0;
/* Rolling shutter effect */
kcam->rolling_shutter_type = rolling_shutter_type;
kcam->rolling_shutter_duration = rolling_shutter_duration;
previous_need_motion = need_motion;
}
void Camera::device_update_volume(Device * /*device*/,
DeviceScene *dscene,
Scene *scene)
{
if(!need_device_update && !need_flags_update) {
return;
}
KernelCamera *kcam = &dscene->data.cam;
BoundBox viewplane_boundbox = viewplane_bounds_get();
for(size_t i = 0; i < scene->objects.size(); ++i) {
Object *object = scene->objects[i];
if(object->mesh->has_volume &&
viewplane_boundbox.intersects(object->bounds))
{
/* TODO(sergey): Consider adding more grained check. */
kcam->is_inside_volume = 1;
break;
}
}
need_device_update = false;
need_flags_update = false;
}
void Camera::device_free(Device * /*device*/,
DeviceScene * /*dscene*/,
Scene *scene)
{
scene->lookup_tables->remove_table(&shutter_table_offset);
}
bool Camera::modified(const Camera& cam)
{
return !Node::equals(cam);
}
bool Camera::motion_modified(const Camera& cam)
{
return !((motion == cam.motion) &&
(use_motion == cam.use_motion) &&
(use_perspective_motion == cam.use_perspective_motion));
}
void Camera::tag_update()
{
need_update = true;
}
float3 Camera::transform_raster_to_world(float raster_x, float raster_y)
{
float3 D, P;
if(type == CAMERA_PERSPECTIVE) {
D = transform_perspective(&rastertocamera,
make_float3(raster_x, raster_y, 0.0f));
float3 Pclip = normalize(D);
P = make_float3(0.0f, 0.0f, 0.0f);
/* TODO(sergey): Aperture support? */
P = transform_point(&cameratoworld, P);
D = normalize(transform_direction(&cameratoworld, D));
/* TODO(sergey): Clipping is conditional in kernel, and hence it could
* be mistakes in here, currently leading to wrong camera-in-volume
* detection.
*/
P += nearclip * D / Pclip.z;
}
else if(type == CAMERA_ORTHOGRAPHIC) {
D = make_float3(0.0f, 0.0f, 1.0f);
/* TODO(sergey): Aperture support? */
P = transform_perspective(&rastertocamera,
make_float3(raster_x, raster_y, 0.0f));
P = transform_point(&cameratoworld, P);
D = normalize(transform_direction(&cameratoworld, D));
}
else {
assert(!"unsupported camera type");
}
return P;
}
BoundBox Camera::viewplane_bounds_get()
{
/* TODO(sergey): This is all rather stupid, but is there a way to perform
* checks we need in a more clear and smart fasion?
*/
BoundBox bounds = BoundBox::empty;
if(type == CAMERA_PANORAMA) {
if(use_spherical_stereo == false) {
bounds.grow(make_float3(cameratoworld.x.w,
cameratoworld.y.w,
cameratoworld.z.w));
}
else {
float half_eye_distance = interocular_distance * 0.5f;
bounds.grow(make_float3(cameratoworld.x.w + half_eye_distance,
cameratoworld.y.w,
cameratoworld.z.w));
bounds.grow(make_float3(cameratoworld.z.w,
cameratoworld.y.w + half_eye_distance,
cameratoworld.z.w));
bounds.grow(make_float3(cameratoworld.x.w - half_eye_distance,
cameratoworld.y.w,
cameratoworld.z.w));
bounds.grow(make_float3(cameratoworld.x.w,
cameratoworld.y.w - half_eye_distance,
cameratoworld.z.w));
}
}
else {
bounds.grow(transform_raster_to_world(0.0f, 0.0f));
bounds.grow(transform_raster_to_world(0.0f, (float)height));
bounds.grow(transform_raster_to_world((float)width, (float)height));
bounds.grow(transform_raster_to_world((float)width, 0.0f));
if(type == CAMERA_PERSPECTIVE) {
/* Center point has the most distance in local Z axis,
* use it to construct bounding box/
*/
bounds.grow(transform_raster_to_world(0.5f*width, 0.5f*height));
}
}
return bounds;
}
float Camera::world_to_raster_size(float3 P)
{
if(type == CAMERA_ORTHOGRAPHIC) {
return min(len(full_dx), len(full_dy));
}
else if(type == CAMERA_PERSPECTIVE) {
/* Calculate as if point is directly ahead of the camera. */
float3 raster = make_float3(0.5f*width, 0.5f*height, 0.0f);
float3 Pcamera = transform_perspective(&rastertocamera, raster);
/* dDdx */
float3 Ddiff = transform_direction(&cameratoworld, Pcamera);
float3 dx = len_squared(full_dx) < len_squared(full_dy) ? full_dx : full_dy;
float3 dDdx = normalize(Ddiff + dx) - normalize(Ddiff);
/* dPdx */
float dist = len(transform_point(&worldtocamera, P));
float3 D = normalize(Ddiff);
return len(dist*dDdx - dot(dist*dDdx, D)*D);
}
else {
// TODO(mai): implement for CAMERA_PANORAMA
assert(!"pixel width calculation for panoramic projection not implemented yet");
}
return 1.0f;
}
CCL_NAMESPACE_END
|
4dd675a3d540814188efe4a220f8d47cbac45fba
|
7a5dbfc55d2fcd43e90e14ebe3fe3fa4705a162a
|
/Quasics2021Code/MaeTester/src/main/cpp/commands/TriggerDrivenShootingCommand.cpp
|
cead09f78fd15287abecd2235582222533c29760
|
[
"BSD-3-Clause"
] |
permissive
|
quasics/quasics-frc-sw-2015
|
c71194921a3f0930bc16ae96952577ff029f8542
|
83aa34f475e5060e31ddf12186b48cb68430acc6
|
refs/heads/master
| 2023-08-23T07:13:23.194240
| 2023-08-17T23:19:51
| 2023-08-17T23:19:51
| 43,209,473
| 7
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,019
|
cpp
|
TriggerDrivenShootingCommand.cpp
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "commands/TriggerDrivenShootingCommand.h"
TriggerDrivenShootingCommand::TriggerDrivenShootingCommand(
Shooter* shooter, double highSpeed, double lowSpeed,
std::function<bool()> runHighSpeed, std::function<bool()> runLowSpeed)
: shooter(shooter),
highSpeed(highSpeed),
lowSpeed(lowSpeed),
runHighSpeed(runHighSpeed),
runLowSpeed(runLowSpeed) {
AddRequirements({shooter});
}
// Called repeatedly when this Command is scheduled to run
void TriggerDrivenShootingCommand::Execute() {
if (runHighSpeed()) {
shooter->SetSpeed(highSpeed);
} else if (runLowSpeed()) {
shooter->SetSpeed(lowSpeed);
} else {
shooter->Stop();
}
}
// Called once the command ends or is interrupted.
void TriggerDrivenShootingCommand::End(bool interrupted) {
shooter->Stop();
}
|
aac7c44758ee6a75b9d805b857c6802bd2fea06a
|
a8880d5cbd16bb0c8c1a871370b22d46ca821bd7
|
/filters/WaveFilter.cpp
|
64dfc38048f0cc9be88e9368393bdd91d21eab21
|
[] |
no_license
|
Totktonada/ImageProcessor
|
53c7f9692360cdd9573a40758a85462dbf6c1ea0
|
ab94496d44be6f5f156c61a96c703b93e9e385b6
|
refs/heads/master
| 2021-01-19T17:11:39.662338
| 2012-10-07T17:31:07
| 2012-10-07T17:31:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,845
|
cpp
|
WaveFilter.cpp
|
#include <QImage>
#include <QtGlobal>
#include <math.h>
#include "WaveFilter.hpp"
#include "../Utils.hpp"
#include "../Algorithms.hpp"
WaveFilter::WaveFilter(double aRadius, double aPeriod,
Orientation aOrientation)
: radius(aRadius),
period(aPeriod),
orientation(aOrientation)
{}
WaveFilter::~WaveFilter()
{}
QImage * WaveFilter::filter(const QImage & source) const
{
uint w = source.width();
uint h = source.height();
QImage * dest = new QImage(source);
QRgb * to = reinterpret_cast<QRgb *>(dest->bits());
const QRgb * rgb =
reinterpret_cast<const QRgb *>(source.constBits());
for (int y = area.y(); y < area.y() + area.height(); ++y)
{
for (int x = area.x(); x < area.x() + area.width(); ++x)
{
to[y * w + x] = getPixel(rgb, x, y, w, h);
}
}
return dest;
}
uint WaveFilter::getWindowRadius() const
{
return (uint) radius + 1;
}
QRgb WaveFilter::getPixel(const QRgb * rgb,
uint x, uint y, uint w, uint h) const
{
/* New coordinates */
double ncX = x - area.x() + 0.5 - area.width() / 2.0;
double ncY = y - area.y() + 0.5 - area.height() / 2.0;
double fromX;
double fromY;
if (orientation == Horizontal)
{
fromX = ncX;
fromY = ncY + radius * Utils::getSin(2 * M_PI * ncX / period);
}
else /* (orientation == Vertical) */
{
fromX = ncX + radius * Utils::getSin(2 * M_PI * ncY / period);
fromY = ncY;
}
/* To old coordinates */
fromX = fromX + area.x() - 0.5 + area.width() / 2.0;
fromY = fromY + area.y() - 0.5 + area.height() / 2.0;
if (fromX < 0.0 || fromX > (w - 1.0) ||
fromY < 0.0 || fromY > (h - 1.0))
{
return qRgb(0, 0, 0);
}
return Algorithms::bilinearInterpolatedValue(rgb, fromX, fromY, w, h);
}
|
1b0775cc67114c590e2e2c89f53a965cd674b53d
|
5654998d8a024b2613fc6bbf709875e428914f81
|
/src/hed/acc/JobDescriptionParser/ADLParser.h
|
1d88c45844b879beb104e5761e9cf597d2d07353
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
davidgcameron/arc
|
96f4188017e8b6ce71c099fb348a09ba037c1dbb
|
9813ef5f45e5089507953239de8fa2248f5ad32c
|
refs/heads/master
| 2021-10-23T22:04:24.290988
| 2019-03-20T07:16:50
| 2019-03-20T07:16:50
| 176,705,313
| 0
| 0
|
Apache-2.0
| 2019-03-20T10:03:27
| 2019-03-20T10:03:27
| null |
UTF-8
|
C++
| false
| false
| 1,874
|
h
|
ADLParser.h
|
// -*- indent-tabs-mode: nil -*-
#ifndef __ARC_ADLPARSER_H__
#define __ARC_ADLPARSER_H__
#include <string>
#include <arc/compute/JobDescriptionParserPlugin.h>
/** ARDLParser
* The ARCJSDLParser class, derived from the JobDescriptionParserPlugin class, is
* a job description parser for the EMI ES job description language (ADL)
* described in <http://>.
*/
namespace Arc {
template<typename T> class Range;
class Software;
class SoftwareRequirement;
class ADLParser
: public JobDescriptionParserPlugin {
public:
ADLParser(PluginArgument* parg);
~ADLParser();
JobDescriptionParserPluginResult Parse(const std::string& source, std::list<JobDescription>& jobdescs, const std::string& language = "", const std::string& dialect = "") const;
JobDescriptionParserPluginResult Assemble(const JobDescription& job, std::string& product, const std::string& language, const std::string& dialect = "") const;
static Plugin* Instance(PluginArgument *arg);
private:
/*
bool parseSoftware(XMLNode xmlSoftware, SoftwareRequirement& sr) const;
void outputSoftware(const SoftwareRequirement& sr, XMLNode& xmlSoftware) const;
template<typename T>
void parseRange(XMLNode xmlRange, Range<T>& range, const T& undefValue) const;
template<typename T>
Range<T> parseRange(XMLNode xmlRange, const T& undefValue) const;
template<typename T>
void outputARCJSDLRange(const Range<T>& range, XMLNode& arcJSDL, const T& undefValue) const;
template<typename T>
void outputJSDLRange(const Range<T>& range, XMLNode& jsdl, const T& undefValue) const;
void parseBenchmark(XMLNode xmlBenchmark, std::pair<std::string, double>& benchmark) const;
void outputBenchmark(const std::pair<std::string, double>& benchmark, XMLNode& xmlBenchmark) const;
*/
};
} // namespace Arc
#endif // __ARC_ADLPARSER_H__
|
048c6433cba0f9fa0ecc0ed01ce732c3095a1cf5
|
00ce81a2ac01f55754ea8fee5fcbc416ff2f90dd
|
/C语言基础/老师课件/基础_09/02_重载++/02_重载++.cpp
|
e4778a3639eb38460e8366c7734b166f6099e6f4
|
[] |
no_license
|
song493818557/mfc
|
1bd0064eec466847bac0f6abc7775d99b13f2423
|
ce562ef61580b959c198c053648c9f77a7ea7a18
|
refs/heads/master
| 2021-01-13T04:49:50.035383
| 2017-01-13T12:10:08
| 2017-01-13T12:10:08
| 78,842,167
| 4
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,083
|
cpp
|
02_重载++.cpp
|
// 02_重载++.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
enum MyEnum
{
UP,
DOWN,
LEFT,
RIGHT
};
class CTest
{
public:
CTest(int nX = 0,int nY = 0,int nDir = UP):
m_x(nX), m_y(nY), m_nDir(nDir)
{
}
public:
CTest operator++()//前置++
{
switch (m_nDir)
{
case UP:
{
m_y--;
break;
}
case DOWN:
{
m_y++;
break;
}
case LEFT:
{
m_x--;
break;
}
case RIGHT:
{
m_x++;
break;
}
}
/*CTest Temp(m_x, m_y, m_nDir);
return Temp;*/
return *this;//this就是本对象的地址,类型是CTest*
}
CTest operator++(int ) //后置++
{
CTest Temp(m_x, m_y, m_nDir);
switch (m_nDir)
{
case UP:
{
m_y--;
break;
}
case DOWN:
{
m_y++;
break;
}
case LEFT:
{
m_x--;
break;
}
case RIGHT:
{
m_x++;
break;
}
}
return Temp;
}
private:
int m_x;
int m_y;
int m_nDir;
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest objA(1,1,UP);
CTest objB;
objB = objA++;
objB = ++objA;
int a = 0;
int b = a++;
b = ++a;
return 0;
}
|
d31485ff209b624db5a91afa254dc0044c8fd1e9
|
3e6c3cb8af1a8928936ee2435d6e86141a02267e
|
/playHists/getVertexWeight.h
|
4f6773feba16f515300786f916ca5cc65216ef59
|
[] |
no_license
|
mengzx/CMS-SUSY-2012
|
cd340bfa0ed48558528c28232ed06ac5cd277bb9
|
6bc003ec9a66e36f0aacba2fa3e4ea3d56b5531d
|
refs/heads/master
| 2021-01-10T19:37:40.935953
| 2013-02-06T15:46:34
| 2013-02-06T15:46:34
| 3,111,915
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 370
|
h
|
getVertexWeight.h
|
#ifndef getVertexWeight_h
#define getVertexWeight_h
#include "TH1D.h"
#include "TString.h"
#include "menus.h"
#include "vectors.h"
#include <vector>
using namespace std;
class getVertexWeight : public menus, public vectors{
public:
getVertexWeight();
~getVertexWeight(){}
TH1D *addHists(TString label);
TH1D *getWeight();
}; //class getVertexWeight
#endif
|
5ad21f26a3abbfc7ca327d28be753befc520e7f9
|
c2efe54b8ad33c2a6f516b865fc104894d800186
|
/[程序员面试金典]1009.找出字符串.cpp
|
eafca0fc9742bcf2d716b74c461718e86f20e5a2
|
[] |
no_license
|
Fly365/AlgorithmCode
|
2f8df8b934dcd3099d0e6b0fed66b670f28d21b3
|
389401a4f7eb9f97ff524277c6e049771276e700
|
refs/heads/master
| 2021-01-12T17:56:10.927847
| 2015-10-27T02:00:23
| 2015-10-27T02:00:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,453
|
cpp
|
[程序员面试金典]1009.找出字符串.cpp
|
这是一道二分查找 的变形题目。唯一的关注点就是当str[mid] == ""时的处理,此时仅通过str[mid]=""是无法判断目标是在mid的左边还是右边。所以,我们遍历mid左边的元素找到第一个不是空字符串的元素。
如果mid左边的所有元素都是空字符串,则去掉令start=mid+1;
否则
找到第一个不是空字符串的元素下标为index
(1)如果str[index]等于目标正好返回。
(2)如果str[index]大于目标,则说明目标在str[index]左边,令end = index - 1。
(3)如果str[index]小于目标,则说明目标在str[mid]右边,令start = mid + 1
/*---------------------------------------
* 日期:2015-08-18
* 作者:SJF0115
* 题目:1009.找出字符串
* 来源:程序员面试金典
* 网址:http://www.nowcoder.com/practice/06f532d3230042769b4d156e963a4f4a?rp=3&ru=/ta/cracking-the-coding-interview
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Finder {
public:
int findString(vector<string> str, int n, string x) {
int size = str.size();
if(size == 0 || n <= 0){
return -1;
}//if
// 采用二分查找
int start = 0,end = size - 1;
int mid;
while(start <= end){
mid = (end - start) / 2 + start;
// 遇到空格特殊处理
if(str[mid] == ""){
int index = mid;
while(index >= start && str[index] == ""){
--index;
}//while
if(index < start){
start = mid + 1;
}//if
else if(str[index] == x){
return index;
}//else
else if(str[index] > x){
end = index - 1;
}//else
else{
start = mid + 1;
}//else
}//if
// 非空格
else{
// 找到目标
if(str[mid] == x){
return mid;
}//if
// 中间值比目标大只能在中间值的左边
else if(str[mid] > x){
end = mid - 1;
}//else
// 中间值比目标小只能在中间值的右边
else{
start = mid + 1;
}//else
}//else
}//while
return -1;
}
};
int main() {
Finder s;
vector<string> vec = {"","","","","","","AECOGS","AOOFYXQ","AQ","AVMMTXNXRA","BAXEVHLYME","BCA","BUV","BVTPMOLHLC","BX","CBDHCOMI","CDWGWW","CLG","CODB","CWKIYFYHNIY","CZA","D","DEMJMHQYMC","DFLYAK","DRR","DVMVXK","EIHULX","EOTCMEXHH","ETYGMD","EXXHWDPS","GNVM","GVEBGEFC","HEFVFXDND","HOUUXMYVC","IDPNQI","IIODZQF","IVPD","JEGHXQCTTNT","JJXNXIYGH","JZBCHVIHK","LIDN","LLKIIAZ","MCBFFHFJBLT","MRTYDDIM","MVWD","N","NJBXRKL","NLEMZIZ","NMMQL","NQQRGMAN","NUO","O","OBC","ONES","OPP","OXOPR","Q","QBZNAE","QCK","QGR","QKLUDC","RWASPGXEUJY","TDDWTG","TER","TTZK","TV","UGUJUEU","UIQYOL","USQENKTCEGJ","UZ","V","VDGRM","VNEFQVOGRYX","VQNFRIPQR","WHLNXPTCPAI","WNYVMOYJBCY","WSZQBUGJO","WVPZVAWYJJ","X","XMTDBDND","XPANBKVAKB","XTPYTK","Y","ZUDJMEVLQJN"};
string str("TER");
cout<<s.findString(vec,vec.size(),str)<<endl;
return 0;
}
|
8ab9091bfa5a09768ae3af2a1c10887510b93a70
|
1555a682e74657c28dcde082bfb704a3f4f32264
|
/gui/path_planner/teb_planner/src/config_widget.cpp
|
741f93062b9fff1a829474d169623d0441a2a64d
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
lyp365859350/rip
|
bc78cd3fbc0f99141f5070922ca893255fd8347b
|
51cfc0683e985ccdbf698556135eda7368758c10
|
refs/heads/master
| 2021-09-23T00:53:11.780796
| 2018-02-22T04:51:23
| 2018-02-22T04:51:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 51,311
|
cpp
|
config_widget.cpp
|
#include <teb_planner_gui/config_widget.hpp>
#include "ui_config_widget.h"
#include <QInputDialog>
#include <fmt/format.h>
#include <teb_planner_gui/exceptions.hpp>
#include <teb_planner_gui/exceptions.hpp>
namespace rip
{
namespace gui
{
namespace tebplanner
{
#define setupMap(map, var_name) \
map[m_ui->var_name] = #var_name;
ConfigWidget::ConfigWidget(QWidget* parent)
: QWidget(parent)
, m_ui(new Ui::ConfigWidget)
, m_settings(Settings::getInstance())
{
m_ui->setupUi(this);
// Disable
// Trajectory
m_ui->autosize->setEnabled(false);
m_ui->dt_ref->setEnabled(false);
m_ui->dt_hysteresis->setEnabled(false);
m_ui->min_samples->setEnabled(false);
m_ui->max_samples->setEnabled(false);
m_ui->overwrite_global_plan->setEnabled(false);
m_ui->backwards_motion->setEnabled(false);
m_ui->global_plan_waypoint_separation->setEnabled(false);
m_ui->waypoints_ordered->setEnabled(false);
m_ui->max_global_plan_lookahead_distance->setEnabled(false);
m_ui->exact_arc_length->setEnabled(false);
m_ui->force_new_goal_distance->setEnabled(false);
m_ui->feasibility_check_num_poses->setEnabled(false);
// Robot
m_ui->max_velocity_x->setEnabled(false);
m_ui->max_velocity_x_backwards->setEnabled(false);
m_ui->max_velocity_y->setEnabled(false);
m_ui->max_velocity_theta->setEnabled(false);
m_ui->acceleration_limit_x->setEnabled(false);
m_ui->acceleration_limit_y->setEnabled(false);
m_ui->acceleration_limit_theta->setEnabled(false);
m_ui->min_turning_radius->setEnabled(false);
m_ui->wheelbase->setEnabled(false);
// Goal Tolerance
m_ui->yaw_goal_tolerance->setEnabled(false);
m_ui->xy_goal_tolerance->setEnabled(false);
m_ui->free_goal_velocity->setEnabled(false);
// Obstacles
m_ui->min_obstacle_distance->setEnabled(false);
m_ui->inflation_distance->setEnabled(false);
m_ui->dynamic_obstacle_inflation_distance->setEnabled(false);
m_ui->include_dynamic_obstacles->setEnabled(false);
m_ui->obstacles_poses_affected->setEnabled(false);
m_ui->obstacle_association_force_inclusion_factor->setEnabled(false);
m_ui->obstacle_association_cutoff_factor->setEnabled(false);
// Optimization
m_ui->num_inner_iterations->setEnabled(false);
m_ui->num_outer_iterations->setEnabled(false);
m_ui->penalty_epsilon->setEnabled(false);
m_ui->max_velocity_x_weight->setEnabled(false);
m_ui->max_velocity_y_weight->setEnabled(false);
m_ui->max_velocity_theta_weight->setEnabled(false);
m_ui->acceleration_limit_x_weight->setEnabled(false);
m_ui->acceleration_limit_y_weight->setEnabled(false);
m_ui->acceleration_limit_theta_weight->setEnabled(false);
m_ui->kinematics_nh_weight->setEnabled(false);
m_ui->kinematics_forward_drive_weight->setEnabled(false);
m_ui->kinematics_turning_radius_weight->setEnabled(false);
m_ui->optimal_time_weight->setEnabled(false);
m_ui->obstacle_weight->setEnabled(false);
m_ui->inflation_weight->setEnabled(false);
m_ui->dynamic_obstacle_weight->setEnabled(false);
m_ui->dynamic_obstacle_inflation_weight->setEnabled(false);
m_ui->waypoint_weight->setEnabled(false);
m_ui->weight_adapt_factor->setEnabled(false);
// HCP
m_ui->enable_hcp->setEnabled(false);
m_ui->enable_mt->setEnabled(false);
m_ui->simple_exploration->setEnabled(false);
m_ui->max_number_classes->setEnabled(false);
m_ui->selection_cost_hysteresis->setEnabled(false);
m_ui->selection_obstacle_cost_scale->setEnabled(false);
m_ui->selection_prefer_initial_plan->setEnabled(false);
m_ui->selection_waypoint_cost_scale->setEnabled(false);
m_ui->selection_alternative_time_cost->setEnabled(false);
m_ui->roadmap_graph_no_samples->setEnabled(false);
m_ui->roadmap_graph_area_width->setEnabled(false);
m_ui->roadmap_graph_area_length_scale->setEnabled(false);
m_ui->h_signature_prescaler->setEnabled(false);
m_ui->h_signature_threshold->setEnabled(false);
m_ui->obstacle_keypoint_offset->setEnabled(false);
m_ui->obstacle_heading_threshold->setEnabled(false);
m_ui->waypoint_all_candidates->setEnabled(false);
// Trajectory
setupMap(m_bools, autosize);
setupMap(m_times, dt_ref);
setupMap(m_times, dt_hysteresis);
setupMap(m_integers, min_samples);
setupMap(m_integers, max_samples);
m_bools[m_ui->overwrite_global_plan] = "global_plan_overwrite_orientation";
setupMap(m_distances, global_plan_waypoint_separation);
setupMap(m_bools, waypoints_ordered);
setupMap(m_distances, max_global_plan_lookahead_distance);
setupMap(m_bools, exact_arc_length);
m_distances[m_ui->force_new_goal_distance] = "force_reinit_new_goal_distance";
setupMap(m_integers, feasibility_check_num_poses);
// Robot
setupMap(m_velocities, max_velocity_x);
setupMap(m_velocities, max_velocity_x_backwards);
setupMap(m_velocities, max_velocity_y);
setupMap(m_angular_velocities, max_velocity_theta);
setupMap(m_accelerations, acceleration_limit_x);
setupMap(m_accelerations, acceleration_limit_y);
setupMap(m_angular_accelerations, acceleration_limit_theta);
setupMap(m_distances, min_turning_radius);
setupMap(m_distances, wheelbase);
// Goal Tolerance
setupMap(m_angles, yaw_goal_tolerance);
setupMap(m_distances, xy_goal_tolerance);
setupMap(m_bools, free_goal_velocity);
// Obstacles
setupMap(m_distances, min_obstacle_distance);
setupMap(m_distances, inflation_distance);
setupMap(m_distances, dynamic_obstacle_inflation_distance);
setupMap(m_bools, include_dynamic_obstacles);
setupMap(m_integers, obstacles_poses_affected);
setupMap(m_doubles, obstacle_association_force_inclusion_factor);
setupMap(m_doubles, obstacle_association_cutoff_factor);
// Optimization
setupMap(m_integers, num_inner_iterations);
setupMap(m_integers, num_outer_iterations);
setupMap(m_doubles, penalty_epsilon);
setupMap(m_doubles, max_velocity_x_weight);
setupMap(m_doubles, max_velocity_y_weight);
setupMap(m_doubles, max_velocity_theta_weight);
setupMap(m_doubles, acceleration_limit_x_weight);
setupMap(m_doubles, acceleration_limit_y_weight);
setupMap(m_doubles, acceleration_limit_theta_weight);
setupMap(m_doubles, kinematics_nh_weight);
setupMap(m_doubles, kinematics_forward_drive_weight);
setupMap(m_doubles, kinematics_turning_radius_weight);
setupMap(m_doubles, optimal_time_weight);
setupMap(m_doubles, obstacle_weight);
setupMap(m_doubles, inflation_weight);
setupMap(m_doubles, dynamic_obstacle_weight);
setupMap(m_doubles, dynamic_obstacle_inflation_weight);
setupMap(m_doubles, waypoint_weight);
setupMap(m_doubles, weight_adapt_factor);
// HCP
setupMap(m_bools, enable_hcp);
setupMap(m_bools, enable_mt);
setupMap(m_bools, simple_exploration);
setupMap(m_integers, max_number_classes);
setupMap(m_doubles, selection_cost_hysteresis);
setupMap(m_doubles, selection_prefer_initial_plan);
setupMap(m_doubles, selection_obstacle_cost_scale);
setupMap(m_doubles, selection_waypoint_cost_scale);
setupMap(m_bools, selection_alternative_time_cost);
setupMap(m_integers, roadmap_graph_no_samples);
setupMap(m_doubles, roadmap_graph_area_width);
setupMap(m_doubles, roadmap_graph_area_length_scale);
setupMap(m_doubles, h_signature_prescaler);
setupMap(m_doubles, h_signature_threshold);
setupMap(m_doubles, obstacle_keypoint_offset);
setupMap(m_doubles, obstacle_heading_threshold);
setupMap(m_bools, waypoint_all_candidates);
for (auto iter : m_distances)
{
connect(iter.first, SIGNAL(textEdited(QString)), this, SLOT(updateDistance()));
}
for (auto iter : m_times)
{
connect(iter.first, SIGNAL(textEdited(QString)), this, SLOT(updateTime()));
}
for (auto iter : m_velocities)
{
connect(iter.first, SIGNAL(textEdited(QString)), this, SLOT(updateVelocity()));
}
for (auto iter : m_accelerations)
{
connect(iter.first, SIGNAL(textEdited(QString)), this, SLOT(updateAcceleration()));
}
for (auto iter : m_doubles)
{
connect(iter.first, SIGNAL(textEdited(QString)), this, SLOT(updateDouble()));
}
for (auto iter : m_integers)
{
connect(iter.first, SIGNAL(textEdited(QString)), this, SLOT(updateInteger()));
}
for (auto iter : m_bools)
{
connect(iter.first, SIGNAL(stateChanged(int)), this, SLOT(updateBool()));
}
connect(m_ui->add_config, SIGNAL(clicked(bool)), this, SLOT(addConfig()));
connect(m_ui->config_options, SIGNAL(currentIndexChanged(QString)), this, SLOT(setConfig(QString)));
connect(m_ui->delete_config, SIGNAL(clicked(bool)), this, SLOT(removeConfig()));
}
void ConfigWidget::setOptions()
{
QStringList names;
for(const std::string& name : m_settings->getConfigNames())
{
names << QString(name.c_str());
}
m_ui->config_options->addItems(names);
}
void ConfigWidget::updateDistance()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::Distance dist = value * units::in;
std::string var_name = m_distances[line_edit];
if (var_name == "global_plan_waypoint_separation")
{
m_current->trajectory.global_plan_viapoint_sep = dist.to(units::m);
}
else if (var_name == "max_global_plan_lookahead_distance")
{
m_current->trajectory.max_global_plan_lookahead_dist = dist.to(units::m);
}
else if (var_name == "force_reinit_new_goal_distance")
{
m_current->trajectory.force_reinit_new_goal_dist = dist.to(units::m);
}
else if (var_name == "min_turning_radius")
{
m_current->robot.min_turning_radius = dist.to(units::m);
}
else if (var_name == "wheelbase")
{
m_current->robot.wheelbase = dist.to(units::m);
}
else if (var_name == "xy_goal_tolerance")
{
m_current->goal_tolerance.xy_goal_tolerance = dist.to(units::m);
}
else if (var_name == "min_obstacle_distance")
{
m_current->obstacles.min_obstacle_dist = dist.to(units::m);
}
else if (var_name == "inflation_distance")
{
m_current->obstacles.inflation_dist = dist.to(units::m);
}
else if (var_name == "dynamic_obstacle_inflation_distance")
{
m_current->obstacles.dynamic_obstacle_inflation_dist = dist.to(units::m);
}
else
{
throw UnknownDistanceSettingException(fmt::format("Unknown distance setting: {}", var_name));
}
}
}
void ConfigWidget::updateTime()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::Time time = value * units::s;
std::string var_name = m_times[line_edit];
if (var_name == "dt_ref")
{
m_current->trajectory.dt_ref = time.to(units::s);
}
else if (var_name == "dt_hysteresis")
{
m_current->trajectory.dt_hysteresis = time.to(units::s);
}
else
{
throw UnknownTimeSettingException(fmt::format("Unknown time setting: {}", var_name));
}
}
}
void ConfigWidget::updateVelocity()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::Velocity vel = value * units::in / units::s;
std::string var_name = m_velocities[line_edit];
if (var_name == "max_velocity_x")
{
m_current->robot.max_vel_x = vel.to(units::m / units::s);
}
else if (var_name == "max_velocity_x_backwards")
{
m_current->robot.max_vel_x_backwards = vel.to(units::m / units::s);;
}
else if (var_name == "max_velocity_y")
{
m_current->robot.max_vel_y = vel.to(units::m / units::s);;
}
else
{
throw UnknownVelocitySettingException(fmt::format("Unknown velocity setting: {}", var_name));
}
}
}
void ConfigWidget::updateAcceleration()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::Acceleration acc = value * units::in / units::s / units::s;
std::string var_name = m_accelerations[line_edit];
if (var_name == "acceleration_limit_x")
{
m_current->robot.acc_lim_x = acc.to(units::m / units::s / units::s);;
}
else if (var_name == "acceleration_limit_y")
{
m_current->robot.acc_lim_y = acc.to(units::m / units::s / units::s);;
}
else
{
throw UnknownAccelerationSettingException(fmt::format("Unknown acceleration setting: {}", var_name));
}
}
}
void ConfigWidget::updateAngle()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::Angle angle = value * units::deg;
std::string var_name = m_angles[line_edit];
if (var_name == "yaw_goal_tolerance")
{
m_current->goal_tolerance.yaw_goal_tolerance = angle.to(units::rad);
}
else
{
throw UnknownAngleSettingException(fmt::format("Unknown angle setting: {}", var_name));
}
}
}
void ConfigWidget::updateAngularVelocity()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::AngularVelocity vel = value * units::deg / units::s;
std::string var_name = m_angular_velocities[line_edit];
if (var_name == "max_velocity_theta")
{
m_current->robot.max_vel_theta = vel.to(units::rad / units::s);
}
else
{
throw UnknownAngularVelocitySettingException(fmt::format("Unknown angular velocity setting: {}", var_name));
}
}
}
void ConfigWidget::updateAngularAcceleration()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
units::AngularAcceleration acc = value * units::deg / units::s / units::s;
std::string var_name = m_angular_accelerations[line_edit];
if (var_name == "acceleration_limits_theta")
{
m_current->robot.acc_lim_theta = acc.to(units::rad / units::s / units::s);
}
else
{
throw UnknownAngularAccelerationSettingException(fmt::format("Unknown angular acceleration setting: {}", var_name));
}
}
}
void ConfigWidget::updateDouble()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
double value = text.toDouble(&ok);
if (ok)
{
std::string var_name = m_doubles[line_edit];
if (var_name == "obstacle_association_force_inclusion_factor")
{
m_current->obstacles.obstacle_association_force_inclusion_factor = value;
}
else if (var_name == "obstacle_association_cutoff_factor")
{
m_current->obstacles.obstacle_association_cutoff_factor = value;
}
else if (var_name == "penalty_epsilon")
{
m_current->optim.penalty_epsilon = value;
}
else if (var_name == "max_velocity_x_weight")
{
m_current->optim.weight_max_vel_x = value;
}
else if (var_name == "max_velocity_y_weight")
{
m_current->optim.weight_max_vel_y = value;
}
else if (var_name == "max_velocity_theta_weight")
{
m_current->optim.weight_max_vel_theta = value;
}
else if (var_name == "acceleration_limit_x_weight")
{
m_current->optim.weight_acc_lim_x = value;
}
else if (var_name == "acceleration_limit_y_weight")
{
m_current->optim.weight_acc_lim_y = value;
}
else if (var_name == "acceleration_limit_theta_weight")
{
m_current->optim.weight_acc_lim_theta = value;
}
else if (var_name == "kinematics_nh_weight")
{
m_current->optim.weight_kinematics_nh = value;
}
else if (var_name == "kinematics_forward_drive_weight")
{
m_current->optim.weight_kinematics_forward_drive = value;
}
else if (var_name == "kinematics_turning_radius_weight")
{
m_current->optim.weight_kinematics_turning_radius = value;
}
else if (var_name == "optimal_time_weight")
{
m_current->optim.weight_optimaltime = value;
}
else if (var_name == "obstacle_weight")
{
m_current->optim.weight_obstacle = value;
}
else if (var_name == "inflation_weight")
{
m_current->optim.weight_inflation = value;
}
else if (var_name == "dynamic_obstacle_weight")
{
m_current->optim.weight_dynamic_obstacle = value;
}
else if (var_name == "dynamic_obstacle_inflation_weight")
{
m_current->optim.weight_dynamic_obstacle_inflation = value;
}
else if (var_name == "waypoint_weight")
{
m_current->optim.weight_viapoint = value;
}
else if (var_name == "weight_adapt_factor")
{
m_current->optim.weight_adapt_factor = value;
}
else if(var_name == "selection_cost_hysteresis")
{
m_current->hcp.selection_cost_hysteresis = value;
}
else if(var_name == "selection_prefer_initial_plan")
{
m_current->hcp.selection_prefer_initial_plan = value;
}
else if(var_name == "selection_obstacle_cost_scale")
{
m_current->hcp.selection_obst_cost_scale = value;
}
else if(var_name == "selection_waypoint_cost_scale")
{
m_current->hcp.selection_viapoint_cost_scale = value;
}
else if(var_name == "roadmap_graph_area_width")
{
m_current->hcp.roadmap_graph_area_width = value;
}
else if(var_name == "roadmap_graph_area_length_scale")
{
m_current->hcp.roadmap_graph_area_length_scale = value;
}
else if(var_name == "h_signature_prescaler")
{
m_current->hcp.h_signature_prescaler = value;
}
else if(var_name == "h_signarture_threshold")
{
m_current->hcp.h_signature_threshold = value;
}
else if(var_name == "obstacle_keypoint_offset")
{
m_current->hcp.obstacle_keypoint_offset = value;
}
else if(var_name == "obstacle_heading_threshold")
{
m_current->hcp.obstacle_heading_threshold = value;
}
else
{
throw UnknownDoubleSettingException(fmt::format("Unknown double setting: {}", var_name));
}
}
}
void ConfigWidget::updateInteger()
{
if (!m_current)
{
return;
}
QLineEdit* line_edit = static_cast<QLineEdit*>(sender());
QString text = line_edit->text();
bool ok;
int value = text.toInt(&ok);
if (ok)
{
std::string var_name = m_integers[line_edit];
if (var_name == "min_samples")
{
m_current->trajectory.min_samples = value;
}
else if (var_name == "max_samples")
{
m_current->trajectory.max_samples = value;
}
else if (var_name == "feasibility_check_num_poses")
{
m_current->trajectory.feasibility_check_no_poses = value;
}
else if (var_name == "obstacles_poses_affected")
{
m_current->obstacles.obstacle_poses_affected = value;
}
else if (var_name == "num_inner_iterations")
{
m_current->optim.no_inner_iterations = value;
}
else if (var_name == "num_outer_iterations")
{
m_current->optim.no_outer_iterations = value;
}
else if(var_name == "max_number_classes")
{
m_current->hcp.max_number_classes = value;
}
else if(var_name == "roadmap_graph_no_samples")
{
m_current->hcp.roadmap_graph_no_samples = value;
}
else
{
throw UnknownIntegerSettingException(fmt::format("Unknown integer setting: {}", var_name));
}
}
}
void ConfigWidget::updateBool()
{
if (!m_current)
{
return;
}
QCheckBox* check_box = static_cast<QCheckBox*>(sender());
bool value = check_box->isChecked();
std::string var_name = m_bools[check_box];
if(var_name == "autosize")
{
m_current->trajectory.teb_autosize = value;
}
else if (var_name == "global_plan_overwrite_orientation")
{
m_current->trajectory.global_plan_overwrite_orientation = value;
}
else if (var_name == "allow_init_with_backwards_motion")
{
m_current->trajectory.allow_init_with_backwards_motion = value;
}
else if (var_name == "waypoints_ordered")
{
m_current->trajectory.via_points_ordered = value;
}
else if (var_name == "exact_arc_length")
{
m_current->trajectory.exact_arc_length = value;
}
else if (var_name == "free_goal_velocity")
{
m_current->goal_tolerance.free_goal_vel = value;
}
else if (var_name == "include_dynamic_obstacles")
{
m_current->obstacles.include_dynamic_obstacles = value;
}
else if(var_name == "enable_hcp")
{
m_current->hcp.enable_homotopy_class_planning = value;
}
else if(var_name == "enable_mt")
{
m_current->hcp.enable_multithreading = value;
}
else if(var_name == "simple_exploration")
{
m_current->hcp.simple_exploration = value;
}
else if(var_name == "selection_alternative_time_cost")
{
m_current->hcp.selection_alternative_time_cost = value;
}
else if(var_name == "waypoint_all_candidates")
{
m_current->hcp.viapoints_all_candidates = value;
}
else
{
throw UnknownBooleanSettingException(fmt::format("Unknown boolean setting: {}", var_name));
}
}
void ConfigWidget::addConfig()
{
bool ok;
QString name = QInputDialog::getText(this, tr("Add Config"), tr("Name:"), QLineEdit::Normal, "Default", &ok);
if (ok && !name.isEmpty())
{
m_settings->addConfig(name.toStdString());
m_ui->config_options->addItem(name);
m_name = name.toStdString();
}
}
void ConfigWidget::setConfig(const QString& name)
{
m_name = name.toStdString();
m_current = m_settings->config(m_name);
if (m_current)
{
// Enable
// Trajectory
m_ui->autosize->setEnabled(true);
m_ui->dt_ref->setEnabled(true);
m_ui->dt_hysteresis->setEnabled(true);
m_ui->min_samples->setEnabled(true);
m_ui->max_samples->setEnabled(true);
m_ui->overwrite_global_plan->setEnabled(true);
m_ui->backwards_motion->setEnabled(true);
m_ui->global_plan_waypoint_separation->setEnabled(true);
m_ui->waypoints_ordered->setEnabled(true);
m_ui->max_global_plan_lookahead_distance->setEnabled(true);
m_ui->exact_arc_length->setEnabled(true);
m_ui->force_new_goal_distance->setEnabled(true);
m_ui->feasibility_check_num_poses->setEnabled(true);
// Robot
m_ui->max_velocity_x->setEnabled(true);
m_ui->max_velocity_x_backwards->setEnabled(true);
m_ui->max_velocity_y->setEnabled(true);
m_ui->max_velocity_theta->setEnabled(true);
m_ui->acceleration_limit_x->setEnabled(true);
m_ui->acceleration_limit_y->setEnabled(true);
m_ui->acceleration_limit_theta->setEnabled(true);
m_ui->min_turning_radius->setEnabled(true);
m_ui->wheelbase->setEnabled(true);
// Goal Tolerance
m_ui->yaw_goal_tolerance->setEnabled(true);
m_ui->xy_goal_tolerance->setEnabled(true);
m_ui->free_goal_velocity->setEnabled(true);
// Obstacles
m_ui->min_obstacle_distance->setEnabled(true);
m_ui->inflation_distance->setEnabled(true);
m_ui->dynamic_obstacle_inflation_distance->setEnabled(true);
m_ui->include_dynamic_obstacles->setEnabled(true);
m_ui->obstacles_poses_affected->setEnabled(true);
m_ui->obstacle_association_force_inclusion_factor->setEnabled(true);
m_ui->obstacle_association_cutoff_factor->setEnabled(true);
// Optimization
m_ui->num_inner_iterations->setEnabled(true);
m_ui->num_outer_iterations->setEnabled(true);
m_ui->penalty_epsilon->setEnabled(true);
m_ui->max_velocity_x_weight->setEnabled(true);
m_ui->max_velocity_y_weight->setEnabled(true);
m_ui->max_velocity_theta_weight->setEnabled(true);
m_ui->acceleration_limit_x_weight->setEnabled(true);
m_ui->acceleration_limit_y_weight->setEnabled(true);
m_ui->acceleration_limit_theta_weight->setEnabled(true);
m_ui->kinematics_nh_weight->setEnabled(true);
m_ui->kinematics_forward_drive_weight->setEnabled(true);
m_ui->kinematics_turning_radius_weight->setEnabled(true);
m_ui->optimal_time_weight->setEnabled(true);
m_ui->obstacle_weight->setEnabled(true);
m_ui->inflation_weight->setEnabled(true);
m_ui->dynamic_obstacle_weight->setEnabled(true);
m_ui->dynamic_obstacle_inflation_weight->setEnabled(true);
m_ui->waypoint_weight->setEnabled(true);
m_ui->weight_adapt_factor->setEnabled(true);
// HCP
m_ui->enable_hcp->setEnabled(true);
m_ui->enable_mt->setEnabled(true);
m_ui->simple_exploration->setEnabled(true);
m_ui->max_number_classes->setEnabled(true);
m_ui->selection_cost_hysteresis->setEnabled(true);
m_ui->selection_obstacle_cost_scale->setEnabled(true);
m_ui->selection_prefer_initial_plan->setEnabled(true);
m_ui->selection_waypoint_cost_scale->setEnabled(true);
m_ui->selection_alternative_time_cost->setEnabled(true);
m_ui->roadmap_graph_no_samples->setEnabled(true);
m_ui->roadmap_graph_area_width->setEnabled(true);
m_ui->roadmap_graph_area_length_scale->setEnabled(true);
m_ui->h_signature_prescaler->setEnabled(true);
m_ui->h_signature_threshold->setEnabled(true);
m_ui->obstacle_keypoint_offset->setEnabled(true);
m_ui->obstacle_heading_threshold->setEnabled(true);
m_ui->waypoint_all_candidates->setEnabled(true);
// Set
// Trajectory
m_ui->autosize->setChecked(m_current->trajectory.teb_autosize);
m_ui->dt_ref->setText(QString::number(m_current->trajectory.dt_ref, 'f', 2));
m_ui->dt_hysteresis->setText(QString::number(m_current->trajectory.dt_hysteresis, 'f', 2));
m_ui->min_samples->setText(QString::number(m_current->trajectory.min_samples));
m_ui->max_samples->setText(QString::number(m_current->trajectory.max_samples));
m_ui->overwrite_global_plan->setChecked(m_current->trajectory.global_plan_overwrite_orientation);
m_ui->backwards_motion->setChecked(m_current->trajectory.allow_init_with_backwards_motion);
m_ui->global_plan_waypoint_separation->setText(QString::number((m_current->trajectory.global_plan_viapoint_sep * units::m).to(units::in), 'f', 2));
m_ui->waypoints_ordered->setChecked(m_current->trajectory.via_points_ordered);
m_ui->max_global_plan_lookahead_distance->setText(QString::number((m_current->trajectory.max_global_plan_lookahead_dist * units::m).to(units::in), 'f', 2));
m_ui->exact_arc_length->setChecked(m_current->trajectory.exact_arc_length);
m_ui->force_new_goal_distance->setText(QString::number((m_current->trajectory.force_reinit_new_goal_dist * units::m).to(units::in), 'f', 2));
m_ui->feasibility_check_num_poses->setText(QString::number(m_current->trajectory.feasibility_check_no_poses));
// Robot
m_ui->max_velocity_x->setText(QString::number((m_current->robot.max_vel_x * units::m / units::s).to(units::in / units::s), 'f', 2));
m_ui->max_velocity_x_backwards->setText(QString::number((m_current->robot.max_vel_x_backwards * units::m / units::s).to(units::in / units::s), 'f', 2));
m_ui->max_velocity_y->setText(QString::number((m_current->robot.max_vel_y * units::m / units::s).to(units::in / units::s), 'f', 2));
m_ui->max_velocity_theta->setText(QString::number((m_current->robot.max_vel_theta * units::rad / units::s).to(units::deg / units::s), 'f', 2));
m_ui->acceleration_limit_x->setText(QString::number((m_current->robot.acc_lim_x * units::m / units::s / units::s).to(units::in / units::s / units::s), 'f', 2));
m_ui->acceleration_limit_y->setText(QString::number((m_current->robot.acc_lim_y * units::m / units::s / units::s).to(units::in / units::s / units::s), 'f', 2));
m_ui->acceleration_limit_theta->setText(QString::number((m_current->robot.acc_lim_theta * units::rad / units::s / units::s).to(units::deg / units::s / units::s), 'f', 2));
m_ui->min_turning_radius->setText(QString::number((m_current->robot.min_turning_radius * units::m).to(units::in), 'f', 2));
m_ui->wheelbase->setText(QString::number((m_current->robot.wheelbase * units::m).to(units::in), 'f', 2));
// Goal Tolerance
m_ui->yaw_goal_tolerance->setText(QString::number((m_current->goal_tolerance.yaw_goal_tolerance * units::rad).to(units::deg), 'f', 2));
m_ui->xy_goal_tolerance->setText(QString::number((m_current->goal_tolerance.xy_goal_tolerance * units::m).to(units::in), 'f', 2));
m_ui->free_goal_velocity->setChecked(m_current->goal_tolerance.free_goal_vel);
// Obstacles
m_ui->min_obstacle_distance->setText(QString::number((m_current->obstacles.min_obstacle_dist * units::m).to(units::in), 'f', 2));
m_ui->inflation_distance->setText(QString::number((m_current->obstacles.inflation_dist * units::m).to(units::in), 'f', 2));
m_ui->dynamic_obstacle_inflation_distance->setText(QString::number((m_current->obstacles.dynamic_obstacle_inflation_dist * units::m).to(units::in), 'f', 2));
m_ui->include_dynamic_obstacles->setChecked(m_current->obstacles.include_dynamic_obstacles);
m_ui->obstacles_poses_affected->setText(QString::number(m_current->obstacles.obstacle_poses_affected));
m_ui->obstacle_association_force_inclusion_factor->setText(QString::number(m_current->obstacles.obstacle_association_force_inclusion_factor, 'f', 2));
m_ui->obstacle_association_cutoff_factor->setText(QString::number(m_current->obstacles.obstacle_association_cutoff_factor, 'f', 2));
// Optimization
m_ui->num_inner_iterations->setText(QString::number(m_current->optim.no_inner_iterations));
m_ui->num_outer_iterations->setText(QString::number(m_current->optim.no_outer_iterations));
m_ui->penalty_epsilon->setText(QString::number(m_current->optim.penalty_epsilon, 'f', 2));
m_ui->max_velocity_x_weight->setText(QString::number(m_current->optim.weight_max_vel_x, 'f', 2));
m_ui->max_velocity_y_weight->setText(QString::number(m_current->optim.weight_max_vel_y, 'f', 2));
m_ui->max_velocity_theta_weight->setText(QString::number(m_current->optim.weight_max_vel_theta, 'f', 2));
m_ui->acceleration_limit_x_weight->setText(QString::number(m_current->optim.weight_acc_lim_x, 'f', 2));
m_ui->acceleration_limit_y_weight->setText(QString::number(m_current->optim.weight_acc_lim_y, 'f', 2));
m_ui->acceleration_limit_theta_weight->setText(QString::number(m_current->optim.weight_acc_lim_theta, 'f', 2));
m_ui->kinematics_nh_weight->setText(QString::number(m_current->optim.weight_kinematics_nh, 'f', 2));
m_ui->kinematics_forward_drive_weight->setText(QString::number(m_current->optim.weight_kinematics_forward_drive, 'f', 2));
m_ui->kinematics_turning_radius_weight->setText(QString::number(m_current->optim.weight_kinematics_turning_radius, 'f', 2));
m_ui->optimal_time_weight->setText(QString::number(m_current->optim.weight_optimaltime, 'f', 2));
m_ui->obstacle_weight->setText(QString::number(m_current->optim.weight_obstacle, 'f', 2));
m_ui->inflation_weight->setText(QString::number(m_current->optim.weight_inflation, 'f', 2));
m_ui->dynamic_obstacle_weight->setText(QString::number(m_current->optim.weight_dynamic_obstacle, 'f', 2));
m_ui->dynamic_obstacle_inflation_weight->setText(QString::number(m_current->optim.weight_dynamic_obstacle_inflation, 'f', 2));
m_ui->waypoint_weight->setText(QString::number(m_current->optim.weight_viapoint, 'f', 2));
m_ui->weight_adapt_factor->setText(QString::number(m_current->optim.weight_adapt_factor, 'f', 2));
// HCP
m_ui->enable_hcp->setChecked(m_current->hcp.enable_homotopy_class_planning);
m_ui->enable_mt->setChecked(m_current->hcp.enable_multithreading);
m_ui->simple_exploration->setChecked(m_current->hcp.simple_exploration);
m_ui->max_number_classes->setText(QString::number(m_current->hcp.max_number_classes));
m_ui->selection_cost_hysteresis->setText(QString::number(m_current->hcp.selection_cost_hysteresis, 'f', 2));
m_ui->selection_obstacle_cost_scale->setText(QString::number(m_current->hcp.selection_obst_cost_scale, 'f', 2));
m_ui->selection_prefer_initial_plan->setText(QString::number(m_current->hcp.selection_prefer_initial_plan, 'f', 2));
m_ui->selection_waypoint_cost_scale->setText(QString::number(m_current->hcp.selection_viapoint_cost_scale, 'f', 2));
m_ui->selection_alternative_time_cost->setText(QString::number(m_current->hcp.selection_alternative_time_cost, 'f', 2));
m_ui->roadmap_graph_no_samples->setText(QString::number(m_current->hcp.roadmap_graph_no_samples, 'f', 2));
m_ui->roadmap_graph_area_width->setText(QString::number(m_current->hcp.roadmap_graph_area_width, 'f', 2));
m_ui->roadmap_graph_area_length_scale->setText(QString::number(m_current->hcp.roadmap_graph_area_length_scale, 'f', 2));
m_ui->h_signature_prescaler->setText(QString::number(m_current->hcp.h_signature_prescaler, 'f', 2));
m_ui->h_signature_threshold->setText(QString::number(m_current->hcp.h_signature_threshold, 'f', 2));
m_ui->obstacle_keypoint_offset->setText(QString::number(m_current->hcp.obstacle_keypoint_offset, 'f', 2));
m_ui->obstacle_heading_threshold->setText(QString::number(m_current->hcp.obstacle_heading_threshold, 'f', 2));
m_ui->waypoint_all_candidates->setChecked(m_current->hcp.viapoints_all_candidates);
}
else
{
// Disable
// Trajectory
m_ui->autosize->setEnabled(false);
m_ui->dt_ref->setEnabled(false);
m_ui->dt_hysteresis->setEnabled(false);
m_ui->min_samples->setEnabled(false);
m_ui->max_samples->setEnabled(false);
m_ui->overwrite_global_plan->setEnabled(false);
m_ui->backwards_motion->setEnabled(false);
m_ui->global_plan_waypoint_separation->setEnabled(false);
m_ui->waypoints_ordered->setEnabled(false);
m_ui->max_global_plan_lookahead_distance->setEnabled(false);
m_ui->exact_arc_length->setEnabled(false);
m_ui->force_new_goal_distance->setEnabled(false);
m_ui->feasibility_check_num_poses->setEnabled(false);
// Robot
m_ui->max_velocity_x->setEnabled(false);
m_ui->max_velocity_x_backwards->setEnabled(false);
m_ui->max_velocity_y->setEnabled(false);
m_ui->max_velocity_theta->setEnabled(false);
m_ui->acceleration_limit_x->setEnabled(false);
m_ui->acceleration_limit_y->setEnabled(false);
m_ui->acceleration_limit_theta->setEnabled(false);
m_ui->min_turning_radius->setEnabled(false);
m_ui->wheelbase->setEnabled(false);
// Goal Tolerance
m_ui->yaw_goal_tolerance->setEnabled(false);
m_ui->xy_goal_tolerance->setEnabled(false);
m_ui->free_goal_velocity->setEnabled(false);
// Obstacles
m_ui->min_obstacle_distance->setEnabled(false);
m_ui->inflation_distance->setEnabled(false);
m_ui->dynamic_obstacle_inflation_distance->setEnabled(false);
m_ui->include_dynamic_obstacles->setEnabled(false);
m_ui->obstacles_poses_affected->setEnabled(false);
m_ui->obstacle_association_force_inclusion_factor->setEnabled(false);
m_ui->obstacle_association_cutoff_factor->setEnabled(false);
// Optimization
m_ui->num_inner_iterations->setEnabled(false);
m_ui->num_outer_iterations->setEnabled(false);
m_ui->penalty_epsilon->setEnabled(false);
m_ui->max_velocity_x_weight->setEnabled(false);
m_ui->max_velocity_y_weight->setEnabled(false);
m_ui->max_velocity_theta_weight->setEnabled(false);
m_ui->acceleration_limit_x_weight->setEnabled(false);
m_ui->acceleration_limit_y_weight->setEnabled(false);
m_ui->acceleration_limit_theta_weight->setEnabled(false);
m_ui->kinematics_nh_weight->setEnabled(false);
m_ui->kinematics_forward_drive_weight->setEnabled(false);
m_ui->kinematics_turning_radius_weight->setEnabled(false);
m_ui->optimal_time_weight->setEnabled(false);
m_ui->obstacle_weight->setEnabled(false);
m_ui->inflation_weight->setEnabled(false);
m_ui->dynamic_obstacle_weight->setEnabled(false);
m_ui->dynamic_obstacle_inflation_weight->setEnabled(false);
m_ui->waypoint_weight->setEnabled(false);
m_ui->weight_adapt_factor->setEnabled(false);
// HCP
m_ui->enable_hcp->setEnabled(false);
m_ui->enable_mt->setEnabled(false);
m_ui->simple_exploration->setEnabled(false);
m_ui->max_number_classes->setEnabled(false);
m_ui->selection_cost_hysteresis->setEnabled(false);
m_ui->selection_obstacle_cost_scale->setEnabled(false);
m_ui->selection_prefer_initial_plan->setEnabled(false);
m_ui->selection_waypoint_cost_scale->setEnabled(false);
m_ui->selection_alternative_time_cost->setEnabled(false);
m_ui->roadmap_graph_no_samples->setEnabled(false);
m_ui->roadmap_graph_area_width->setEnabled(false);
m_ui->roadmap_graph_area_length_scale->setEnabled(false);
m_ui->h_signature_prescaler->setEnabled(false);
m_ui->h_signature_threshold->setEnabled(false);
m_ui->obstacle_keypoint_offset->setEnabled(false);
m_ui->obstacle_heading_threshold->setEnabled(false);
m_ui->waypoint_all_candidates->setEnabled(false);
}
}
void ConfigWidget::removeConfig()
{
int index = m_ui->config_options->currentIndex();
if (index >= 0)
{
m_settings->removeConfig(m_name);
m_ui->config_options->removeItem(index);
}
}
}
}
}
|
ed0b1dd1732197928080008e35192e7693d81f21
|
365fc4bbaf92417ebb031bce628e9aaa141241fb
|
/05-ScenceManager/WeaponAttack.h
|
25746ad72275c5a2ad26065f9ed4245a39b52455
|
[] |
no_license
|
ThuTinh/GAME_UPDATE
|
30b45d6d444865f186486b6457b32a7a0aea3329
|
af2e174a20cbf3553c2bdee7b2c072a0a6fff26a
|
refs/heads/master
| 2022-11-20T19:15:17.739302
| 2020-07-24T12:58:45
| 2020-07-24T12:58:45
| 258,240,574
| 0
| 0
| null | 2020-07-24T12:58:46
| 2020-04-23T14:59:07
|
C++
|
UTF-8
|
C++
| false
| false
| 200
|
h
|
WeaponAttack.h
|
#pragma once
#include"Item.h"
class Sword : public Item
{
public:
Sword();
~Sword();
virtual void Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects);
void onPlayerContact() override;
private:
};
|
23fd5d3f4952559b7cadd656ebb4dd6f0230a13b
|
46e07ee08e7da16f485e4ecaff4c904f4d35e861
|
/cpp/app/is_vowel/is_vowel.cpp
|
b2e9079e06b3bcb7c3bc63b52e6bcbf0cd23e6ec
|
[] |
no_license
|
xifeng205/test
|
3f5d5419ebaee2b6521842ac07b9036ec905fcb7
|
91935b42eda99200a411395f8708bef9027249a9
|
refs/heads/master
| 2023-02-02T12:53:29.932233
| 2020-12-17T06:58:15
| 2020-12-17T06:58:15
| 322,201,691
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 949
|
cpp
|
is_vowel.cpp
|
/*********************************************************************
* Author : cuiyunpeng
* Email : @163.com
* Create time : 2020-08-01 14:22
* Last modified : 2020-08-01 14:22
* Filename : is_vowel.cpp
* Description :
*********************************************************************/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
namespace tools_n {
bool is_vowel(char chr) {
vector<char> vowel =
{'a','o','e','u','i','A','O','E','U','I'};
return std::any_of(vowel.begin(), vowel.end(),
[chr](char ch) { return ch == chr; });
}
}
int main(int argc, char **argv)
{
std::cout << tools_n::is_vowel('C') << std::endl;
std::cout << tools_n::is_vowel('c') << std::endl;
std::cout << tools_n::is_vowel('a') << std::endl;
std::cout << tools_n::is_vowel('A') << std::endl;
return 0;
}
|
fa5eaafdef7186304e2407a80bac464395c15c7a
|
5569ec3412d181e442350e8513536196984bb1c4
|
/project_1/client/udp_handler.cc
|
b90847f6b531ecf2505f049cd66515db93ebadb0
|
[] |
no_license
|
SanjayYr/DistributedSystemsProject1
|
478a76175f769b46076f38d201d9e03bc54e3cc1
|
ae42e241b1216785af0a6b776146fd84294fc82d
|
refs/heads/master
| 2021-04-26T23:26:03.820726
| 2018-03-06T18:58:13
| 2018-03-06T18:58:13
| 123,993,249
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,334
|
cc
|
udp_handler.cc
|
#include "udp_handler.h"
UDPReceiver::UDPReceiver(uint16_t port){
std::cout << "UDP listner on Port: " << port << std::endl;
fd_rx = socket(AF_INET, SOCK_DGRAM, 0);
if(fd_rx < 0){
perror("OS did not give an fd for UDP rx socket");
}
optval = 1;
setsockopt(fd_rx, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int));
clientadd.sin_family = AF_INET;
clientadd.sin_addr.s_addr = htonl(INADDR_ANY);
clientadd.sin_port = htons(port);
if(bind(fd_rx, (struct sockaddr *)&clientadd,
sizeof(clientadd)) < 0){
perror("ERROR on binding");
}
this->recv_thread = std::thread(&UDPReceiver::receive_monitor, this, 99);
}
int UDPReceiver::receive_monitor(uint32_t tid){
std::cout << "receiver thread created TID: " << tid << std::endl;
int len;
socklen_t socklen = sizeof(clientadd);
struct sockaddr_in recvadd;
memset((char *)&recvadd, 0, sizeof(recvadd));
while(1){
len = recvfrom(fd_rx, buf, kBUFF_SIZE, 0,
(struct sockaddr *)&recvadd, &socklen);
if(len > 0){
std::cout << "Received: " << buf << "\n--"
<< "From:" << inet_ntoa(recvadd.sin_addr) << std::endl;
}
}
}
int UDPReceiver::join_all(){
this->recv_thread.join();
}
|
1a0b54718c385b322d3ada68fcf4c4d9dfc981c6
|
aeb70bce11a92577de4cf4d800b201728912d0c7
|
/BasicEngine/TextureCache.h
|
7d703a8ae918941d33ad7eef47e1199fe8196a03
|
[] |
no_license
|
jaidurn/BasicEngine
|
435d912d0daa151ab8123dc8b966ec83aba8a4fc
|
eedbd556cc6fe8fb01afb1a968988cc7c0d7b20f
|
refs/heads/master
| 2022-09-17T02:08:36.585500
| 2019-11-01T10:09:34
| 2019-11-01T10:09:34
| 218,895,473
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 866
|
h
|
TextureCache.h
|
#pragma once
//==========================================================================================
// File Name:
// Author:
// Date Created:
// Purpose:
// Allows for creation, storing, and accessing textures.
// This keeps the textures from being created multiple times.
//==========================================================================================
#include <map>
#include <string>
#include <SDL.h>
class Texture;
typedef std::string string;
class TextureCache
{
public:
TextureCache(SDL_Renderer *renderer,
const Uint8 redKey,
const Uint8 greenKey,
const Uint8 blueKey);
~TextureCache();
Texture* getTexture(string texturePath);
void setRenderer(SDL_Renderer *renderer);
private:
std::map<string, Texture*> m_cache;
SDL_Renderer *m_renderer;
Uint8 m_redKey;
Uint8 m_greenKey;
Uint8 m_blueKey;
void cleanUp();
};
|
426eca73776789df8842d7359231840a31f533c6
|
a97896728e984e349460851c572df0885f7a445e
|
/Semestre anterior/Faculdade Juninho/Estrutura de Dados/Estrutura de Dados/Nova pasta/lista 1 ex4.cpp
|
06dd779201435ae850b1e6b3ad74f238f286eb39
|
[] |
no_license
|
Euclides-R/Studies-Faculdade
|
5efaa6c238b7d1be000c6733ef912606fcd09dff
|
e2d5301e760e34abfd39d23756f8078a0a9d9249
|
refs/heads/main
| 2023-05-04T11:35:54.997157
| 2021-05-28T00:37:15
| 2021-05-28T00:37:15
| 246,105,688
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 632
|
cpp
|
lista 1 ex4.cpp
|
// Autor: Bruno Nunes Serrano
// Cel: +55 41 99681 6778
#include <iostream>
#include <tchar.h>
using namespace std;
double soma=0;
double somarElementosPares(double vet[], int n){
int conv;
for(int i=0;i<n;i++){
conv=(int)vet[i];
if (conv%2==0){
soma=soma+vet[i];
}
}
return soma;
}
int main (int argc, char *argv[]){
_tsetlocale(LC_ALL,_T("portuguese"));
double vetor[10];
cout<<"Digite 10 valores num�ricos\n";
for(int i=0;i<10;i++){
cout<<"Digite o valor para a posi��o "<<i+1<<" :";
cin>>vetor[i];
}
somarElementosPares(vetor,10);
cout<<"\n\nSoma dos valores pares �: "<<soma;
return 0;}
|
5fa243479476ffb2f90399652b2395d13ffa97ad
|
54001b746c70dff858b0b6310ab65958d0b2f7f1
|
/Engine/Code/Engine/Net/UDP/Data/NetSessionStateMachine/NetSessionStateMachineEnd.hpp
|
fd8b2387c20ac981f0c93510caebca04a8791494
|
[] |
no_license
|
atbaird/ProceduralSystemsForNonCombatRPG
|
024bccb62d997f430d8c5283d837cddfb386ff95
|
70ae98a38f89e74339b46422ff6ab02a9a584f9b
|
refs/heads/master
| 2021-01-20T13:27:36.642071
| 2017-05-06T23:20:03
| 2017-05-06T23:20:03
| 90,496,215
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 504
|
hpp
|
NetSessionStateMachineEnd.hpp
|
#pragma once
#ifndef NETSESSIONSTATEMACHINEEND_HPP
#define NETSESSIONSTATEMACHINEEND_HPP
class NetSession;
class NetSessionStateMachineEnd
{
public:
//State Machine end functions
static void InvalidStateEnd(NetSession* session);
static void SetupStateEnd(NetSession* session);
static void DisconnectedStateEnd(NetSession* session);
static void ConnectedStateEnd(NetSession* session);
static void HostingStateEnd(NetSession* session);
static void JoiningStateEnd(NetSession* session);
};
#endif
|
1faa889dbd681bb246927f8aa31fa05f15c93c41
|
13bfcfd7492f3f4ee184aeafd0153a098e0e2fa5
|
/Kattis/keytocrypto.cpp
|
9769ea957d8cc8276bed86ef0823bdbdc97603fc
|
[] |
no_license
|
jqk6/CodeArchive
|
fc59eb3bdf60f6c7861b82d012d298f2854d7f8e
|
aca7db126e6e6f24d0bbe667ae9ea2c926ac4a5f
|
refs/heads/master
| 2023-05-05T09:09:54.032436
| 2021-05-20T07:10:02
| 2021-05-20T07:10:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 284
|
cpp
|
keytocrypto.cpp
|
#include<iostream>
using namespace std;
#define OW0 ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int main(){OW0
string e, k;
cin>>e>>k;
int s = k.size();
for(int i = 0; i < e.size(); i++){
k.push_back((e[i]-k[i]+26)%26 + 'A');
}
k.erase(0, s);
cout<<k;
return 0;
}
|
1f57b4e60bdd648121b6b9e30ba6af88e35b9188
|
f7b876a11cc15cec6a5b377df3e915aaf5bcc289
|
/8_Array/ReverseArrayInplace.cpp
|
f3a8971bb3373c896221bd7c78cb89afbe1d17be
|
[] |
no_license
|
AniRobotics/CPP-Fundamental-Problems
|
01a25962f998689364a52ed2c04f544a75ec2d7d
|
9f0c2641a54022a4acee8f21cad22db261c4aeff
|
refs/heads/master
| 2021-04-22T02:00:15.944414
| 2020-09-15T16:42:31
| 2020-09-15T16:42:31
| 249,841,528
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 453
|
cpp
|
ReverseArrayInplace.cpp
|
#include <iostream>
using namespace std;
int main(int argc, char** argv){
int start_ind = 1, end_ind = 3;
int arr[] = {1,2,3,4,5,6};
int temp;
while (start_ind < end_ind) {
temp = arr[start_ind];
arr[start_ind] = arr[end_ind];
arr[end_ind] = temp;
start_ind++;
end_ind--;
}
// Print the reversed array
for(int i = 0; i < 6; i++) {
std::cout << arr[i] << ",";
}
std::cout << std::endl;
return 0;
}
|
7fafb730eb50ee27966a4298da459a2c03bb6fc9
|
36ecbb92e2d5c6d9f4fd504d0d199d1d4e46f5c7
|
/src/randomRenders.cpp
|
fb3a7dece8571520a71abf1d3a4823726cfc54ea
|
[] |
no_license
|
ahota/pbnj_apps
|
b287c70a6ac9e71bece89bacfc21af39c479f234
|
a0c4247e5431e9c5b1ee31952e4aa950b71e1405
|
refs/heads/master
| 2020-03-29T09:45:12.788223
| 2018-09-21T14:08:31
| 2018-09-21T14:08:31
| 149,772,580
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,443
|
cpp
|
randomRenders.cpp
|
#include <pbnj.h>
#include <Camera.h>
#include <Configuration.h>
#include <Particles.h>
#include <Renderer.h>
#include <Streamlines.h>
#include <TimeSeries.h>
#include <TransferFunction.h>
#include <Volume.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include <dirent.h>
std::string imageFamily(std::string filename, unsigned int count,
float Ks=-1.f)
{
std::string::size_type index;
index = filename.rfind('.');
std::string base = filename.substr(0, index);
std::string family = std::to_string(count);
if(Ks != -1.f)
{
char spec[8];
std::sprintf(spec, "%.1f", Ks);
family += '.';
family += spec;
family.insert(0, 8 - family.length(), '0');
}
else
{
family.insert(0, 4 - family.length(), '0');
}
std::string ext = filename.substr(index);
return base + '.' + family + ext;
}
int main(int argc, const char **argv)
{
if(argc != 2 || std::strcmp(argv[1], "-h") == 0 ||std::strcmp(argv[1], "--help") == 0) {
{
std::cerr << "Creates a number of renders for config files in a"
<< std::endl
<< " given directory. For use with testing goldfish."
<< std::endl
<< " Only works for single volumes, no timeseries data"
<< std::endl;
}
std::cerr << "Usage: " << argv[0] << " <config dir>" << std::endl;
return 1;
}
DIR *directory = opendir(argv[1]);
struct dirent *ent;
std::vector<std::string> configFiles;
if(directory != NULL)
{
ent = readdir(directory);
while(ent != NULL)
{
if(ent->d_name[0] != '.')
{
std::string fullname = std::string(argv[1])+'/'+ent->d_name;
configFiles.push_back(fullname);
}
ent = readdir(directory);
}
}
else
{
std::cerr << "Could not open directory " << argv[1] << std::endl;
return 1;
}
for(int configIndex = 0; configIndex < configFiles.size(); configIndex++)
{
std::cerr << "file: " << configFiles[configIndex] << std::endl;
pbnj::ConfigReader *reader = new pbnj::ConfigReader();
rapidjson::Document json;
reader->parseConfigFile(configFiles[configIndex], json);
pbnj::Configuration *config = new pbnj::Configuration(json);
pbnj::pbnjInit(&argc, argv);
unsigned int numRenders = 1;
unsigned int specularSteps = 10;
float specularDelta = 0.1;
pbnj::Volume *volume;
pbnj::Streamlines *streamlines;
pbnj::Particles *particles;
bool isSurface = false;
pbnj::CONFTYPE confType = config->getConfigType(config->dataFilename);
if(confType == pbnj::PBNJ_VOLUME)
{
pbnj::CONFSTATE confState = config->getConfigState();
if(confState == pbnj::SINGLE_VAR)
{
volume = new pbnj::Volume(config->dataFilename,
config->dataVariable, config->dataXDim, config->dataYDim,
config->dataZDim);
}
else if(confState == pbnj::SINGLE_NOVAR)
{
volume = new pbnj::Volume(config->dataFilename, config->dataXDim,
config->dataYDim, config->dataZDim);
}
isSurface = (config->isosurfaceValues.size() > 0);
}
else if(confType == pbnj::PBNJ_STREAMLINES)
{
streamlines = new pbnj::Streamlines(config->dataFilename);
isSurface = true;
}
else if(confType == pbnj::PBNJ_PARTICLES)
{
particles = new pbnj::Particles(config->dataFilename);
isSurface = true;
}
else
{
std::cerr << "Config file either invalid or unsupported";
std::cerr << std::endl;
}
pbnj::Camera *camera = new pbnj::Camera(config->imageWidth,
config->imageHeight);
camera->setPosition(config->cameraX, config->cameraY, config->cameraZ);
camera->setUpVector(config->cameraUpX, config->cameraUpY,
config->cameraUpZ);
if(confType == pbnj::PBNJ_STREAMLINES &&
config->dataFilename.find("bfield") == std::string::npos)
{
camera->setView(-config->cameraX, -config->cameraY, -50);
}
else
{
camera->centerView();
}
std::random_device rand_device;
std::mt19937 generator(rand_device());
std::uniform_int_distribution<> cam_x(-1.0*config->dataXDim,
1.0*config->dataXDim);
std::uniform_int_distribution<> cam_y(-1.0*config->dataYDim,
1.0*config->dataYDim);
std::uniform_int_distribution<> cam_z(-1.0*config->dataZDim,
1.0*config->dataZDim);
/*
if(confType == pbnj::PBNJ_STREAMLINES)
{
cam_x = std::uniform_int_distribution<>(streamlines->getBounds()[0], streamlines->getBounds()[1]);
cam_y = std::uniform_int_distribution<>(streamlines->getBounds()[2], streamlines->getBounds()[3]);
cam_z = std::uniform_int_distribution<>(streamlines->getBounds()[4], streamlines->getBounds()[5]);
}
*/
pbnj::Renderer *renderer = new pbnj::Renderer();
renderer->setSamples(config->samples);
renderer->setBackgroundColor(config->bgColor);
renderer->setCamera(camera);
if(!isSurface)
{
volume->setColorMap(config->colorMap);
volume->setOpacityMap(config->opacityMap);
volume->attenuateOpacity(config->opacityAttenuation);
}
bool volumeRender = (config->isosurfaceValues.size() == 0);
for(int render = 0; render < numRenders; render++)
{
for(int step = 0; step < specularSteps; step++)
{
float Ks = specularDelta * step;
if(confType == pbnj::PBNJ_STREAMLINES)
{
streamlines->setSpecular(Ks);
renderer->addSubject(streamlines);
}
else if(confType == pbnj::PBNJ_PARTICLES)
{
particles->setSpecular(Ks);
renderer->addSubject(particles);
}
else
{
std::cerr << "oops" << std::endl;
}
std::string imageFilename = imageFamily(config->imageFilename, render, Ks);
renderer->renderImage(imageFilename);
std::cout << "rendered to " << imageFilename << std::endl;
}
float cx = cam_x(generator), cy = cam_y(generator), cz = cam_z(generator);
std::cerr << "DEBUG: " << render << " " << cx << " " << cy << " " << cz << std::endl;
camera->setPosition(cx, cy, cz);
camera->setUpVector(0, 1, 0);
camera->centerView();
//std::vector<float> streamlinesCenter = streamlines->getCenter();
//std::vector<float> view = {cx - streamlinesCenter[0], cy - streamlinesCenter[1], cz - streamlinesCenter[2]};
//camera->setView(streamlines->getCenter());
}
/*
if(volumeRender)
{
//renderer->setVolume(volume);
renderer->addSubject(volume);
std::string imageFilename = imageFamily(config->imageFilename, render);
renderer->renderImage(imageFilename);
}
else
{
//renderer->setIsosurface(volume, config->isosurfaceValues);
for(int step = 0; step < specularSteps; step++)
{
float Ks = specularDelta * step;
//renderer->setMaterialSpecular(Ks);
renderer->addSubject(volume, Ks);
std::string imageFilename = imageFamily(config->imageFilename,
render, Ks);
renderer->renderImage(imageFilename);
}
}
}
*/
//std::string imageFilename = imageFamily(config->imageFilename, numRenders);
//renderer->renderImage(imageFilename);
}
return 0;
}
|
ed70fe4464911300ce1458a3d0c86ec1c1f0a1f0
|
285c6f7328fe80e60feff6326b8a31e0d0dd7cc7
|
/TextBasedAdventure/ProcessInput.cpp
|
346183ad6d8fa1d29909a8c03ef894267e38ff10
|
[] |
no_license
|
james-a-henderson/TextBasedAdventure
|
1fa22b12d0b4161ede9428a94958ccfcb8284322
|
2ea118db4f05ddbc3e140b06eeac5d4784f1e5bb
|
refs/heads/master
| 2021-05-28T08:54:55.338811
| 2015-02-14T04:57:07
| 2015-02-14T04:57:07
| 27,137,281
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,141
|
cpp
|
ProcessInput.cpp
|
#include "GameState.h"
#include "Item.h"
#include "Room.h"
#include <string>
#include <iostream>
#include <boost/range/algorithm/count.hpp>
#include <boost/algorithm/string.hpp>
#include <vector>
using namespace std;
bool verifyCommand(string command, vector<string> * inputVec);
bool verifyCommand(string command, vector<string>* inputVec, int start, int end);
//Processes input
/*
When processing an input,
use this format for checking if a specific word was inputted:
else if(boost::iequals(inputVec.at(wordNum), word))
where wordNum is the specific word needing to be processed
(0 for first word, 1 for second word, etc)
and word is the word that the input is being checked against
if wordNum is > 0, first check that inputVec is big enough
format
else if(inputVec.size() > (wordNum + 1) && boost::iequals(inputVec.at(wordNum), word))
**exception: use only if specific case doesn't matter. If case does matter, use:
else if(inputVec.at(wordNum) == word)
*/
void processInput(string input, GameState* game)
{
//Splits each word in the input string into a seperate string,
//which are then stored in the vector inputVec.
vector<string> inputVec;
boost::split(inputVec, input, boost::is_any_of(" "), boost::token_compress_off);
int wordCount = boost::count(input, ' ');
bool inputProcessed; //stores whether or not an item or room processed the input
//processes input in the current room
inputProcessed = game->getCurrentRoom()->processInput(game, input);
if (!inputProcessed) //if there was no command relevent to the current room
{
//process input in the inventory
inputProcessed = game->processInventoryInput(input);
}
if (!inputProcessed) //if there was no command relevent to the inventory or current room
{
//Exits game if input is exit (ignoring case).
if (boost::iequals("exit", input))
{
game->setExit(true);
}
else if (boost::iequals("dance", input))
{
cout << "Why would you do that?\n";
}
else if (boost::iequals("jump", input.substr(0, 4)))
{
if (input.length() == 4)
cout << "You jump in place\n";
else if (inputVec.size() > 2)
{
cout << "You can jump, but not ";
for (int i = 1; i < inputVec.size(); i++)
cout << inputVec.at(i) << ' ';
cout << "style\n";
}
else if (boost::iequals(" up", input.substr(4, 3)))
cout << "You jump straight up.\n";
else if (boost::iequals(" down", input.substr(4, 5)))
cout << "You jump straight down to your death.\n";
else
cout << "You do not know how to jump " << inputVec.at(1) << " style.\n";
}
else if (boost::iequals("look", input))
{
game->getCurrentRoom()->look();
}
else if (boost::iequals("view inventory", input))
{
game->viewInventory();
}
else if (boost::iequals("switch", input)) //test
{
game->getCurrentRoom()->exit("switch", game);
cout << "You switch rooms.\n";
}
else if (boost::iequals("turn down for what", input))
{
cout << "That song is terrible.\n";
}
//default case. If input does not match any specific case, this executes.
else
{
cout << "You do not know how to " << input << ".\n";
}
}
}
|
4164769518c4551a708683f927e60e90f9c10fd7
|
5545be3e081642326dac86010d5b12ea42b7f662
|
/pa2/Decryption.cpp
|
e47e803f4bc7d8dc6abd91832ea052f9b60423f2
|
[] |
no_license
|
JingyuZhaooo/Professional-C-plus-plus
|
7bc8a304a20d8452f21962412c7ae3bbb92b9819
|
eb856356041e1ae4955113ef3349f4e362d019f0
|
refs/heads/master
| 2021-04-29T19:26:02.075999
| 2017-01-06T11:15:36
| 2017-01-06T11:15:36
| 78,199,567
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,507
|
cpp
|
Decryption.cpp
|
#include "Decryption.h"
#include <fstream>
#include <iostream>
#include <tbb/parallel_invoke.h>
#include "Sha1.h"
#include <string>
#include "Timer.h"
#include <ctype.h>
Decryption::Decryption()
{
}
Decryption::~Decryption()
{
for (auto iter : mSolved)
{
delete iter.second;
}
}
void Decryption::Decrypt(Dictionary& myDict, std::ifstream& fileName)
{
std::vector<decryptedInfo*> unsolved;
std::string str;
int entryNumCount = 1;
while (std::getline(fileName, str))
{
std::string* password = myDict.FindMatch(str);
decryptedInfo* currInfo = new decryptedInfo();
currInfo->entryNum = entryNumCount;
currInfo->hex_str = str;
if (password != nullptr)
{
currInfo->textSol = *password;
mSolved.emplace(currInfo->entryNum, currInfo);
entryNumCount++;
}
else
{
currInfo->textSol = "?????";
unsolved.push_back(currInfo);
entryNumCount++;
}
}
Timer timer1;
timer1.start();
for (auto& i : unsolved)
{
BruteForce(i);
mSolved.emplace(i->entryNum, i);
}
double elapsed1 = timer1.getElapsed();
std::cout << "Serial Brute Force: " << elapsed1 << " seconds" << std::endl;
Timer timer;
timer.start();
tbb::parallel_invoke(
[&, this]() { BruteForceHelper(unsolved, "aaaa", "d999"); },
[&, this]() { BruteForceHelper(unsolved, "eaaa", "h999"); },
[&, this]() { BruteForceHelper(unsolved, "iaaa", "l999"); },
[&, this]() { BruteForceHelper(unsolved, "maaa", "p999"); },
[&, this]() { BruteForceHelper(unsolved, "qaaa", "t999"); },
[&, this]() { BruteForceHelper(unsolved, "uaaa", "x999"); },
[&, this]() { BruteForceHelper(unsolved, "yaaa", "1999"); },
[&, this]() { BruteForceHelper(unsolved, "2aaa", "5999"); },
[&, this]() { BruteForceHelper(unsolved, "6aaa", "9999"); }
);
double elapsed = timer.getElapsed();
std::cout << "Parallel Brute Force: " << elapsed << " seconds" << std::endl;
for (auto i : unsolved)
{
mSolved.emplace(i->entryNum, i);
}
std::ofstream text("pass_solved.txt");
if (text.is_open())
{
for (int i = 1; i < entryNumCount; i++)
{
text << mSolved.find(i)->second->hex_str << "," << mSolved.find(i)->second->textSol << "\n";
}
text.close();
}
}
void Decryption::BruteForce(decryptedInfo* info)
{
int countingMachine[] = { -1, -1, -1, -1 }; //using base 36
int count = 0; // this records the last number
unsigned char hash[20];
char hex_str[41];
while (true)
{
std::string possiblePassword;
Convert36(countingMachine, possiblePassword);
sha1::calc(possiblePassword.c_str(), possiblePassword.length(), hash);
sha1::toHexString(hash, hex_str);
if (strcmp(hex_str,info->hex_str.c_str()) == 0)
{
info->textSol = possiblePassword;
return;
}
if (countingMachine[3] < 36) // if the last number is less than 35, we can add one to it
{
countingMachine[3] += 1;
}
else if (countingMachine[2] < 36 ) // if the last number is 35, we can set it back to zero and increase the 3rd number by one
{
countingMachine[2] += 1;
countingMachine[3] = 0;
}
else if (countingMachine[1] < 36)
{
countingMachine[1] += 1;
countingMachine[2] = 0;
countingMachine[3] = 0;
}
else if (countingMachine[0] < 36)
{
countingMachine[0] += 1;
countingMachine[1] = 0;
countingMachine[2] = 0;
countingMachine[3] = 0;
}
else if (countingMachine[0] = 36)
{
break;
}
}
return;
}
void Decryption::Convert36(int count[], std::string& str) // convert the base 36 number to a string
{
for (int i = 3; i >= 0; i--)
{
if (count[i] == -1)
{
break;
}
if (count[i] < 26)
{
str += (count[i] + 'a');
}
else
{
str += ((count[i] - 26) + '0');
}
}
}
void Decryption::BruteForceHelper(std::vector<decryptedInfo*>& unsolved, std::string starting, std::string ending)
{
unsigned char hash[20];
char hex_str[41];
int countingMachine[4];
char char1 = starting[0];
char char2 = starting[1];
char char3 = starting[2];
char char4 = starting[3];
//std::cout << int(char1) << std::endl;
if (isalpha(char1))
{
countingMachine[0] = char1 - 97;
}
else
{
countingMachine[0] = char1 - 22;
}
if (isalpha(char2))
{
countingMachine[1] = char2 - 97;
}
else
{
countingMachine[1] = char2 - 22;
}
if (isalpha(char3))
{
countingMachine[2] = char3 - 97;
}
else
{
countingMachine[2] = char3 - 22;
}
if (isalpha(char4))
{
countingMachine[3] = char4 - 97;
}
else
{
countingMachine[3] = char4 - 22;
}
for (auto& info : unsolved)
{
while(true)
{
std::string toEvaluate;
Convert36(countingMachine, toEvaluate);
sha1::calc(toEvaluate.c_str(), toEvaluate.length(), hash);
sha1::toHexString(hash, hex_str);
if (strcmp(hex_str, info->hex_str.c_str()) == 0)
{
info->textSol = toEvaluate;
break;
}
if (toEvaluate.compare(ending) == 0) // found it!
{
break;
}
if (countingMachine[3] < 36) // if the last number is less than 35, we can add one to it
{
countingMachine[3] += 1;
}
else if (countingMachine[2] < 36) // if the last number is 35, we can set it back to zero and increase the 3rd number by one
{
countingMachine[2] += 1;
countingMachine[3] = 0;
}
else if (countingMachine[1] < 36)
{
countingMachine[1] += 1;
countingMachine[2] = 0;
countingMachine[3] = 0;
}
else if (countingMachine[0] < 36)
{
countingMachine[0] += 1;
countingMachine[1] = 0;
countingMachine[2] = 0;
countingMachine[3] = 0;
}
else if (countingMachine[0] = 36)
{
break;
}
}
return;
}
}
|
dd46aec030c359e25eaf6b47527123945e654d91
|
a61ee3ce335c9747da70b5cfec2ac48510243722
|
/MADVPano/exiv2/source/webpimage.cpp
|
13bac54607c31ad7c00456d72c44595f6bcd962a
|
[] |
no_license
|
MADV360/ImmoviewerMadventureDemo_iOS
|
3b06cfeae8b1868e2fdebfe31c8f681b006a61e4
|
c2f2651e34f6ec099e298cb4ca2d0dde7cac9925
|
refs/heads/master
| 2021-05-09T22:22:23.348207
| 2019-04-10T09:59:47
| 2019-04-10T09:59:47
| 118,747,968
| 3
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 31,821
|
cpp
|
webpimage.cpp
|
// ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2018 Exiv2 authors
* This program is part of the Exiv2 distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
File: webpimage.cpp
*/
/*
Google's WEBP container spec can be found at the link below:
https://developers.google.com/speed/webp/docs/riff_container
*/
// *****************************************************************************
// included header files
#include "../include/config.h"
#include "webpimage.hpp"
#include "image_int.hpp"
#include "enforce.hpp"
#include "futils.hpp"
#include "basicio.hpp"
#include "tags.hpp"
#include "tags_int.hpp"
#include "types.hpp"
#include "tiffimage.hpp"
#include "tiffimage_int.hpp"
#include "convert.hpp"
#include <cmath>
#include <iomanip>
#include <string>
#include <cstring>
#include <iostream>
#include <sstream>
#include <cassert>
#include <cstdio>
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
// *****************************************************************************
// class member definitions
namespace Exiv2 {
namespace Internal {
}} // namespace Internal, Exiv2
namespace Exiv2 {
using namespace Exiv2::Internal;
WebPImage::WebPImage(BasicIo::AutoPtr io)
: Image(ImageType::webp, mdNone, io)
{
} // WebPImage::WebPImage
std::string WebPImage::mimeType() const
{
return "image/webp";
}
/* =========================================== */
/* Misc. */
const byte WebPImage::WEBP_PAD_ODD = 0;
const int WebPImage::WEBP_TAG_SIZE = 0x4;
/* VP8X feature flags */
const int WebPImage::WEBP_VP8X_ICC_BIT = 0x20;
const int WebPImage::WEBP_VP8X_ALPHA_BIT = 0x10;
const int WebPImage::WEBP_VP8X_EXIF_BIT = 0x8;
const int WebPImage::WEBP_VP8X_XMP_BIT = 0x4;
/* Chunk header names */
const char* WebPImage::WEBP_CHUNK_HEADER_VP8X = "VP8X";
const char* WebPImage::WEBP_CHUNK_HEADER_VP8L = "VP8L";
const char* WebPImage::WEBP_CHUNK_HEADER_VP8 = "VP8 ";
const char* WebPImage::WEBP_CHUNK_HEADER_ANMF = "ANMF";
const char* WebPImage::WEBP_CHUNK_HEADER_ANIM = "ANIM";
const char* WebPImage::WEBP_CHUNK_HEADER_ICCP = "ICCP";
const char* WebPImage::WEBP_CHUNK_HEADER_EXIF = "EXIF";
const char* WebPImage::WEBP_CHUNK_HEADER_XMP = "XMP ";
/* =========================================== */
void WebPImage::setIptcData(const IptcData& /*iptcData*/)
{
// not supported
// just quietly ignore the request
// throw(Error(kerInvalidSettingForImage, "IPTC metadata", "WebP"));
}
void WebPImage::setComment(const std::string& /*comment*/)
{
// not supported
throw(Error(kerInvalidSettingForImage, "Image comment", "WebP"));
}
/* =========================================== */
void WebPImage::writeMetadata()
{
if (io_->open() != 0) {
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
BasicIo::AutoPtr tempIo(new MemIo);
assert (tempIo.get() != 0);
doWriteMetadata(*tempIo); // may throw
io_->close();
io_->transfer(*tempIo); // may throw
} // WebPImage::writeMetadata
void WebPImage::doWriteMetadata(BasicIo& outIo)
{
if (!io_->isopen()) throw Error(kerInputDataReadFailed);
if (!outIo.isopen()) throw Error(kerImageWriteFailed);
#ifdef DEBUG
std::cout << "Writing metadata" << std::endl;
#endif
byte data [WEBP_TAG_SIZE*3];
DataBuf chunkId(WEBP_TAG_SIZE+1);
chunkId.pData_ [WEBP_TAG_SIZE] = '\0';
io_->read(data, WEBP_TAG_SIZE * 3);
uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian);
/* Set up header */
if (outIo.write(data, WEBP_TAG_SIZE * 3) != WEBP_TAG_SIZE * 3)
throw Error(kerImageWriteFailed);
/* Parse Chunks */
bool has_size = false;
bool has_xmp = false;
bool has_exif = false;
bool has_vp8x = false;
bool has_alpha = false;
bool has_icc = iccProfileDefined();
int width = 0;
int height = 0;
byte size_buff[WEBP_TAG_SIZE];
Blob blob;
if (exifData_.count() > 0) {
ExifParser::encode(blob, littleEndian, exifData_);
if (blob.size() > 0) {
has_exif = true;
}
}
if (xmpData_.count() > 0 && !writeXmpFromPacket()) {
XmpParser::encode(xmpPacket_, xmpData_,
XmpParser::useCompactFormat |
XmpParser::omitAllFormatting);
}
has_xmp = xmpPacket_.size() > 0;
/* Verify for a VP8X Chunk First before writing in
case we have any exif or xmp data, also check
for any chunks with alpha frame/layer set */
while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {
io_->read(chunkId.pData_, WEBP_TAG_SIZE);
io_->read(size_buff, WEBP_TAG_SIZE);
long size = Exiv2::getULong(size_buff, littleEndian);
DataBuf payload(size);
io_->read(payload.pData_, payload.size_);
byte c;
if ( payload.size_ % 2 ) io_->read(&c,1);
/* Chunk with information about features
used in the file. */
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) {
has_vp8x = true;
}
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) {
has_size = true;
byte size_buf[WEBP_TAG_SIZE];
// Fetch width - stored in 24bits
memcpy(&size_buf, &payload.pData_[4], 3);
size_buf[3] = 0;
width = Exiv2::getULong(size_buf, littleEndian) + 1;
// Fetch height - stored in 24bits
memcpy(&size_buf, &payload.pData_[7], 3);
size_buf[3] = 0;
height = Exiv2::getULong(size_buf, littleEndian) + 1;
}
/* Chunk with with animation control data. */
#ifdef __CHECK_FOR_ALPHA__ // Maybe in the future
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANIM) && !has_alpha) {
has_alpha = true;
}
#endif
/* Chunk with with lossy image data. */
#ifdef __CHECK_FOR_ALPHA__ // Maybe in the future
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_alpha) {
has_alpha = true;
}
#endif
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) {
has_size = true;
byte size_buf[2];
/* Refer to this https://tools.ietf.org/html/rfc6386
for height and width reference for VP8 chunks */
// Fetch width - stored in 16bits
memcpy(&size_buf, &payload.pData_[6], 2);
width = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff;
// Fetch height - stored in 16bits
memcpy(&size_buf, &payload.pData_[8], 2);
height = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff;
}
/* Chunk with with lossless image data. */
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) {
if ((payload.pData_[5] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) {
has_alpha = true;
}
}
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) {
has_size = true;
byte size_buf_w[2];
byte size_buf_h[3];
/* For VP8L chunks width & height are stored in 28 bits
of a 32 bit field requires bitshifting to get actual
sizes. Width and height are split even into 14 bits
each. Refer to this https://goo.gl/bpgMJf */
// Fetch width - 14 bits wide
memcpy(&size_buf_w, &payload.pData_[1], 2);
size_buf_w[1] &= 0x3F;
width = Exiv2::getUShort(size_buf_w, littleEndian) + 1;
// Fetch height - 14 bits wide
memcpy(&size_buf_h, &payload.pData_[2], 3);
size_buf_h[0] =
((size_buf_h[0] >> 6) & 0x3) |
((size_buf_h[1] & 0x3F) << 0x2);
size_buf_h[1] =
((size_buf_h[1] >> 6) & 0x3) |
((size_buf_h[2] & 0xF) << 0x2);
height = Exiv2::getUShort(size_buf_h, littleEndian) + 1;
}
/* Chunk with animation frame. */
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) {
if ((payload.pData_[5] & 0x2) == 0x2) {
has_alpha = true;
}
}
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) {
has_size = true;
byte size_buf[WEBP_TAG_SIZE];
// Fetch width - stored in 24bits
memcpy(&size_buf, &payload.pData_[6], 3);
size_buf[3] = 0;
width = Exiv2::getULong(size_buf, littleEndian) + 1;
// Fetch height - stored in 24bits
memcpy(&size_buf, &payload.pData_[9], 3);
size_buf[3] = 0;
height = Exiv2::getULong(size_buf, littleEndian) + 1;
}
/* Chunk with alpha data. */
if (equalsWebPTag(chunkId, "ALPH") && !has_alpha) {
has_alpha = true;
}
}
/* Inject a VP8X chunk if one isn't available. */
if (!has_vp8x) {
inject_VP8X(outIo, has_xmp, has_exif, has_alpha,
has_icc, width, height);
}
io_->seek(12, BasicIo::beg);
while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {
io_->read(chunkId.pData_, 4);
io_->read(size_buff, 4);
long size = Exiv2::getULong(size_buff, littleEndian);
DataBuf payload(size);
io_->read(payload.pData_, size);
if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) {
if (has_icc){
payload.pData_[0] |= WEBP_VP8X_ICC_BIT;
} else {
payload.pData_[0] &= ~WEBP_VP8X_ICC_BIT;
}
if (has_xmp){
payload.pData_[0] |= WEBP_VP8X_XMP_BIT;
} else {
payload.pData_[0] &= ~WEBP_VP8X_XMP_BIT;
}
if (has_exif) {
payload.pData_[0] |= WEBP_VP8X_EXIF_BIT;
} else {
payload.pData_[0] &= ~WEBP_VP8X_EXIF_BIT;
}
if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)
throw Error(kerImageWriteFailed);
if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)
throw Error(kerImageWriteFailed);
if (outIo.write(payload.pData_, payload.size_) != payload.size_)
throw Error(kerImageWriteFailed);
if (outIo.tell() % 2) {
if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);
}
if (has_icc) {
if (outIo.write((const byte*)WEBP_CHUNK_HEADER_ICCP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
ul2Data(data, (uint32_t) iccProfile_.size_, littleEndian);
if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
if (outIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) {
throw Error(kerImageWriteFailed);
}
has_icc = false;
}
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) {
// Skip it altogether handle it prior to here :)
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) {
// Skip and add new data afterwards
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) {
// Skip and add new data afterwards
} else {
if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)
throw Error(kerImageWriteFailed);
if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)
throw Error(kerImageWriteFailed);
if (outIo.write(payload.pData_, payload.size_) != payload.size_)
throw Error(kerImageWriteFailed);
}
// Encoder required to pad odd sized data with a null byte
if (outIo.tell() % 2) {
if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);
}
}
if (has_exif) {
if (outIo.write((const byte*)WEBP_CHUNK_HEADER_EXIF, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
us2Data(data, (uint16_t) blob.size()+8, bigEndian);
ul2Data(data, (uint32_t) blob.size(), littleEndian);
if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
if (outIo.write((const byte*)&blob[0], static_cast<long>(blob.size())) != (long)blob.size())
{
throw Error(kerImageWriteFailed);
}
if (outIo.tell() % 2) {
if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);
}
}
if (has_xmp) {
if (outIo.write((const byte*)WEBP_CHUNK_HEADER_XMP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
ul2Data(data, (uint32_t) xmpPacket().size(), littleEndian);
if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
if (outIo.write((const byte*)xmpPacket().data(), static_cast<long>(xmpPacket().size())) != (long)xmpPacket().size()) {
throw Error(kerImageWriteFailed);
}
if (outIo.tell() % 2) {
if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);
}
}
// Fix File Size Payload Data
outIo.seek(0, BasicIo::beg);
filesize = outIo.size() - 8;
outIo.seek(4, BasicIo::beg);
ul2Data(data, (uint32_t) filesize, littleEndian);
if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed);
} // WebPImage::writeMetadata
/* =========================================== */
void WebPImage::printStructure(std::ostream& out, PrintStructureOption option,int depth)
{
if (io_->open() != 0) {
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
// Ensure this is the correct image type
if (!isWebPType(*io_, true)) {
if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
throw Error(kerNotAnImage, "WEBP");
}
bool bPrint = option==kpsBasic || option==kpsRecursive;
if ( bPrint || option == kpsXMP || option == kpsIccProfile || option == kpsIptcErase ) {
byte data [WEBP_TAG_SIZE * 2];
io_->read(data, WEBP_TAG_SIZE * 2);
uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian);
DataBuf chunkId(5) ;
chunkId.pData_[4] = '\0' ;
if ( bPrint ) {
out << Internal::indent(depth)
<< "STRUCTURE OF WEBP FILE: "
<< io().path()
<< std::endl;
out << Internal::indent(depth)
<< Internal::stringFormat(" Chunk | Length | Offset | Payload")
<< std::endl;
}
io_->seek(0,BasicIo::beg); // rewind
while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {
uint64_t offset = (uint64_t) io_->tell();
byte size_buff[WEBP_TAG_SIZE];
io_->read(chunkId.pData_, WEBP_TAG_SIZE);
io_->read(size_buff, WEBP_TAG_SIZE);
long size = Exiv2::getULong(size_buff, littleEndian);
DataBuf payload(offset?size:WEBP_TAG_SIZE); // header is different from chunks
io_->read(payload.pData_, payload.size_);
if ( bPrint ) {
out << Internal::indent(depth)
<< Internal::stringFormat(" %s | %8u | %8u | ", (const char*)chunkId.pData_,size,(uint32_t)offset)
<< Internal::binaryToString(payload,payload.size_>32?32:payload.size_)
<< std::endl;
}
if ( equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF) && option==kpsRecursive ) {
// create memio object with the payload, then print the structure
BasicIo::AutoPtr p = BasicIo::AutoPtr(new MemIo(payload.pData_,payload.size_));
printTiffStructure(*p,out,option,depth);
}
bool bPrintPayload = (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP) && option==kpsXMP)
|| (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP) && option==kpsIccProfile)
;
if ( bPrintPayload ) {
out.write((const char*) payload.pData_,payload.size_);
}
if ( offset && io_->tell() % 2 ) io_->seek(+1, BasicIo::cur); // skip padding byte on sub-chunks
}
}
}
/* =========================================== */
void WebPImage::readMetadata()
{
if (io_->open() != 0) throw Error(kerDataSourceOpenFailed, io_->path(), strError());
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (!isWebPType(*io_, true)) {
if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
throw Error(kerNotAJpeg);
}
clearMetadata();
byte data[12];
DataBuf chunkId(5);
chunkId.pData_[4] = '\0' ;
io_->read(data, WEBP_TAG_SIZE * 3);
const uint32_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian) + 8;
enforce(filesize <= io_->size(), Exiv2::kerCorruptedMetadata);
WebPImage::decodeChunks(filesize);
} // WebPImage::readMetadata
void WebPImage::decodeChunks(uint64_t filesize)
{
DataBuf chunkId(5);
byte size_buff[WEBP_TAG_SIZE];
bool has_canvas_data = false;
#ifdef DEBUG
std::cout << "Reading metadata" << std::endl;
#endif
chunkId.pData_[4] = '\0' ;
while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {
io_->read(chunkId.pData_, WEBP_TAG_SIZE);
io_->read(size_buff, WEBP_TAG_SIZE);
const uint32_t size = Exiv2::getULong(size_buff, littleEndian);
enforce(size <= (filesize - io_->tell()), Exiv2::kerCorruptedMetadata);
DataBuf payload(size);
if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_canvas_data) {
enforce(size >= 10, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
byte size_buf[WEBP_TAG_SIZE];
io_->read(payload.pData_, payload.size_);
// Fetch width
memcpy(&size_buf, &payload.pData_[4], 3);
size_buf[3] = 0;
pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1;
// Fetch height
memcpy(&size_buf, &payload.pData_[7], 3);
size_buf[3] = 0;
pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_canvas_data) {
enforce(size >= 10, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
io_->read(payload.pData_, payload.size_);
byte size_buf[WEBP_TAG_SIZE];
// Fetch width""
memcpy(&size_buf, &payload.pData_[6], 2);
size_buf[2] = 0;
size_buf[3] = 0;
pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff;
// Fetch height
memcpy(&size_buf, &payload.pData_[8], 2);
size_buf[2] = 0;
size_buf[3] = 0;
pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_canvas_data) {
enforce(size >= 5, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
byte size_buf_w[2];
byte size_buf_h[3];
io_->read(payload.pData_, payload.size_);
// Fetch width
memcpy(&size_buf_w, &payload.pData_[1], 2);
size_buf_w[1] &= 0x3F;
pixelWidth_ = Exiv2::getUShort(size_buf_w, littleEndian) + 1;
// Fetch height
memcpy(&size_buf_h, &payload.pData_[2], 3);
size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2);
size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2);
pixelHeight_ = Exiv2::getUShort(size_buf_h, littleEndian) + 1;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_canvas_data) {
enforce(size >= 12, Exiv2::kerCorruptedMetadata);
has_canvas_data = true;
byte size_buf[WEBP_TAG_SIZE];
io_->read(payload.pData_, payload.size_);
// Fetch width
memcpy(&size_buf, &payload.pData_[6], 3);
size_buf[3] = 0;
pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1;
// Fetch height
memcpy(&size_buf, &payload.pData_[9], 3);
size_buf[3] = 0;
pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1;
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) {
io_->read(payload.pData_, payload.size_);
this->setIccProfile(payload);
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) {
io_->read(payload.pData_, payload.size_);
byte size_buff[2];
// 4 meaningful bytes + 2 padding bytes
byte exifLongHeader[] = { 0xFF, 0x01, 0xFF, 0xE1, 0x00, 0x00 };
byte exifShortHeader[] = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 };
byte exifTiffLEHeader[] = { 0x49, 0x49, 0x2A }; // "MM*"
byte exifTiffBEHeader[] = { 0x4D, 0x4D, 0x00, 0x2A }; // "II\0*"
byte* rawExifData = NULL;
long offset = 0;
bool s_header = false;
bool le_header = false;
bool be_header = false;
long pos = -1;
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 4);
if (pos == -1) {
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 6);
if (pos != -1) {
s_header = true;
}
}
if (pos == -1) {
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffLEHeader, 3);
if (pos != -1) {
le_header = true;
}
}
if (pos == -1) {
pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffBEHeader, 4);
if (pos != -1) {
be_header = true;
}
}
if (s_header) {
offset += 6;
}
if (be_header || le_header) {
offset += 12;
}
const long size = payload.size_ + offset;
rawExifData = (byte*)malloc(size);
if (s_header) {
us2Data(size_buff, (uint16_t) (size - 6), bigEndian);
memcpy(rawExifData, (char*)&exifLongHeader, 4);
memcpy(rawExifData + 4, (char*)&size_buff, 2);
}
if (be_header || le_header) {
us2Data(size_buff, (uint16_t) (size - 6), bigEndian);
memcpy(rawExifData, (char*)&exifLongHeader, 4);
memcpy(rawExifData + 4, (char*)&size_buff, 2);
memcpy(rawExifData + 6, (char*)&exifShortHeader, 6);
}
memcpy(rawExifData + offset, payload.pData_, payload.size_);
#ifdef DEBUG
std::cout << "Display Hex Dump [size:" << (unsigned long)size << "]" << std::endl;
std::cout << Internal::binaryToHex(rawExifData, size);
#endif
if (pos != -1) {
XmpData xmpData;
ByteOrder bo = ExifParser::decode(exifData_,
payload.pData_ + pos,
payload.size_ - pos);
setByteOrder(bo);
}
else
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode Exif metadata." << std::endl;
#endif
exifData_.clear();
}
if (rawExifData) free(rawExifData);
} else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) {
io_->read(payload.pData_, payload.size_);
xmpPacket_.assign(reinterpret_cast<char*>(payload.pData_), payload.size_);
if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_)) {
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode XMP metadata." << std::endl;
#endif
} else {
#ifdef DEBUG
std::cout << "Display Hex Dump [size:" << (unsigned long)payload.size_ << "]" << std::endl;
std::cout << Internal::binaryToHex(payload.pData_, payload.size_);
#endif
}
} else {
io_->seek(size, BasicIo::cur);
}
if ( io_->tell() % 2 ) io_->seek(+1, BasicIo::cur);
}
}
/* =========================================== */
Image::AutoPtr newWebPInstance(BasicIo::AutoPtr io, bool /*create*/)
{
Image::AutoPtr image(new WebPImage(io));
if (!image->good()) {
image.reset();
}
return image;
}
bool isWebPType(BasicIo& iIo, bool /*advance*/)
{
const int32_t len = 4;
const unsigned char RiffImageId[4] = { 'R', 'I', 'F' ,'F'};
const unsigned char WebPImageId[4] = { 'W', 'E', 'B' ,'P'};
byte webp[len];
byte data[len];
byte riff[len];
iIo.read(riff, len);
iIo.read(data, len);
iIo.read(webp, len);
bool matched_riff = (memcmp(riff, RiffImageId, len) == 0);
bool matched_webp = (memcmp(webp, WebPImageId, len) == 0);
iIo.seek(-12, BasicIo::cur);
return matched_riff && matched_webp;
}
/*!
@brief Function used to check equality of a Tags with a
particular string (ignores case while comparing).
@param buf Data buffer that will contain Tag to compare
@param str char* Pointer to string
@return Returns true if the buffer value is equal to string.
*/
bool WebPImage::equalsWebPTag(Exiv2::DataBuf& buf, const char* str) {
for(int i = 0; i < 4; i++ )
if(toupper(buf.pData_[i]) != str[i])
return false;
return true;
}
/*!
@brief Function used to add missing EXIF & XMP flags
to the feature section.
@param iIo get BasicIo pointer to inject data
@param has_xmp Verify if we have xmp data and set required flag
@param has_exif Verify if we have exif data and set required flag
@return Returns void
*/
void WebPImage::inject_VP8X(BasicIo& iIo, bool has_xmp,
bool has_exif, bool has_alpha,
bool has_icc, int width, int height) {
byte size[4] = { 0x0A, 0x00, 0x00, 0x00 };
byte data[10] = { 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00 };
iIo.write((const byte*)WEBP_CHUNK_HEADER_VP8X, WEBP_TAG_SIZE);
iIo.write(size, WEBP_TAG_SIZE);
if (has_alpha) {
data[0] |= WEBP_VP8X_ALPHA_BIT;
}
if (has_icc) {
data[0] |= WEBP_VP8X_ICC_BIT;
}
if (has_xmp) {
data[0] |= WEBP_VP8X_XMP_BIT;
}
if (has_exif) {
data[0] |= WEBP_VP8X_EXIF_BIT;
}
/* set width - stored in 24bits*/
int w = width - 1;
data[4] = w & 0xFF;
data[5] = (w >> 8) & 0xFF;
data[6] = (w >> 16) & 0xFF;
/* set height - stored in 24bits */
int h = height - 1;
data[7] = h & 0xFF;
data[8] = (h >> 8) & 0xFF;
data[9] = (h >> 16) & 0xFF;
iIo.write(data, 10);
/* Handle inject an icc profile right after VP8X chunk */
if (has_icc) {
byte size_buff[WEBP_TAG_SIZE];
ul2Data(size_buff, iccProfile_.size_, littleEndian);
if (iIo.write((const byte*)WEBP_CHUNK_HEADER_VP8X, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)
throw Error(kerImageWriteFailed);
if (iIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE)
throw Error(kerImageWriteFailed);
if (iIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_)
throw Error(kerImageWriteFailed);
if (iIo.tell() % 2) {
if (iIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed);
}
has_icc = false;
}
}
long WebPImage::getHeaderOffset(byte *data, long data_size,
byte *header, long header_size) {
long pos = -1;
for (long i=0; i < data_size - header_size; i++) {
if (memcmp(header, &data[i], header_size) == 0) {
pos = i;
break;
}
}
return pos;
}
} // namespace Exiv2
|
6dd67f1d405d23b542fab2710c3be16c7f162044
|
1cc1f24482e668788e61193265ab35a025fb2c80
|
/DungeonCrawler/DungeonCrawler/Enemy.cpp
|
6107a33fbe0c8a534e1de329483928466b64dacb
|
[] |
no_license
|
leonvantuyl/ALG2_L-E
|
faea7ef248eb34747a41f80e991e5bce1f5ce2a3
|
55491bb2cc3f1ca243f255b802b426b73869de67
|
refs/heads/master
| 2021-01-20T20:18:23.418300
| 2016-06-06T11:39:52
| 2016-06-06T11:39:52
| 60,081,390
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 398
|
cpp
|
Enemy.cpp
|
#include "stdafx.h"
#include "Enemy.h"
#include <iostream>
#include "RandomGenerator.h"
using namespace std;
Enemy::Enemy(int lvl) : EnemyBase()
{
level = lvl;
RandomGenerator rg;
name = EnemyName[rg.getRandom(0,5)];
state = EnemyState[rg.getRandom(0, 5)];
health = rg.getRandom(10, 20) * (lvl +1);
alive = true;
attackpoints = rg.getRandom( 2, 6 ) * (lvl + 1);
}
Enemy::~Enemy()
{
}
|
fc2ee2bb621bbcffb26948dd1c8c4b7feba0e8a7
|
6f00050c211cf0ed234a3a5684b0dcb9440ecee6
|
/src/common/rgbCurve.cpp
|
d323b95a792d5af592b4ca5b2bc82e4d363bf71f
|
[] |
no_license
|
tuttleofx/ofxHDR
|
c68581b814366c58377f6c5c66cec3cf166968b0
|
c15a132f2e8acddb74413103e5fd18b5c52b33c2
|
refs/heads/master
| 2020-04-17T22:34:30.581117
| 2016-09-15T19:29:32
| 2016-09-15T19:29:32
| 67,035,772
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,572
|
cpp
|
rgbCurve.cpp
|
#include "rgbCurve.hpp"
#include <algorithm>
#include <functional>
#include <fstream>
#include <iostream>
#include <sstream>
namespace cameraColorCalibration {
namespace common {
rgbCurve::rgbCurve(std::size_t size)
{
for(auto &curve : _data)
{
curve.resize(size);
}
setZero();
}
rgbCurve::rgbCurve(const std::string &path)
{
read(path);
}
void rgbCurve::setLinear()
{
const float coefficient = 1.f / static_cast<float>(getSize() - 1);
for(std::size_t i = 0; i < getSize(); ++i)
{
setAllChannels(i, i * coefficient);
}
}
void rgbCurve::setGamma()
{
const float coefficient = 1.f / static_cast<float>(getSize() - 1);
for(std::size_t i = 0; i < getSize(); ++i)
{
setAllChannels(i, std::pow(4.0f * i * coefficient, 1.7f) + 1e-4);
}
}
void rgbCurve::setGaussian(double size)
{
const float coefficient = 1.f / (static_cast<float>(getSize() - 1) / 4.0f);
for(std::size_t i = 0; i < getSize(); ++i)
{
float factor = i / size * coefficient - 2.0f / size;
setAllChannels(i, std::exp( -factor * factor ));
}
}
void rgbCurve::setTriangular()
{
const float coefficient = 1.f / static_cast<float>(getSize() - 1);
for(std::size_t i = 0; i < getSize(); ++i)
{
float value = i * coefficient * 1.8f + 0.1f;
if (value >= 1.f)
{
value = 2.0f - value;
}
setAllChannels(i, value);
}
}
void rgbCurve::setPlateau()
{
const float coefficient = 1.f / static_cast<float>(getSize() - 1);
for(std::size_t i = 0; i < getSize(); ++i)
{
setAllChannels(i, 1.0f - std::pow((2.0f * i * coefficient - 1.0f), 12.0f));
}
}
void rgbCurve::setLog10()
{
const float coefficient = 1.f / static_cast<float>(getSize() - 1);
const float logInverseNorm = 1.0f / 0.0625f;
const float logInverseMaxValue = 1.0f / 1e8;
for(std::size_t i = 0; i < getSize(); ++i)
{
setAllChannels(i, logInverseMaxValue * std::pow(10.0f, (i * coefficient * logInverseNorm) - 8.f));
}
}
void rgbCurve::inverseAllValues()
{
for(auto &curve : _data)
{
for(auto &value : curve)
{
if(value != 0.f)
{
value = 1.f / value;
}
}
}
}
void rgbCurve::setAllAbsolute()
{
for(auto &curve : _data)
{
for(auto &value : curve)
{
value = std::abs(value);
}
}
}
void rgbCurve::normalize()
{
for(auto &curve : _data)
{
std::size_t first = 0;
std::size_t last = curve.size() - 1;
// find first and last value not null
for (; (first < curve.size()) && (curve[first] == 0) ; ++first);
for (; (last > 0) && (curve[last] == 0) ; --last);
std::size_t middle = first + ((last - first) / 2);
float midValue = curve[middle];
if (midValue == 0.0f)
{
// find first non-zero middle response
for (; (middle < last) && (curve[middle] == 0.0f) ; ++middle);
midValue = curve[middle];
}
std::cout << "-> middle [" << middle << "]: " << midValue <<std::endl;
const float coefficient = 1 / midValue;
for(auto &value : curve)
{
value *= coefficient;
}
}
}
void rgbCurve::interpolateMissingValues()
{
for(auto &curve : _data)
{
std::size_t previousValidIndex = 0;
for(std::size_t index = 1; index < curve.size(); ++index)
{
if(curve[index] != 0.0f)
{
if(previousValidIndex+1 < index)
{
const float inter = (curve[index] - curve[previousValidIndex]) / (index - previousValidIndex);
for(std::size_t j = previousValidIndex+1; j < index; ++j)
{
curve[j] = curve[previousValidIndex] + inter * (j-previousValidIndex);
}
}
previousValidIndex = index;
}
}
}
}
float& rgbCurve::operator() (float sample, std::size_t channel)
{
assert(channel < _data.size());
return _data[channel][getIndex(sample)];
}
float rgbCurve::operator() (float sample, std::size_t channel) const
{
assert(channel < _data.size());
return _data[channel][getIndex(sample)];
}
const rgbCurve rgbCurve::operator+(const rgbCurve &other) const
{
return sum(other);
}
const rgbCurve rgbCurve::operator-(const rgbCurve &other) const
{
return subtract(other);
}
void rgbCurve::operator*=(const rgbCurve &other)
{
multiply(other);
}
const rgbCurve rgbCurve::sum(const rgbCurve &other) const
{
assert(getSize() == other.getSize());
rgbCurve sum = rgbCurve(*this);
for(std::size_t channel = 0; channel < getNbChannels(); ++channel)
{
auto &sumCurve = sum.getCurve(channel);
const auto &otherCurve = other.getCurve(channel);
//sum member channel by the other channel
std::transform (sumCurve.begin(), sumCurve.end(), otherCurve.begin(), sumCurve.begin(), std::plus<float>());
}
return sum;
}
const rgbCurve rgbCurve::subtract(const rgbCurve &other) const
{
assert(getSize() == other.getSize());
rgbCurve sub = rgbCurve(*this);
for(std::size_t channel = 0; channel < getNbChannels(); ++channel)
{
auto &subCurve = sub.getCurve(channel);
const auto &otherCurve = other.getCurve(channel);
//subtract member channel by the other channel
std::transform (subCurve.begin(), subCurve.end(), otherCurve.begin(), subCurve.begin(), std::minus<float>());
}
return sub;
}
void rgbCurve::multiply(const rgbCurve &other)
{
assert(getSize() == other.getSize());
for(std::size_t channel = 0; channel < getNbChannels(); ++channel)
{
auto &curve = getCurve(channel);
const auto &otherCurve = other.getCurve(channel);
//multiply member channel by the other channel
std::transform (curve.begin(), curve.end(), otherCurve.begin(), curve.begin(), std::multiplies<float>());
}
}
void rgbCurve::write(const std::string &path, const std::string &name) const
{
std::ofstream file(path);
if(!file)
{
throw std::logic_error("Can't create curves file");
return;
}
std::string text(name + ",Red,Green,Blue,\n");
for(std::size_t index = 0; index < getSize(); ++index)
{
text += std::to_string(index) + ",";
for(std::size_t channel = 0; channel < getNbChannels(); ++channel)
{
text += std::to_string(_data[channel][index]) + ",";
}
text += "\n";
}
file << text;
file.close();
}
void rgbCurve::read(const std::string &path)
{
std::ifstream file(path);
std::vector <std::vector <std::string> > fileData;
if(!file)
{
throw std::logic_error("Can't open curves file");
return;
}
//create fileData
while (file)
{
std::string line;
if (!getline( file, line )) break;
std::istringstream sline( line );
std::vector<std::string> record;
while (sline)
{
std::string value;
if (!getline( sline, value, ',' )) break;
record.push_back( value );
}
fileData.push_back( record );
}
//clear rgbCurve
for(auto &curve : _data)
{
curve.clear();
}
//fill rgbCurve
try
{
for(std::size_t line = 1; line < fileData.size(); ++line)
{
_data[0].push_back(std::stof(fileData[line][1]));
_data[1].push_back(std::stof(fileData[line][2]));
_data[2].push_back(std::stof(fileData[line][3]));
}
}
catch(std::exception &e)
{
throw std::logic_error("Invalid Curve File");
}
file.close();
}
double rgbCurve::sumAll(const rgbCurve &curve)
{
double sum = 0.0f;
for(std::size_t channel = 0; channel < curve.getNbChannels(); ++channel)
{
auto const &sumCurve = curve.getCurve(channel);
for(auto value : sumCurve)
{
sum += value;
}
}
return sum;
}
} // namespace common
} // namespace cameraColorCalibration
|
ffe53e51b3b7665904042a77c1321f3a1c02198d
|
b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07
|
/Medusa/Medusa/Geometry/GeometryFactory.cpp
|
9aef6c0981314c4c6dd8e4ecb2e20060bf6b839c
|
[
"MIT"
] |
permissive
|
xueliuxing28/Medusa
|
c4be1ed32c2914ff58bf02593f41cf16e42cc293
|
15b0a59d7ecc5ba839d66461f62d10d6dbafef7b
|
refs/heads/master
| 2021-06-06T08:27:41.655517
| 2016-10-08T09:49:54
| 2016-10-08T09:49:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,031
|
cpp
|
GeometryFactory.cpp
|
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "Geometry/GeometryFactory.h"
#include "Geometry/Rect2.h"
#include "Core/String/StringParser.h"
#include "Geometry/Color4.h"
MEDUSA_BEGIN;
void GeometryFactory::CreateCircleBorder(Point3F center, float radius, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT(segmentsCount > 2, "");
MEDUSA_ASSERT(radius > 0.f, "");
const float eachRadian = (float)Math::PI2 / segmentsCount;
outPoints.ReserveSize(segmentsCount);
Point3F firstPoint(center.X + radius, center.Y);
outPoints.Append(firstPoint);
FOR_EACH_SIZE(i, segmentsCount - 1)
{
float angle = eachRadian*(i + 1);
Point3F temp;
temp.X = center.X + radius*Math::Cos(angle);
temp.Y = center.Y + radius*Math::Sin(angle);
outPoints.Append(temp);
}
//DrawPolygonBorder
}
void GeometryFactory::CreateCircle(Point3F center, float radius, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT(segmentsCount > 2, "");
MEDUSA_ASSERT(radius > 0.f, "");
const float eachRadian = Math::PI2 / segmentsCount;
outPoints.ReserveSize(segmentsCount + 2);
outPoints.Append(center);
Point3F firstPoint(center.X + radius, center.Y);
outPoints.Append(firstPoint);
FOR_EACH_SIZE(i, segmentsCount - 1)
{
float angle = eachRadian*(i + 1);
Point3F temp;
temp.X = center.X + radius*Math::Cos(angle);
temp.Y = center.Y + radius*Math::Sin(angle);
outPoints.Append(temp);
}
outPoints.Append(firstPoint);
//DrawPolygon
}
void GeometryFactory::CreateArc(Point3F center, float radius, float beginRadian, float endRadian, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT(segmentsCount > 1, "");
MEDUSA_ASSERT(radius > 0.f, "");
MEDUSA_ASSERT(endRadian > beginRadian, "");
MEDUSA_ASSERT(beginRadian <= Math::PI2, "");
MEDUSA_ASSERT(endRadian <= Math::PI2, "");
const float eachRadian = (float)(endRadian - beginRadian) / segmentsCount;
outPoints.ReserveSize(segmentsCount + 1);
FOR_EACH_SIZE(i, segmentsCount + 1)
{
float angle = beginRadian + eachRadian*(i);
Point3F temp;
temp.X = center.X + radius*Math::Cos(angle);
temp.Y = center.Y + radius*Math::Sin(angle);
outPoints.Append(temp);
}
//DrawLinesStrip
}
void GeometryFactory::CreateFanBorder(Point3F center, float radius, float beginRadian, float endRadian, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT(segmentsCount > 1, "");
MEDUSA_ASSERT(radius > 0.f, "");
MEDUSA_ASSERT(endRadian > beginRadian, "");
MEDUSA_ASSERT(beginRadian <= Math::PI2, "");
MEDUSA_ASSERT(endRadian <= Math::PI2, "");
const float eachRadian = (float)(endRadian - beginRadian) / segmentsCount;
outPoints.ReserveSize(segmentsCount + 2);
outPoints.Append(center);
FOR_EACH_SIZE(i, segmentsCount + 1)
{
float angle = beginRadian + eachRadian*(i);
Point3F temp;
temp.X = center.X + radius*Math::Cos(angle);
temp.Y = center.Y + radius*Math::Sin(angle);
outPoints.Append(temp);
}
//DrawLinesLoop
}
void GeometryFactory::CreateFan(Point3F center, float radius, float beginRadian, float endRadian, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT(segmentsCount > 1, "");
MEDUSA_ASSERT(radius > 0.f, "");
MEDUSA_ASSERT(endRadian > beginRadian, "");
MEDUSA_ASSERT(beginRadian <= Math::PI2, "");
MEDUSA_ASSERT(endRadian <= Math::PI2, "");
const float eachRadian = (float)(endRadian - beginRadian) / segmentsCount;
outPoints.ReserveSize(segmentsCount + 1);
outPoints.Append(center);
FOR_EACH_SIZE(i, segmentsCount + 1)
{
float angle = beginRadian + eachRadian*(i);
Point3F temp;
temp.X = center.X + radius*Math::Cos(angle);
temp.Y = center.Y + radius*Math::Sin(angle);
outPoints.Append(temp);
}
//DrawTrianglesFan
}
void GeometryFactory::CreateQuadBezier(Point3F origin, Point3F control, Point3F dest, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT_NOT_ZERO(segmentsCount, "");
outPoints.ReserveSize(segmentsCount + 1);
float t = 0.f;
float eachT = 1.f / segmentsCount;
FOR_EACH_SIZE(i, segmentsCount)
{
Point3F temp;
temp.X = powf(1 - t, 2) * origin.X + 2.0f * (1 - t) * t * control.X + t * t * dest.X;
temp.Y = powf(1 - t, 2) * origin.Y + 2.0f * (1 - t) * t * control.Y + t * t * dest.Y;
outPoints.Append(temp);
t += eachT;
}
outPoints.Append(dest);
//DrawLinesStrip
}
void GeometryFactory::CreateCubicBezier(Point3F origin, Point3F control1, Point3F control2, Point3F dest, size_t segmentsCount, List<Point3F>& outPoints)
{
outPoints.Clear();
MEDUSA_ASSERT_NOT_ZERO(segmentsCount, "");
outPoints.ReserveSize(segmentsCount + 1);
float t = 0.f;
float eachT = 1.f / segmentsCount;
FOR_EACH_SIZE(i, segmentsCount)
{
Point3F temp;
temp.X = powf(1 - t, 3) * origin.X + 3.0f * powf(1 - t, 2) * t * control1.X + 3.0f * (1 - t) * t * t * control2.X + t * t * t * dest.X;
temp.Y = powf(1 - t, 3) * origin.Y + 3.0f * powf(1 - t, 2) * t * control1.Y + 3.0f * (1 - t) * t * t * control2.Y + t * t * t * dest.Y;
outPoints.Append(temp);
t += eachT;
}
outPoints.Append(dest);
//DrawLinesStrip
}
Color4B GeometryFactory::CreateColor(StringRef str)
{
uint val = StringParser::StringTo<uint32>(str, 16);
return Color4B(val);
}
Color4F GeometryFactory::BlendColor(Color4F dest, Color4F src)
{
return Color4F(dest.R + (src.R - dest.R)*src.A,
dest.G + (src.G - dest.G)*src.A,
dest.B + (src.B - dest.B)*src.A,
dest.A * src.A
);
}
Color4B GeometryFactory::BlendColor(Color4B dest, Color4B src)
{
return BlendColor(dest.To4F(), src.To4F()).To4B();
}
void GeometryFactory::CreateRect(const Rect2F& rect, Array<Point2F, 4>& outPoints)
{
outPoints.Clear();
outPoints[0] = rect.LeftBottom();
outPoints[1] = rect.RightBottom();
outPoints[2] = rect.RightTop();
outPoints[3] = rect.LeftTop();
}
MEDUSA_END;
|
d749186be4dde8a499e541b03393c61554d1f244
|
792ad26fd812df30bf9a4cc286cca43b87986685
|
/数据结构/HDU 1754 I Hate It 线段树.cpp
|
efb2dcfb43f43dea831e31dd83d8fc7e9f21410d
|
[] |
no_license
|
Clqsin45/acmrec
|
39fbf6e02bb0c1414c05ad7c79bdfbc95dc26bf6
|
745b341f2e73d6b1dcf305ef466a3ed3df2e65cc
|
refs/heads/master
| 2020-06-18T23:44:21.083754
| 2016-11-28T05:10:44
| 2016-11-28T05:10:44
| 74,934,363
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,437
|
cpp
|
HDU 1754 I Hate It 线段树.cpp
|
#include <stdio.h>
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define MAX 200005
int f[MAX << 2];
int max(int x, int y)
{
return x > y ? x : y;
}
void pushup(int x)
{
f[x] = max(f[x << 1], f[x<<1|1]);
}
int require(int L, int R, int l, int r, int rt)
{
if(L <= l && R >= r)
{
return f[rt];
}
int ret = 0;
int m = (l + r) >> 1;
if(L <= m) ret = max(ret, require(L, R, lson));
if(R > m) ret = max(ret, require(L, R, rson));
return ret;
}
void modify(int p, int k, int l, int r, int rt)
{
if(l == r)
{
f[rt] = k;
return;
}
int m = (l + r) >> 1;
if(p <= m) modify(p, k, lson);
else modify(p, k, rson);
pushup(rt);
}
void build(int l, int r, int rt)
{
if(l == r)
{
scanf("%d\n", &f[rt]);
return;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
pushup(rt);
}
int main(void)
{
int N, M, i, st1, st2;
char op[10];
while(scanf("%d%d", &N, &M) != EOF)
{
build(1, N, 1);
for(i = 1; i<= M; i++)
{
scanf("%s%d%d", op, &st1, &st2);
if(op[0] == 'U')
{
modify(st1, st2, 1, N, 1);
}
else
{
printf("%d\n", require(st1, st2, 1, N, 1));
}
}
}
return 0;
}
|
a472144a9bf7d8d5e8f1c90f11b643daef84db6e
|
8f76cb5e386fa68f29489d479286d5ac7fac8c59
|
/src/server/plugins/htaccess/main.cpp
|
68d941f2539de2ef9327701e33aebbc690220501
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
isabella232/Heliod-Web-Server
|
ce672d264e705b0d2128ddd7846434804db24905
|
6fc8b2f0ed8e76979140fae7912b44cd03ca4289
|
refs/heads/master
| 2022-02-13T21:55:02.995051
| 2016-05-23T12:38:23
| 2016-05-23T12:38:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,965
|
cpp
|
main.cpp
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
*
* THE BSD LICENSE
*
* 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 nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "base/crit.h"
#include "base/pblock.h"
#include "base/util.h"
#include "frame/func.h"
#include "frame/protocol.h"
#include "frame/log.h"
#include "htaccess.h"
#include "libaccess/cryptwrapper.h"
/* Flag to indicate if AuthUserFile file contains groups for each user */
int _ht_gwu = 0;
/* Name of SAF to handle HTTP Basic authentication */
char *_ht_fn_basic = "basic-auth";
/* Name of SAF to handle user database lookup */
char *_ht_fn_user = 0;
/* Name of SAF to handle combined user/group database lookup */
char *_ht_fn_usrgrp = 0;
#ifdef __cplusplus
extern "C"
#endif
NSAPI_PUBLIC int
htaccess_userdb(pblock *pb, Session *sn, Request *rq)
{
char *userdb = pblock_findval("userdb", pb);
char *user = pblock_findval("user", pb);
char *pw = pblock_findval("pw", pb);
char *t;
char *cp;
SYS_FILE fd;
filebuffer *buf;
int ln;
int eof;
struct stat finfo;
char line[1024];
if (!userdb) {
log_error(LOG_MISCONFIG, "htaccess-userdb", sn, rq,
"missing \"userdb\" argument for SAF");
return REQ_ABORTED;
}
if (!user) {
log_error(LOG_MISCONFIG, "htaccess-userdb", sn, rq,
"missing \"user\" argument for SAF");
return REQ_ABORTED;
}
if (!pw) {
log_error(LOG_MISCONFIG, "htaccess-userdb", sn, rq,
"missing \"pw\" argument for SAF");
return REQ_ABORTED;
}
if ((system_stat(userdb, &finfo) < 0) || !S_ISREG(finfo.st_mode)) {
log_error(LOG_MISCONFIG, "htaccess-userdb", sn, rq,
"invalid user database file %s", userdb);
return REQ_ABORTED;
}
/* Open user file */
fd = system_fopenRO(userdb);
if (fd == SYS_ERROR_FD) {
log_error(LOG_FAILURE, "htaccess-userdb", sn, rq,
"can't open basic user/group file %s (%s)", userdb,
system_errmsg());
protocol_status(sn, rq, PROTOCOL_SERVER_ERROR, NULL);
return REQ_ABORTED;
}
buf = filebuf_open(fd, FILE_BUFFERSIZE);
if(!buf) {
log_error(LOG_FAILURE, "htaccess-userdb", sn, rq,
"can't open buffer from password file %s (%s)", userdb,
system_errmsg());
protocol_status(sn, rq, PROTOCOL_SERVER_ERROR, NULL);
system_fclose(fd);
return REQ_ABORTED;
}
/* Scan user file for desired user */
for (eof = 0, ln = 1; !eof; ++ln) {
eof = util_getline(buf, ln, sizeof(line), line);
if (line[0]) {
/* Look for ':' terminating user name */
t = strchr(line, ':');
if (t) {
/* Terminate user name */
*t++ = '\0';
/* Is this the desired user? */
if (!strcmp(line, user)) {
/* Look for colon at end of password */
cp = strchr(t, ':');
if (cp) {
/* Terminate password, advance to start of groups */
*cp++ = '\0';
}
if (ACL_CryptCompare(pw, t, t) != 0) {
log_error(LOG_SECURITY, "htaccess-userdb", sn, rq,
"user %s password did not match user database %s",
user, userdb);
break;
}
/* Got a match, so try for groups */
if (cp) {
/* Save start of groups */
t = cp;
/* Terminate groups at next ':' or end-of-line */
cp = strchr(t, ':');
if (cp) *cp = 0;
/* Set comma-separated list of groups */
pblock_nvinsert("auth-group", t, rq->vars);
}
else {
/* Set an empty group list */
pblock_nvinsert("auth-group", "", rq->vars);
}
filebuf_close(buf);
return REQ_PROCEED;
}
}
}
}
/* The desired user was not found, or the password didn't match */
filebuf_close(buf);
return REQ_NOACTION;
}
#ifdef __cplusplus
extern "C"
#endif
NSAPI_PUBLIC int
htaccess_init(pblock *pb, Session *unused2, Request *unused3)
{
char *gwu = pblock_findval("groups-with-users", pb);
char *fnbasic = pblock_findval("basic-auth-fn", pb);
char *fnuser = pblock_findval("user-auth-fn", pb);
_ht_gwu = (gwu && !strcasecmp(gwu, "yes"));
_ht_fn_basic = (fnbasic) ? fnbasic : (char *)"basic-auth";
_ht_fn_user = (fnuser) ? fnuser : 0;
if (!func_find("htaccess-userdb")) {
func_insert("htaccess-userdb", htaccess_userdb);
}
if (!func_find("htaccess-register")) {
func_insert("htaccess-register", htaccess_register);
}
return REQ_PROCEED;
}
#ifdef __cplusplus
extern "C"
#endif
NSAPI_PUBLIC int
htaccess_find(pblock *pb, Session *sn, Request *rq)
{
int rv;
rv = htaccess_evaluate(pb, sn, rq);
/*
* This must be done at the end, because AuthTrans functions
* we call may set it to 1.
*/
rq->directive_is_cacheable = 0;
return rv;
}
|
affa816b905ef1a9f742e72466e040adebad2864
|
0cc78c181eb031ee6c0182184ca29caae6d1c60c
|
/code/chapter1/1-5.cpp
|
6910d035e160f3b7748d3942687ee632fc2bc61e
|
[] |
no_license
|
Lunabot87/Study_Cpp
|
6e5d06bff7eebf811d94eb6fa2afad38ce01babf
|
909ede895a3e8a056489a0a995a0cefb0626f67b
|
refs/heads/master
| 2020-04-13T22:43:13.742656
| 2019-06-25T07:42:33
| 2019-06-25T07:42:33
| 163,486,825
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 529
|
cpp
|
1-5.cpp
|
#include <iostream>
using namespace std;
int multiplyTwoNumbers(int num_a, int num_b){
//int sum = num_a + num_b;
int sum = num_a * num_b;
return sum;
}
void printHelloWorld(){
cout << "Hello world!" << endl;
return;
cout << "Hello world!2" << endl;
}
int addTwoNumbers(int num_a, int num_b){
return num_a + num_b;
}
int main(){
cout << multiplyTwoNumbers(1,2) << endl;
cout << multiplyTwoNumbers(3,4) << endl;
cout << multiplyTwoNumbers(8,13) << endl;
printHelloWorld();
addTwoNumbers(1,2);
return 0;
}
|
bf97ffb63580ad92bfc5e51991445b96615b7a3f
|
8f469e3a353f1960276c21836f954d813bdec567
|
/twoPassAssembler/symtab.cpp
|
658a6a29ac5c361ddfd1cc4283f92a05388f371b
|
[] |
no_license
|
wndzlf/twopassAssembler
|
8a327a15b6e50c37e1f447c4a9c98d888c0696ef
|
7da3a3fbc0dd32b7242ec3940269ace734ff5946
|
refs/heads/master
| 2020-04-06T18:47:47.146054
| 2018-11-15T13:10:11
| 2018-11-15T13:10:11
| 157,713,243
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,058
|
cpp
|
symtab.cpp
|
//
// symtab.cpp
// twoPassAssembler
//
// Created by admin on 12/11/2018.
// Copyright © 2018 wndzlf. All rights reserved.
//
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
class symtab{
private:
fstream symboltab;
string label;
string path;
int num;
public:
symtab();
~symtab();
int search(string label);
void insert(string label, int locc);
};
symtab::symtab(){
symboltab.open("/Users/admin/Desktop/twoPassAssembler/twoPassAssembler/symtab.txt",ios::out);
this->num = 0;
};
symtab::~symtab() {
symboltab.close();
}
int symtab::search(string label){
string line;
while(!symboltab.eof()){
getline(symboltab, line);
string sym, val;
istringstream stream(line);
stream >> sym >> val;
//duplicate
if (label == sym) {
return -1;
}
}
return 1;
}
void symtab::insert(string label, int locc){
symboltab <<label<<" " << locc <<endl;
}
|
10d61b367aa3cf4de08563dbd9d0abf9f0239e3c
|
70238f403826253b36323e0c4700795788c61187
|
/thirdparty/iPlug2/WDL/mutex.h
|
a83c24f476f7e2d0b3deb9d0072ce1ef51dd30b8
|
[
"MIT",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
tommitytom/RetroPlug
|
d4d1c9d671cec7373bf3e27030bc0d29b46191be
|
40c6f01352d50cb31b1d4f31b7cc17fd2cf47ce8
|
refs/heads/main
| 2023-06-30T00:28:58.282288
| 2022-11-01T02:03:57
| 2022-11-01T02:03:57
| 185,368,230
| 262
| 11
|
MIT
| 2021-08-15T04:15:59
| 2019-05-07T09:23:48
|
C++
|
UTF-8
|
C++
| false
| false
| 5,759
|
h
|
mutex.h
|
/*
WDL - mutex.h
Copyright (C) 2005 and later, Cockos Incorporated
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/*
This file provides a simple class that abstracts a mutex or critical section object.
On Windows it uses CRITICAL_SECTION, on everything else it uses pthread's mutex library.
It simulates the Critical Section behavior on non-Windows, as well (meaning a thread can
safely Enter the mutex multiple times, provided it Leaves the same number of times)
*/
#ifndef _WDL_MUTEX_H_
#define _WDL_MUTEX_H_
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
// define this if you wish to use carbon critical sections on OS X
// #define WDL_MAC_USE_CARBON_CRITSEC
#ifdef WDL_MAC_USE_CARBON_CRITSEC
#include <Carbon/Carbon.h>
#else
#include <pthread.h>
#endif
#endif
#include "wdltypes.h"
#include "wdlatomic.h"
#ifdef _DEBUG
#include <assert.h>
#endif
class WDL_Mutex {
public:
WDL_Mutex()
{
#ifdef _WIN32
InitializeCriticalSection(&m_cs);
#elif defined( WDL_MAC_USE_CARBON_CRITSEC)
MPCreateCriticalRegion(&m_cr);
#elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) && !defined(__linux__)
const pthread_mutex_t tmp = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
m_mutex = tmp;
#else
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
#ifdef __linux__
// todo: macos too?
pthread_mutexattr_setprotocol(&attr,PTHREAD_PRIO_INHERIT);
#endif
pthread_mutex_init(&m_mutex,&attr);
pthread_mutexattr_destroy(&attr);
#endif
}
~WDL_Mutex()
{
#ifdef _WIN32
DeleteCriticalSection(&m_cs);
#elif defined(WDL_MAC_USE_CARBON_CRITSEC)
MPDeleteCriticalRegion(m_cr);
#else
pthread_mutex_destroy(&m_mutex);
#endif
}
void Enter()
{
#ifdef _WIN32
EnterCriticalSection(&m_cs);
#elif defined(WDL_MAC_USE_CARBON_CRITSEC)
MPEnterCriticalRegion(m_cr,kDurationForever);
#else
pthread_mutex_lock(&m_mutex);
#endif
}
void Leave()
{
#ifdef _WIN32
LeaveCriticalSection(&m_cs);
#elif defined(WDL_MAC_USE_CARBON_CRITSEC)
MPExitCriticalRegion(m_cr);
#else
pthread_mutex_unlock(&m_mutex);
#endif
}
private:
#ifdef _WIN32
CRITICAL_SECTION m_cs;
#elif defined(WDL_MAC_USE_CARBON_CRITSEC)
MPCriticalRegionID m_cr;
#else
pthread_mutex_t m_mutex;
#endif
// prevent callers from copying mutexes accidentally
WDL_Mutex(const WDL_Mutex &cp)
{
#ifdef _DEBUG
assert(sizeof(WDL_Mutex) == 0);
#endif
}
WDL_Mutex &operator=(const WDL_Mutex &cp)
{
#ifdef _DEBUG
assert(sizeof(WDL_Mutex) == 0);
#endif
return *this;
}
} WDL_FIXALIGN;
class WDL_MutexLock {
public:
WDL_MutexLock(WDL_Mutex *m) : m_m(m) { if (m) m->Enter(); }
~WDL_MutexLock() { if (m_m) m_m->Leave(); }
// the caller modifies this, make sure it unlocks the mutex first and locks the new mutex!
WDL_Mutex *m_m;
} WDL_FIXALIGN;
class WDL_SharedMutex
{
public:
WDL_SharedMutex() { m_sharedcnt=0; }
~WDL_SharedMutex() { }
void LockExclusive() // note: the calling thread must NOT have any shared locks, or deadlock WILL occur
{
m_mutex.Enter();
#ifdef _WIN32
while (m_sharedcnt>0) Sleep(1);
#else
while (m_sharedcnt>0) usleep(100);
#endif
}
void UnlockExclusive() { m_mutex.Leave(); }
void LockShared()
{
m_mutex.Enter();
wdl_atomic_incr(&m_sharedcnt);
m_mutex.Leave();
}
void UnlockShared()
{
wdl_atomic_decr(&m_sharedcnt);
}
void SharedToExclusive() // assumes a SINGLE shared lock by this thread!
{
m_mutex.Enter();
#ifdef _WIN32
while (m_sharedcnt>1) Sleep(1);
#else
while (m_sharedcnt>1) usleep(100);
#endif
UnlockShared();
}
void ExclusiveToShared() // assumes exclusive locked returns with shared locked
{
// already have exclusive lock
wdl_atomic_incr(&m_sharedcnt);
m_mutex.Leave();
}
private:
WDL_Mutex m_mutex;
volatile int m_sharedcnt;
// prevent callers from copying accidentally
WDL_SharedMutex(const WDL_SharedMutex &cp)
{
#ifdef _DEBUG
assert(sizeof(WDL_SharedMutex) == 0);
#endif
}
WDL_SharedMutex &operator=(const WDL_SharedMutex &cp)
{
#ifdef _DEBUG
assert(sizeof(WDL_SharedMutex) == 0);
#endif
return *this;
}
} WDL_FIXALIGN;
class WDL_MutexLockShared {
public:
WDL_MutexLockShared(WDL_SharedMutex *m) : m_m(m) { if (m) m->LockShared(); }
~WDL_MutexLockShared() { if (m_m) m_m->UnlockShared(); }
private:
WDL_SharedMutex *m_m;
} WDL_FIXALIGN;
class WDL_MutexLockExclusive {
public:
WDL_MutexLockExclusive(WDL_SharedMutex *m) : m_m(m) { if (m) m->LockExclusive(); }
~WDL_MutexLockExclusive() { if (m_m) m_m->UnlockExclusive(); }
private:
WDL_SharedMutex *m_m;
} WDL_FIXALIGN;
#endif
|
79916e455f57e3a314ad76601e4c097dff6e9692
|
bcf5350f45204576b1670b9276623c47f818c66e
|
/C/HarvardHacker3/Find/main.cpp
|
96e01694c440504d80d68ba2591310cf37b997a7
|
[] |
no_license
|
ezet/HIG
|
c7b445b2eed72c6af12005e0db5bec22abd94a01
|
7204355e84a413f2fcb4361522050ead2e677064
|
refs/heads/master
| 2021-01-22T08:30:00.935259
| 2017-05-27T20:28:33
| 2017-05-27T20:28:33
| 92,620,923
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,772
|
cpp
|
main.cpp
|
#include <iostream>
const int K = 50;
bool RecurSearch(int value, int arr[], int n) {
int mid = (n - 1) / 2;
if (n == 0) {
return false;
} else if (arr[mid] < value) {
return RecurSearch(value, arr+mid+1, n/2);
} else if (arr[mid] > value) {
return RecurSearch(value, arr, n/2);
} else {
return true;
}
}
bool Search(int value, int arr[], int n) {
int mid, begin = 0, end = n-1;
while (begin <= end) {
mid = begin + (end - begin) / 2;
if (arr[mid] < value) {
begin = mid + 1;
} else if (arr[mid] > value) {
end = mid - 1;
} else {
return true;
}
}
return false;
}
int* Sort(int arr[], int n) {
int *count = new int[K+1];
int *out = new int[n];
for (int i = 0; i <= K; ++i) {
count[i] = 0;
}
for (int i = 0; i < n ; ++i) {
count[arr[i]] += 1;
}
for (int i = 1; i <= K; ++i) {
count[i] += count[i-1];
}
for (int i = n-1; i >= 0; --i) {
out[count[arr[i]]-1] = arr[i];
count[arr[i]] -= 1;
}
delete[] count;
return out;
}
int main(int argc, char *argv[]) {
//int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//std::cout << RecurSearch(1, arr, 10);
//std::cout << RecurSearch(1, arr, 10) << '\n'
// << RecurSearch(2, arr, 10) << '\n'
// << RecurSearch(3, arr, 10) << '\n'
// << RecurSearch(4, arr, 10) << '\n'
// << RecurSearch(5, arr, 10) << '\n'
// << RecurSearch(6, arr, 10) << '\n'
// << RecurSearch(7, arr, 10) << '\n'
// << RecurSearch(8, arr, 10) << '\n'
// << RecurSearch(9, arr, 10) << '\n'
// << RecurSearch(10, arr, 10) << '\n';
int arr2[] = { 50, 0, 2, 5, 20, 10, 50, 40, 10, 20, 5, 1 };
int *arr3 = Sort(arr2, 12);
for (int i = 0; i < 12; ++i) {
std::cout << arr3[i] << '\n';
}
return 0;
}
|
17948443ac432fc06cc156a435178ed613817ce1
|
42a91b4556a6d7b9d533dab692a104ff0b0c978a
|
/PathSearch/Intermediate/Build/Win64/UE4Editor/Inc/PathSearch/AStar.generated.h
|
25676aa413de997c41a28db8b5efac2b160a6d28
|
[] |
no_license
|
juanpablohdzm/AI_Algorithms
|
12e315b5bd3122b99fa7fcb07b9d085362dd9562
|
2322cd92d7a53814fb5201f6ec06a46ecfaefcb5
|
refs/heads/master
| 2020-04-18T21:19:32.349797
| 2019-04-16T15:17:53
| 2019-04-16T15:17:53
| 167,762,358
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,676
|
h
|
AStar.generated.h
|
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef PATHSEARCH_AStar_generated_h
#error "AStar.generated.h already included, missing '#pragma once' in AStar.h"
#endif
#define PATHSEARCH_AStar_generated_h
#define PathSearch_Source_PathSearch_Public_AStar_h_15_RPC_WRAPPERS
#define PathSearch_Source_PathSearch_Public_AStar_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define PathSearch_Source_PathSearch_Public_AStar_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesAAStar(); \
friend struct Z_Construct_UClass_AAStar_Statics; \
public: \
DECLARE_CLASS(AAStar, AGraph, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/PathSearch"), NO_API) \
DECLARE_SERIALIZER(AAStar)
#define PathSearch_Source_PathSearch_Public_AStar_h_15_INCLASS \
private: \
static void StaticRegisterNativesAAStar(); \
friend struct Z_Construct_UClass_AAStar_Statics; \
public: \
DECLARE_CLASS(AAStar, AGraph, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/PathSearch"), NO_API) \
DECLARE_SERIALIZER(AAStar)
#define PathSearch_Source_PathSearch_Public_AStar_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API AAStar(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AAStar) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AAStar); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AAStar); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AAStar(AAStar&&); \
NO_API AAStar(const AAStar&); \
public:
#define PathSearch_Source_PathSearch_Public_AStar_h_15_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AAStar(AAStar&&); \
NO_API AAStar(const AAStar&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AAStar); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AAStar); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(AAStar)
#define PathSearch_Source_PathSearch_Public_AStar_h_15_PRIVATE_PROPERTY_OFFSET \
FORCEINLINE static uint32 __PPO__HeuristicPorcentage() { return STRUCT_OFFSET(AAStar, HeuristicPorcentage); }
#define PathSearch_Source_PathSearch_Public_AStar_h_12_PROLOG
#define PathSearch_Source_PathSearch_Public_AStar_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
PathSearch_Source_PathSearch_Public_AStar_h_15_PRIVATE_PROPERTY_OFFSET \
PathSearch_Source_PathSearch_Public_AStar_h_15_RPC_WRAPPERS \
PathSearch_Source_PathSearch_Public_AStar_h_15_INCLASS \
PathSearch_Source_PathSearch_Public_AStar_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define PathSearch_Source_PathSearch_Public_AStar_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
PathSearch_Source_PathSearch_Public_AStar_h_15_PRIVATE_PROPERTY_OFFSET \
PathSearch_Source_PathSearch_Public_AStar_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
PathSearch_Source_PathSearch_Public_AStar_h_15_INCLASS_NO_PURE_DECLS \
PathSearch_Source_PathSearch_Public_AStar_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> PATHSEARCH_API UClass* StaticClass<class AAStar>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID PathSearch_Source_PathSearch_Public_AStar_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
027ddd47d4fa4b933375fdd976d78f7982af6f21
|
15f30dda8e3a3773d317ac5ffc0419179323dd08
|
/test_linked_list.cpp
|
bb0efc25fdf0e05915e66599ed47d1efb17dff74
|
[] |
no_license
|
yiping/playground
|
c6e051a1cc951198f654951dbbdd87a801cc6711
|
07854bfd32f20f9fc47eb3b1fb5d650a96fda007
|
refs/heads/master
| 2020-05-31T00:12:48.090411
| 2018-01-20T22:01:39
| 2018-01-20T22:01:39
| 33,869,060
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,736
|
cpp
|
test_linked_list.cpp
|
#include <iostream>
using namespace std;
class Node
{
public:
int Data;
Node* Next;
};
class LinkedList
{
private:
Node* Head;
Node* Tail;
public:
LinkedList()
{
Head = NULL;
Tail = NULL;
}
void addNode(int value)
{
Node* nd = new Node;
nd->Next = NULL;
nd->Data = value;
if (Head == NULL)
{
Head = nd;
Tail = nd;
}
else
{
Tail->Next = nd;
Tail = nd;
}
}
void display()
{
Node* nd = Head;
while (nd != NULL)
{
cout << "->" << nd->Data;
nd = nd->Next;
}
cout << endl;
}
void reverse()
{
reverseInternal(Head);
//cout << Tail->Data <<endl;
Node* tmp = Head;
Head = Tail;
Tail = tmp;
}
void reverseInternal(Node* nd)
{
if (nd->Next->Next != NULL)
{
reverseInternal(nd->Next);
}
nd->Next->Next = nd;
nd->Next = NULL;
}
};
int main()
{
cout<<"Hello World"<<endl;
cout << "------"<<endl;
LinkedList lst;
for (int i = 0; i<10; i++)
{
lst.addNode(i);
}
lst.display();
lst.reverse();
lst.display();
lst.reverse();
lst.display();
return 0;
}
|
328c8ebfdd3b17a2e7d6767c9194575099e6d29c
|
32c7c726603e83306fb07868271f306685235f80
|
/rosbag2_performance/rosbag2_performance_benchmarking/include/rosbag2_performance_benchmarking/byte_producer.hpp
|
99ba2cf880c03a61ddd9f34f65398df00d52f921
|
[
"Apache-2.0"
] |
permissive
|
ros2/rosbag2
|
27dd1e412378079eee36046f536cbae422b13b17
|
98708682c0808137738fd7edb9e184d95d44a6e2
|
refs/heads/rolling
| 2023-08-17T19:07:03.100244
| 2023-08-09T20:55:52
| 2023-08-09T20:55:52
| 127,306,752
| 212
| 220
|
Apache-2.0
| 2023-09-14T17:51:22
| 2018-03-29T14:54:57
|
C++
|
UTF-8
|
C++
| false
| false
| 2,687
|
hpp
|
byte_producer.hpp
|
// Copyright 2020, Robotec.ai sp. z o.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROSBAG2_PERFORMANCE_BENCHMARKING__BYTE_PRODUCER_HPP_
#define ROSBAG2_PERFORMANCE_BENCHMARKING__BYTE_PRODUCER_HPP_
#include <chrono>
#include <memory>
#include <thread>
#include <functional>
#include "rclcpp/utilities.hpp"
#include "msg_utils/helpers.hpp"
#include "rosbag2_performance_benchmarking_msgs/msg/byte_array.hpp"
#include "rosbag2_performance_benchmarking/producer_config.hpp"
class ByteProducer
{
public:
using producer_initialize_function_t = std::function<void ()>;
using producer_callback_function_t = std::function<void (
std::shared_ptr<rosbag2_performance_benchmarking_msgs::msg::ByteArray>)>;
using producer_finalize_function_t = std::function<void ()>;
ByteProducer(
const ProducerConfig & config,
producer_initialize_function_t producer_initialize,
producer_callback_function_t producer_callback,
producer_finalize_function_t producer_finalize)
: configuration_(config),
producer_initialize_(producer_initialize),
producer_callback_(producer_callback),
producer_finalize_(producer_finalize),
sleep_time_(configuration_.frequency == 0 ? 1 : 1000 / configuration_.frequency),
message_(std::make_shared<rosbag2_performance_benchmarking_msgs::msg::ByteArray>())
{
msg_utils::helpers::generate_data(*message_, configuration_.message_size);
}
void run()
{
producer_initialize_();
for (auto i = 0u; i < configuration_.max_count; ++i) {
if (!rclcpp::ok()) {
break;
}
producer_callback_(message_);
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time_));
}
producer_finalize_();
}
private:
ProducerConfig configuration_;
producer_initialize_function_t producer_initialize_;
producer_callback_function_t producer_callback_;
producer_finalize_function_t producer_finalize_;
unsigned int sleep_time_; // in milliseconds
// for simplification, this pointer will be reused
std::shared_ptr<rosbag2_performance_benchmarking_msgs::msg::ByteArray> message_;
};
#endif // ROSBAG2_PERFORMANCE_BENCHMARKING__BYTE_PRODUCER_HPP_
|
a06be9ebf8ec9ea20ea4d794ab463c170ee6e145
|
f572dff0c0f45105c386074840e038097e0da0c1
|
/Algo_F1.cpp
|
e516ea6f9823dc8fbe640aee89275db66133b364
|
[] |
no_license
|
SehoonKwon/MultiCamp
|
1540d1ab0d8426f375f238209a8f145a7bbdcd2e
|
a0b77efa16c3c7c01cddd213e237e3e5f9f65d92
|
refs/heads/master
| 2022-12-11T22:22:49.844609
| 2020-09-08T11:47:19
| 2020-09-08T11:47:19
| 293,792,867
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 471
|
cpp
|
Algo_F1.cpp
|
//#include <iostream>
//using namespace std;
//
//int N;
//int cnt = 0;
//
//void solve()
//{
// while (N > 0)
// {
// if (N >= 500)
// {
// N -= 500;
// cnt++;
// }
// else if (N >= 100)
// {
// N -= 100;
// cnt++;
// }
// else if (N >= 50)
// {
// N -= 50;
// cnt++;
// }
// else
// {
// N -= 10;
// cnt++;
// }
// }
//
// cout << cnt;
//}
//
//int main()
//{
// cin >> N;
// solve();
// return 0;
//}
|
4de9d53f46b883bb8d8b0eb5771b2ef5669d67cf
|
51fd1616ffa6a0ab8231a165715fa43c22f5d967
|
/src/utils/dynlibs_unix.cpp
|
e7f745a700fc1d65add34105fd9061d3c062a1a8
|
[
"MIT"
] |
permissive
|
Samsung/netcoredbg
|
156e9a32cf7b648ee15746cfe740e8896fecbcc1
|
bac8ea845dc5484218b88ecf015abf81e6ef95d2
|
refs/heads/master
| 2023-08-31T08:59:35.933783
| 2023-07-07T09:56:30
| 2023-07-07T09:56:30
| 113,926,796
| 605
| 90
|
MIT
| 2023-08-30T08:24:43
| 2017-12-12T01:15:07
|
C#
|
UTF-8
|
C++
| false
| false
| 1,400
|
cpp
|
dynlibs_unix.cpp
|
// Copyright (C) 2020 Samsung Electronics Co., Ltd.
// See the LICENSE file in the project root for more information.
/// \file dynlibsi_unix.h This file contains unix-specific function definitions
/// required to work with dynamically loading libraries.
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#include <crt_externs.h>
#endif
#include <dlfcn.h>
#include "utils/limits.h"
#include "utils/dynlibs.h"
namespace netcoredbg
{
// This functon load specified library and returns handle (which then
// can be passed to DLSym and DLCLose functions).
// In case of error function returns NULL.
DLHandle DLOpen(const std::string &path)
{
return reinterpret_cast<DLHandle>(::dlopen(path.c_str(), RTLD_GLOBAL | RTLD_NOW));
}
// This function resolves symbol address within library specified by handle,
// and returns it's address, in case of error function returns NULL.
void* DLSym(DLHandle handle, string_view name)
{
char str[LINE_MAX];
if (name.size() >= sizeof(str))
return {};
name.copy(str, name.size());
str[name.size()] = 0;
return ::dlsym(handle, str);
}
/// This function unloads previously loadded library, specified by handle.
/// In case of error this function returns `false'.
bool DLClose(DLHandle handle)
{
return ::dlclose(handle);
}
} // ::netcoredbg
#endif // __unix__
|
d60e514f345aba420ce08ac0ea0b3c14c5886dc5
|
2af9ee33cf5d7e64a229ef439a534e527af3cb7c
|
/System/Builder/MOG/src/MOGBuilder.h
|
36aa82a5aec822f337aade7301056ccd30ab4f93
|
[] |
no_license
|
jorgesep/BGS
|
c117a77f25b045db1d5d7ad61bc4f19455d8920f
|
2082e72994e90d91d01928eaf649e1437dca8de0
|
refs/heads/master
| 2020-12-22T14:50:31.916976
| 2018-06-25T14:51:29
| 2018-06-25T14:51:29
| 10,537,627
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,381
|
h
|
MOGBuilder.h
|
/*******************************************************************************
* This file is part of libraries to evaluate performance of Background
* Subtraction algorithms.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#ifndef _MOG_ALGORITHM_H
#define _MOG_ALGORITHM_H
#include <opencv2/opencv.hpp>
#include <boost/filesystem.hpp>
#include "IBGSAlgorithm.h"
using namespace cv;
using namespace boost::filesystem;
class MOGBuilder : public IBGSAlgorithm
{
public:
//default constructor
MOGBuilder():
history(100),nmixtures(4),backgroundRatio(0.999),noiseSigma(0),alpha(2.0e-5) {};
~MOGBuilder();
// parametric constructor
MOGBuilder(int _hist, int _nmix, double _bgRatio, double _noise=0):
history(_hist),nmixtures(_nmix),backgroundRatio(_bgRatio),noiseSigma(_noise)
{ };
void SetAlgorithmParameters() {};
void LoadConfigParameters();
void SaveConfigParameters() {};
void Initialization();
void GetBackground(OutputArray);
void GetForeground(OutputArray);
void Update(InputArray, OutputArray);
void LoadModel() {};
void SaveModel() {};
string PrintParameters();
const string Name() {return string("MOG"); };
string ElapsedTimeAsString();
double ElapsedTime() {return duration; } ;
private:
int history;
int nmixtures;
double backgroundRatio;
double noiseSigma;
double alpha;
double duration;
static const int DefaultHistory;
static const int DefaultNMixtures;
static const double DefaultBackgroundRatio;
static const double DefaultNoiseSigma;
static const double DefaultAlpha;
BackgroundSubtractorMOG *model;
};
#endif
|
734ce4349c58aa507cb2ed8efe58d57c3d657b7c
|
50145f5197c9f6ac80b6674b7e390b105693ac29
|
/qtdebugging.h
|
b4c4d913ff3fdacbdcaad7d6a5ee2f74d83a8eb6
|
[] |
no_license
|
cmguo/QtDebugging
|
7bddf41cbaa3f5a32613cd4b989fe80382a3f36e
|
35ce0f164b0305137a47bffcde4b9a2b5ce6690e
|
refs/heads/main
| 2023-01-07T17:44:43.176607
| 2020-11-08T13:19:11
| 2020-11-08T13:19:11
| 311,067,415
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 172
|
h
|
qtdebugging.h
|
#ifndef QTDEBUGGING_H
#define QTDEBUGGING_H
#include "QtDebugging_global.h"
class QTDEBUGGING_EXPORT QtDebugging
{
public:
QtDebugging();
};
#endif // QTDEBUGGING_H
|
eb4c29ca81e5011e40d9da5565a3e890f30bb798
|
834abdb88e0626973a4df7bc082c164ae30b923a
|
/06_PrintListInReversedOrder/06_PrintListInReversedOrder/main_LittleRed.cpp
|
70df618e78aa3ffb58435d1b9a56adec394e441d
|
[] |
no_license
|
YaoEmily/InterviewCoding
|
ef2f93d92b864ef56359e83f96049e1d5dd7e569
|
8cca4d22b49d108e158653b6a2739ac57ce4e9eb
|
refs/heads/master
| 2021-04-06T11:51:37.220936
| 2018-06-15T00:31:22
| 2018-06-15T00:31:22
| 124,400,656
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 927
|
cpp
|
main_LittleRed.cpp
|
#include <iostream>
using namespace std;
struct ListNode{
int m_nValue;
ListNode* m_pNext;
};
void AddToTail(ListNode* pHead, int value){
ListNode* pNew = new ListNode();
pNew->m_nValue = value;
pNew->m_pNext = nullptr;
if (pHead->m_pNext == nullptr){
//pHead = pNew;
pHead->m_pNext = pNew;
}
else{
ListNode* pNode = pHead;
while (pNode->m_pNext != nullptr){
pNode = pNode->m_pNext;
}
pNode->m_pNext = pNew;
}
}
void PrintList(ListNode* pHead){
if (pHead == nullptr){
cout << "It's empty." << endl;
}
else{
ListNode* pNode = pHead;
cout << pNode->m_nValue << "--->";
while (pNode->m_pNext != nullptr){
pNode = pNode->m_pNext;
cout << pNode->m_nValue << "--->";
}
}
}
//int main(void){
// ListNode * pF = new ListNode();
// //ListNode** pHead = &pF;
// for (int i = 0; i < 10; i++){
// //AddToTail(pHead, i);
// AddToTail(pF, i);
// }
// PrintList(pF);
// system("pause");
//}
|
7c00f314b0f909683ef7008c2d2422e1ae95db02
|
b87030d81938d0a7060c0237e98af2319aad0917
|
/0.9/code/src/main.cpp
|
c11fbfd48d73cd811a025a87ed7d98c5eedf3554
|
[] |
no_license
|
Erk-Vural/Arduino-Car-Wash
|
969b44164202776e8464d4e2215dfc9d9cd1de99
|
6834726d21b942569a1b7ba286207a53c36e9e38
|
refs/heads/main
| 2023-08-04T21:09:28.771162
| 2021-09-10T11:13:36
| 2021-09-10T11:13:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,029
|
cpp
|
main.cpp
|
#include <Arduino.h>
#include <time.h>
#include <EEPROM.h>
int greenLed = 2;
int redLed = 3;
int fives = 0;
int tens = 0;
int twenties = 0;
int fifties = 0;
int hundreds = 0;
int registerAm = 0;
int amount = 0;
int five = 0, ten = 0, twenty = 0, fifty = 0, hundred = 0;
int customerAcc = 0;
int kopukle = 0, yika = 0, kurula = 0, cilala = 0;
//eeprom icin
int eeprom_Memory_address = 0;
int eeprom_size = 1024;
int fivesAddress = 10, tensAddress = 20, twentiesAddress = 30, fiftiesAddress = 40, hundredsAddress = 50;
int serviceBaslangicAddress = 60;
int step = 0;
struct service {
int serviceID;
char serviceName[10];
int serviceLeft;
int servicePrice;
int btn;
} service1, service2, service3, service4;
void initVal() {
fives = 20;
tens = 20;
twenties = 10;
fifties = 30;
hundreds = 5;
//eeprom icin
EEPROM.write(fivesAddress, fives);
EEPROM.write(tensAddress, tens);
EEPROM.write(twentiesAddress, twenties);
EEPROM.write(fiftiesAddress, fifties);
EEPROM.write(hundredsAddress, hundreds);
fives = EEPROM.read(fivesAddress);
tens = EEPROM.read(tensAddress);
twenties = EEPROM.read(twentiesAddress);
fifties = EEPROM.read(fiftiesAddress);
hundreds = EEPROM.read(hundredsAddress);
Serial.println("BANKNOT ADETLERİ");
Serial.print(fives);
Serial.print(",");
Serial.print(tens);
Serial.print(",");
Serial.print(twenties);
Serial.print(",");
Serial.print(fifties);
Serial.print(",");
Serial.println(hundreds);
registerAm = (hundreds * 100) + (fifties * 50) + (twenties * 20) + (tens * 10) + (fives * 5);
service1.serviceID = 1;
strcpy(service1.serviceName, "kopukleme");
service1.serviceLeft = 30;
service1.servicePrice = 15;
//eepromda servisleri yazma okuma
/*int tempAdress=serviceBaslangicAddress;
EEPROM.put(tempAdress, service1);*/
service2.serviceID = 2;
strcpy(service2.serviceName, "yikama");
service2.serviceLeft = 50;
service2.servicePrice = 10;
/*tempAdress += sizeof(service1);
EEPROM.put(tempAdress, service2);*/
service3.serviceID = 3;
strcpy(service3.serviceName, "kurulama");
service3.serviceLeft = 100;
service3.servicePrice = 5;
/*tempAdress += sizeof(service2);
EEPROM.put(tempAdress, service3);*/
service4.serviceID = 4;
strcpy(service4.serviceName, "cilalama");
service4.serviceLeft = 20;
service4.servicePrice = 50;
/*tempAdress += sizeof(service3);
EEPROM.put(tempAdress, service4);*/
/*tempAdress=serviceBaslangicAddress;
EEPROM.get(serviceBaslangicAddress, service1);
tempAdress += sizeof(service1);
EEPROM.get(tempAdress, service2);
tempAdress += sizeof(service2);
EEPROM.get(tempAdress, service3);
tempAdress += sizeof(service3);
EEPROM.get(tempAdress, service4);*/
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
// Leds
pinMode(greenLed, OUTPUT);
pinMode(redLed, OUTPUT);
initVal();
}
void reset(int btContiune, int btReset) {
if (btContiune == HIGH) {
step += 1;
delay(500);
Serial.println("Devam pressed");
} else if (btReset == HIGH) {
service1.serviceLeft += kopukle;
service2.serviceLeft += yika;
service3.serviceLeft += kurula;
service4.serviceLeft += cilala;
five = 0, ten = 0, twenty = 0, fifty = 0, hundred = 0;
customerAcc = 0;
kopukle = 0, yika = 0, kurula = 0, cilala = 0;
amount = 0;
step = 0;
delay(500);
Serial.println("Reset pressed");
}
}
void addCashMenu() {
Serial.println("/////////////////////////////////////////////////");
Serial.println("Enter amount of money for your account.");
Serial.println("1. Buton : 5 TL Sayisi");
Serial.println("2. Buton : 10 TL Sayisi");
Serial.println("3. Buton : 20 TL Sayisi");
Serial.println("4. Buton : 50 TL Sayisi");
Serial.println("5. Buton : 100 TL Sayisi");
Serial.println("6. Buton : Bitis");
Serial.println("/////////////////////////////////////////////////");
}
void addCash(int btFive, int btTen, int btTwenty, int btFifty, int btHundred, int btFinish) {
if (btFive == HIGH) {
five += 1;
delay(500);
Serial.println("Button 1 pressed");
} else if (btTen == HIGH) {
ten += 1;
delay(500);
Serial.println("Button 2 pressed");
} else if (btTwenty == HIGH) {
twenty += 1;
delay(500);
Serial.println("Button 3 pressed");
} else if (btFifty == HIGH) {
fifty += 1;
delay(500);
Serial.println("Button 4 pressed");
} else if (btHundred == HIGH) {
hundred += 1;
delay(500);
Serial.println("Button 5 pressed");
} else if (btFinish == HIGH) {
Serial.println("Button 6 pressed");
delay(500);
customerAcc = 0;
customerAcc += five * 5 + ten * 10 + twenty * 20 + fifty * 50 + hundred * 100;
String Str = "Total cash in customer account : ";
String StrD = Str + customerAcc ;
Serial.println("");
Serial.println("/////////////////////////////////////////////////");
Serial.println(StrD);
step += 1;
}
}
void selectServiceMenu() {
Serial.println("/////////////////////////////////////////////////");
Serial.println("Select Services: ");
// Serial.println("Kopukleme");
Serial.print(service1.serviceID);
Serial.print(",");
Serial.print(service1.serviceName);
Serial.print(",");
Serial.print(service1.servicePrice);
Serial.print(",");
Serial.print("Kalan Hizmet:");
Serial.println(+service1.serviceLeft);
// Serial.println("Yikama");
Serial.print(service2.serviceID);
Serial.print(",");
Serial.print(service2.serviceName);
Serial.print(",");
Serial.print(service2.servicePrice);
Serial.print(",");
Serial.print("Kalan Hizmet:");
Serial.println(+service2.serviceLeft);
// Serial.println("Kurulama");
Serial.print(service3.serviceID);
Serial.print(",");
Serial.print(service3.serviceName);
Serial.print(",");
Serial.print(service3.servicePrice);
Serial.print(",");
Serial.print("Kalan Hizmet:");
Serial.println(+service3.serviceLeft);
//Serial.println("Cilalama");
Serial.print(service4.serviceID);
Serial.print(",");
Serial.print(service4.serviceName);
Serial.print(",");
Serial.print(service4.servicePrice);
Serial.print(",");
Serial.print("Kalan Hizmet:");
Serial.println(+service4.serviceLeft);
Serial.println("Bitis");
Serial.println("/////////////////////////////////////////////////");
}
void applyService() {
// service1
if (strcmp("kopukleme", service1.serviceName)) {
if (service1.serviceLeft > 0) {
service1.serviceLeft -= 1 * kopukle;
} else {
kopukle -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("yikama", service1.serviceName)) {
if (service1.serviceLeft > 0) {
service1.serviceLeft -= 1 * yika;
} else {
yika -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("kurulama", service1.serviceName)) {
if (service1.serviceLeft > 0) {
service1.serviceLeft -= 1 * kurula;
} else {
kurula -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("cilalama", service1.serviceName)) {
if (service1.serviceLeft > 0) {
service1.serviceLeft -= 1 * cilala;
} else {
cilala -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
}
// service2
if (strcmp("kopukleme", service2.serviceName)) {
if (service2.serviceLeft > 0) {
service2.serviceLeft -= 1 * kopukle;
} else {
kopukle -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("yikama", service2.serviceName)) {
if (service2.serviceLeft > 0) {
service2.serviceLeft -= 1 * yika;
} else {
yika -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("kurulama", service2.serviceName)) {
if (service2.serviceLeft > 0) {
service2.serviceLeft -= 1 * kurula;
} else {
kurula -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("cilalama", service2.serviceName)) {
if (service2.serviceLeft > 0) {
service2.serviceLeft -= 1 * cilala;
} else {
cilala -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
}
// service3
if (strcmp("kopukleme", service3.serviceName)) {
if (service3.serviceLeft > 0) {
service3.serviceLeft -= 1 * kopukle;
} else {
kopukle -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("yikama", service3.serviceName)) {
if (service3.serviceLeft > 0) {
service3.serviceLeft -= 1 * yika;
} else {
yika -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("kurulama", service3.serviceName)) {
if (service3.serviceLeft > 0) {
service3.serviceLeft -= 1 * kurula;
} else {
kurula -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("cilalama", service3.serviceName)) {
if (service3.serviceLeft > 0) {
service3.serviceLeft -= 1 * cilala;
} else {
cilala -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
}
// service4
if (strcmp("kopukleme", service4.serviceName)) {
if (service4.serviceLeft > 0) {
service4.serviceLeft -= 1 * kopukle;
} else {
kopukle -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("yikama", service4.serviceName)) {
if (service4.serviceLeft > 0) {
service4.serviceLeft -= 1 * yika;
} else {
yika -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("kurulama", service4.serviceName)) {
if (service4.serviceLeft > 0) {
service4.serviceLeft -= 1 * kurula;
} else {
kurula -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
} else if (strcmp("cilalama", service4.serviceName)) {
if (service4.serviceLeft > 0) {
service4.serviceLeft -= 1 * cilala;
} else {
cilala -= 1;
Serial.println("Yeterli hizmet kalmadi!");
}
}
}
void selectService(int btKopukle, int btYika, int btKurula, int btCilala, int btFinish) {
if (btKopukle == HIGH) {
kopukle += 1;
delay(500);
Serial.println("Kopukle pressed");
} else if (btYika == HIGH) {
yika += 1;
delay(500);
Serial.println("Yika pressed");
} else if (btKurula == HIGH) {
kurula += 1;
delay(500);
Serial.println("Kurula pressed");
} else if (btCilala == HIGH) {
cilala += 1;
delay(500);
Serial.println("Cilala pressed");
} else if (btFinish == HIGH) {
Serial.println("Bitis pressed");
delay(500);
amount = 0;
amount = kopukle * 15 + yika * 10 + kurula * 5 + cilala * 50;
if (amount <= customerAcc) {
applyService();
String Str = "Total price of selected services : ";
String StrD = Str + amount;
Serial.println("");
Serial.println("/////////////////////////////////////////////////");
Serial.println(StrD);
step += 1;
} else {
String Str = "Customer account is insufficient resetting steps: ";
Serial.println("");
Serial.println("/////////////////////////////////////////////////");
Serial.println(Str);
reset(LOW, HIGH);
}
}
}
void resetMenu() {
Serial.println("/////////////////////////////////////////////////");
Serial.println("Yanlis secim yaptiysaniz Resetleyebilirsiniz(Tum secimler iptal edilir!).");
Serial.println("6. Buton: Devam");
Serial.println("7. Buton: Reset");
Serial.println("/////////////////////////////////////////////////");
}
void isStuct() {
int isStuck = (rand() % 4) + 1;
if (isStuck == 2) {
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, LOW);
Serial.println("Money Stuct\n");
Serial.println("Returning Money...\n");
reset(LOW, HIGH);
}
else {
digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
Serial.println("Money Processed\n");
Serial.println("Calculating Change...\n");
reset(HIGH, LOW);
}
}
void UpdateEepromCacheAmount() {
EEPROM.write(fivesAddress, fives);
EEPROM.write(tensAddress, tens);
EEPROM.write(twentiesAddress, twenties);
EEPROM.write(fiftiesAddress, fifties);
EEPROM.write(hundredsAddress, hundreds);
Serial.println("Kalan Banknot Adetleri(5,10,20,50,100 degerinde banknotlar)");
int fives2 = EEPROM.read(fivesAddress);
int tens2 = EEPROM.read(tensAddress);
int twenties2 = EEPROM.read(twentiesAddress);
int fifties2 = EEPROM.read(fiftiesAddress);
int hundreds2 = EEPROM.read(hundredsAddress);
Serial.print(fives2);
Serial.print(",");
Serial.print(tens2);
Serial.print(",");
Serial.print(twenties2);
Serial.print(",");
Serial.print(fifties2);
Serial.print(",");
Serial.println(hundreds2);
}
void giveChange() {
int change = customerAcc - amount;
if (registerAm < change) {
Serial.println("insufficient amount in register Resetting steps.");
reset(LOW, HIGH);
} else {
int f = 0, t = 0, tw = 0, ft = 0, h = 0;
h = change / 100;
change -= h * 100;
ft = change / 50;
change -= ft * 50;
tw = change / 20;
change -= tw * 20;
t = change / 10;
change -= t * 10;
f = change / 5;
change -= f * 5;
String Strf = "Fives : ";
String StrF = Strf + f;
String Strt = "Tens : ";
String StrT = Strt + t;
String Strtw = "Twenties : ";
String StrTw = Strtw + tw;
String Strft = "Fifties : ";
String StrFt = Strft + ft;
String Strh = "Hundreds : ";
String StrH = Strh + h;
//eeprom icin
fives -= f;
tens -= t;
twenties -= tw;
fifties -= ft;
hundreds -= h;
registerAm -= amount;
UpdateEepromCacheAmount();
Serial.println("");
Serial.println("/////////////////////////////////////////////////");
Serial.print("Total change : ");
Serial.println(customerAcc - amount);
Serial.println(StrF);
Serial.println(StrT);
Serial.println(StrTw);
Serial.println(StrFt);
Serial.println(StrH);
step += 1;
//step = 0;
}
}
void serviceLeft() {
Serial.println("/////////////////////////////////////////////////");
Serial.println("");
Serial.print("Kalan ");
Serial.print(service1.serviceName);
Serial.print(": ");
Serial.println(service1.serviceLeft);
Serial.print("Kalan ");
Serial.print(service2.serviceName);
Serial.print(": ");
Serial.println(service2.serviceLeft);
Serial.print("Kalan ");
Serial.print(service3.serviceName);
Serial.print(": ");
Serial.println(service3.serviceLeft);
Serial.print("Kalan ");
Serial.print(service4.serviceName);
Serial.print(": ");
Serial.println(service4.serviceLeft);
Serial.println("");
}
void contiuneService() {
five = 0, ten = 0, twenty = 0, fifty = 0, hundred = 0;
kopukle = 0, yika = 0, kurula = 0, cilala = 0;
customerAcc = 0;
amount = 0;
step = 0;
delay(500);
}
void loop() {
// put your main code here, to run repeatedly:
// Reset Finish Buttons
int btReset = digitalRead(4);
int btFinish = digitalRead(5);
if (step == 0) {
//Serial.println(step);
Serial.println("/////////////////////////////////////////////////");
Serial.println("Welcome To Car Wash!");
addCashMenu();
step += 1;
} else if (step == 1) {
//Serial.println(step);
// addCash Buttons
int btFive = digitalRead(13);
int btTen = digitalRead(12);
int btTwenty = digitalRead(11);
int btFifty = digitalRead(10);
int btHundred = digitalRead(9);
addCash(btFive, btTen, btTwenty, btFifty, btHundred, btFinish);
if (btFinish == HIGH) {
selectServiceMenu();
}
} else if (step == 2) {
//Serial.println(step);
// selectService Buttons
int btKopukle = digitalRead(13);
int btYika = digitalRead(12);
int btKurula = digitalRead(11);
int btCilala = digitalRead(10);
amount = 0;
selectService(btKopukle, btYika, btKurula, btCilala, btFinish);
if (btFinish == HIGH) {
resetMenu();
}
} else if (step == 3) {
//Serial.println(step);
reset(btFinish, btReset);
} else if (step == 4) {
//Serial.println(step);
isStuct();
} else if (step == 5) {
//Serial.println(step);
giveChange();
serviceLeft();
} else if( step == 6){
//Serial.println(step);
contiuneService();
}
}
|
86ba6d310808a6fa3b330ee092dc79fdb6a92f93
|
783c6fa86d4c35f49ddeec7f326eb48c76e014bb
|
/Account.cpp
|
0994f1dfd0c9c42f7a87fe0ed2d1eeb831b62d7f
|
[] |
no_license
|
MoezGholami/hjamg_utosca3
|
7572f408c7a35ebcd404f1e830b9d22327976be9
|
6199ebf2984cc43684d7638c336303a0ee23cf14
|
refs/heads/master
| 2020-04-17T09:23:58.209916
| 2014-05-03T15:19:36
| 2014-05-03T15:19:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,853
|
cpp
|
Account.cpp
|
#include "Account.h"
#include "Nosy.h"
#include "Benefector.h"
#include <sstream>
#include <string>
Account::Account(const string &name, const string &phoneNumber, int id, pthread_t rt, pthread_mutex_t rm)
{
Name=name;
PhoneNumber=phoneNumber;
ID=id;
pthread_mutex_init(&runningMutex, 0);
pthread_mutex_init(&bensQmtx, 0);
pthread_mutex_init(&watchQmtx, 0);
pthread_mutex_init(&valMtx, 0);
pthread_cond_init(&wakeupCond,0);
cancelling=false;
canBeCancelled=true;
destructorCalled=false;
finished=false;
Lock(runningMutex);
qcounter=0;
val=0;
runningOn=rt;
runningMutex=rm;
out.open(string(name+".txt").c_str(), ios::out);
out<<"log of Qs for "<<name<<"'s account:\n";
stringstream ss;
ss<<"Acount: "<<Name<<" with ID: "<<ID<<" has been created.\n";
cout<<ss.str();
}
Account::~Account(void)
{
cancel();
}
void Account::cancel(void)
{
if(finished)
return ;
destructorCalled=true;
if(!canBeCancelled)
usleep(10000);
cancelling=true;
pthread_cond_broadcast(&wakeupCond);
while(!finished)
usleep(10000);
UnLock(runningMutex);
pthread_cond_destroy(&wakeupCond);
pthread_mutex_destroy(&watchQmtx);
pthread_mutex_destroy(&bensQmtx);
pthread_mutex_destroy(&valMtx);
pthread_mutex_destroy(&runningMutex);
stringstream ss;
ss<<"Acount: "<<Name<<" with ID: "<<ID<<" is exiting.\n";
cout<<ss.str();
}
void Account::printQs(void)
{
out<<"\n\n\nBenefector Q:\t";
for(unsigned i=0; i<bens.size(); ++i)
out<<bens[i]->getName()<<", ";
out<<"\nWatchers Q:\t";
for(unsigned i=0; i<watchers.size(); ++i)
out<<watchers[i]->getName()<<", ";
out<<endl;
}
int Account::getID(void)
{
return ID;
}
string Account::getName()
{
return Name;
}
bool Account::isCancelling(void)
{
return cancelling;
}
int Account::IncAndReturn(int plus)
{
Lock(valMtx);
val+=plus;
int v=val;
stringstream ss;
if (plus == 0)
ss<<"The value of "<<Name<<" has not been changed and it is: "<<v<<endl;
else
ss<<"The value of "<<Name<<" has been changed and it is: "<<v<<endl;
cout<<ss.str();
UnLock(valMtx);
return v;
}
void Account::wait4Charity(Benefector* christ)
{
if(destructorCalled)
return ;
canBeCancelled=false;
Lock(bensQmtx);
bens.push_back(christ);
pthread_cond_broadcast(&wakeupCond);
UnLock(bensQmtx);
}
void Account::wait4Watching(Nosy* n)
{
if(destructorCalled)
return ;
canBeCancelled=false;
Lock(watchQmtx);
watchers.push_back(n);
pthread_cond_broadcast(&wakeupCond);
UnLock(watchQmtx);
}
void Account::wakeMeUp(void)
{
pthread_cond_broadcast(&wakeupCond);
}
bool Account::isWaitingForWatching(Nosy *n)
{
Lock(watchQmtx);
bool result=(watchers.end()!=find(watchers.begin(), watchers.end(), n));
UnLock(watchQmtx);
return result;
}
void Account::SetThreadFinished(void)
{
finished=true;
}
void Account::oneAct(void)
{
Lock(watchQmtx);
Lock(bensQmtx);
printQs();
qcounter=(qcounter+1)%6;
if((qcounter>0 && watchers.size()>0)|| (watchers.size()>0 && bens.size()==0) ) //access for a nosy
{
Nosy *n=watchers.front();
n->nosyWatch(this);
out<<"Picking "<<n->getName()<<"\n";
watchers.pop_front();
}
else //access for a benefector
{
if(watchers.size()==0) //if there is no watcher and you have to serve a benefector, then start again looking for watchers
qcounter=0;
if(bens.size()>0)
{
Benefector *b=bens.front();
b->help(this);
out<<"Picking "<<b->getName()<<"\n";
bens.pop_front();
}
}
if(bens.size()==0 && watchers.size()==0)
{
UnLock(watchQmtx);
UnLock(bensQmtx);
canBeCancelled=destructorCalled;
while(pthread_cond_wait(&wakeupCond,&runningMutex)); //Block
}
else
{
UnLock(watchQmtx);
UnLock(bensQmtx);
}
}
void *RunAnAccount(void* acptr)
{
Account *inUse=(Account *)acptr;
while(!inUse->isCancelling())
{
Account *inUse=(Account *)acptr;
inUse->oneAct();
}
inUse->SetThreadFinished();
return 0;
}
|
da7e46491beecfbdd34bd10f4edd5d85f0371289
|
7eb24c0930960c0d907da0dcaaafd6557d494a65
|
/include/ExplorationIGDVPN2optB.h
|
bd74c4629968f664df6296c66b493f6b8aa3ca93
|
[] |
no_license
|
wadatti/QAPSolver
|
b169a117dda5715c47bfd30d2e36665d22db9a3a
|
69f857e92a85b8e3bd17452309d81aebf62b82f7
|
refs/heads/master
| 2021-01-13T20:15:30.570651
| 2020-03-04T11:08:10
| 2020-03-04T11:08:10
| 242,479,487
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 838
|
h
|
ExplorationIGDVPN2optB.h
|
/*******************************************************************************
* ExplorationIGDVPN2optB
*
* ランダム選択・完全再生型(k-opt局所探索)
*******************************************************************************/
#ifndef EXPLORATIONIGDVPN2OPTB_H
#define EXPLORATIONIGDVPN2OPTB_H
#include "ExplorationBase.h"
class ExplorationIGDVPN2optB : public ExplorationBase
{
public:
/* コンストラクタ */
ExplorationIGDVPN2optB(QAP *qapInst, ExpCond *cond, std::string fileName);
/* デストラクタ */
~ExplorationIGDVPN2optB();
/* 探索の実行 */
void Explore();
private:
/* 初期化 */
void Init();
/* 解の再構成処理 */
void Destruction(double ratio);
/* 2optBサーチ */
void LocalSearch();
};
#endif /* EXPLORATIONIGDVPN2OPTB_H */
|
02b5e1313fc2289ddb9aaa243d938d2f847ec57a
|
c475e087a0471e1a983e4cb55b50a021f359b42b
|
/cellular_potts_adhesive_hamiltonian.cpp
|
94d3b38389478af382a1e3b698ddbddc0ac9958e
|
[] |
no_license
|
kmatsu3/Cellular_Potts
|
a64df38950cc037f34c95151ebc0eb17177888b4
|
e7c6ea55c23e090b1859b3f6224267bfae79e551
|
refs/heads/master
| 2021-06-24T12:29:39.980384
| 2021-01-08T03:32:13
| 2021-01-08T03:32:13
| 194,646,509
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,249
|
cpp
|
cellular_potts_adhesive_hamiltonian.cpp
|
#include "cellular_potts_hamiltonian.hpp"
#include "cellular_potts_state.hpp"
//
double local_state_class::get_local_adhesion_energy(
const adhesion_system_class & adhesion_system
)
{
double return_value=0.0;
double work_density=0.0;
double work_density_neighbor=0.0;
double work_polarity_value=1.0;
double polar_product_neighbor=0.0;
int pair_index;
int neighbor_index;
std::string debug_message;
if(
(cell_type!=buffer_type)
&&
(iszero_norm_in_adhesive_hamiltonian(relative_coordinates)==false_value)
)
{
for(neighbor_index=0;neighbor_index<number_of_neighbor_sites;neighbor_index++)
{
pair_index
=cell_type
*adhesion_system.number_of_cell_types
+neighbor_types[neighbor_index];
work_vector_double_for_neighbors[neighbor_index]=0.0;
if(
(
(
neighbor_types[neighbor_index]
==
buffer_type
)
||
(
cell
==
neighbor_cells[neighbor_index]
)
||
(iszero_norm_in_adhesive_hamiltonian(neighbor_relative_coordinates[neighbor_index])
==
true_value
)
)
)
{
}
else if(adhesion_system.typepair_to_adhesion_flags[pair_index])
{
for(
int map_index
= adhesion_system.typepair_to_adhesion_pointers[pair_index];
map_index
< adhesion_system.typepair_to_adhesion_pointers[pair_index+1];
map_index++
)
{
work_polarity_value=1.0;
work_density=0.0;
for(
int component_index=0;
component_index<adhesion_system.number_of_adhesion_components;
component_index++
)
{
work_density
+= work_polarity_value
*adhesion_system.polar_components_1[
map_index*adhesion_system.number_of_adhesion_components
+component_index
];
work_polarity_value
=work_polarity_value
*product_polarity;
};
polar_product_neighbor
=normalized_product_in_adhesive_hamiltonian(
neighbor_polarities[neighbor_index],
neighbor_relative_coordinates[neighbor_index]
);
work_polarity_value=1.0;
work_density_neighbor=0.0;
for(
int component_index=0;
component_index<adhesion_system.number_of_adhesion_components;
component_index++
)
{
work_density_neighbor
+=work_polarity_value
*adhesion_system.polar_components_2[
map_index
*adhesion_system.number_of_adhesion_components
+component_index
];
work_polarity_value
=work_polarity_value
*polar_product_neighbor;
};
// should be debugging
// debug_message = adhesion_system.get_adhesion_type(map_index)
// + ":";
if(
adhesion_system.get_adhesion_type(map_index)
==
adhesion_system.get_adhesion_type_identifier("normal")
)
{
work_vector_double_for_neighbors[neighbor_index]
+=adhesion_system.coupling_constants[map_index]
*work_density*work_density_neighbor;
//debug
// debug_message += "debug list A: strength ="
// + io_method.double_to_string(adhesion_system.coupling_constants[map_index])
// + "map no." + io_method.longint_to_string(map_index)
// + "cell no." + io_method.longint_to_string(cell)
// + "neig no." + io_method.longint_to_string(neighbor_cells[neighbor_index]);
//io_method.standard_output(debug_message);
//debug
}
else if(
adhesion_system.get_adhesion_type(map_index)
==
adhesion_system.get_adhesion_type_identifier("tight")
)
{
work_vector_double_for_neighbors[neighbor_index]
+=adhesion_system.get_adhesion_tight_junction_constant(
map_index,
cell,
neighbor_cells[neighbor_index]
)
*work_density*work_density_neighbor;
//debug
// debug_message += "debug list B: strength ="
// + io_method.double_to_string(
// adhesion_system.get_adhesion_tight_junction_constant(
// map_index,
// cell,
// neighbor_cells[neighbor_index]
// )
// )
// + "map no." + io_method.longint_to_string(map_index)
// + "cell no." + io_method.longint_to_string(cell)
// + "neig no." + io_method.longint_to_string(neighbor_cells[neighbor_index]);
// io_method.standard_output(debug_message);
//debug
};
//
};
};
// ;
};
return_value
=accumulate(
work_vector_double_for_neighbors.begin(),
work_vector_double_for_neighbors.end(),
0.0
);
};
// debug
/*
std::string messages;
messages = "debug:";
messages+= "cell_type =" + io_method.int_to_string(cell_type) + '_';
io_method.standard_output(messages);
for( int neighbor_index=0;neighbor_index<number_of_neighbor_sites;neighbor_index++)
{
messages = "energy["+ io_method.int_to_string(neighbor_index)+ ","
+ io_method.int_to_string(neighbor_types[neighbor_index]) + "]"
+ "=" + io_method.double_to_string(work_vector_double_for_neighbors[neighbor_index]);
io_method.standard_output(messages);
};
//
*/
return return_value;
};
//
inline int local_state_class::iszero_norm_in_adhesive_hamiltonian(
const std::vector<double> & vector_data
)
const {
int return_value=false_value;
double norm = std::inner_product(vector_data.begin(),vector_data.end(),vector_data.begin(),0.0);
if(norm<0.00000000001)
{
return_value=true_value;
};
return return_value;
};
//
inline double local_state_class::normalized_product_in_adhesive_hamiltonian(
const std::vector<double> & vector_1,
const std::vector<double> & vector_2
)
{
//
double norm_1 =std::inner_product(vector_1.begin(),vector_1.end(),vector_1.begin(),0.0);
double norm_2 =std::inner_product(vector_2.begin(),vector_2.end(),vector_2.begin(),0.0);
double product_12 =std::inner_product(vector_1.begin(),vector_1.end(),vector_2.begin(),0.0);
return product_12/pow(norm_1*norm_2,0.5);
//
};
//
|
9b0e669b2b094d8834c5857733179ff468be2971
|
d2fc7fb55ce6acc1f274efc51789dc1dc06c3eb2
|
/idea/Jojo/src/gohelper.cpp
|
062e3ec27e9de50cd9da787751d35cb270f9e6db
|
[] |
no_license
|
Strongc/isu
|
31dc6b7049e009bc753d000307936141787942d1
|
d40f16c3841552b00329b16a61f5c9893ea6c4eb
|
refs/heads/master
| 2021-01-15T18:14:32.458687
| 2014-11-03T14:22:02
| 2014-11-03T14:22:02
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,963
|
cpp
|
gohelper.cpp
|
#include <go/gohelper.h>
#include <go/runtime_mgr.h>
#include <go/runtime_tool.h>
#include <go/runtime_mgr.h>
#include <boost/thread/tss.hpp>
#include <go/detail/tools/mgrgeter.h>
//File:gohelper.cpp
// (C) Copyright 2013 四元飒
// Use, modification and distribution is subject to the Isu source code
// License, Version 0.1. (See local file LICENSE_0_1.txt)
// See http://blog.csdn.net/fq_hayate for updates, documentation, and revision history.
//Q&A:a313865974@sina.com
namespace isu
{
namespace go
{
namespace detail
{
extern boost::thread_specific_ptr<
shared_ptr<detail::machine> >
afxcurrent_machine;
extern boost::thread_specific_ptr<
shared_ptr<detail::processor> >
afxcurrent_processor;
}
namespace
{
typedef detail::typeconfig::processor_ptr processor_ptr;
template<class Func>
void _each_procmgr(Func f)
{
for (processor_ptr& p
: *detail::global_processor_manager().get())
{
f(p);
}
}
}
detail::shared_ptr<detail::machine> curm_ptr()
{
auto ptr=detail::afxcurrent_machine.get();
return ptr ? *ptr : detail::shared_ptr<detail::machine>();
}
detail::shared_ptr<detail::machine> current_machine()
{
return curm_ptr();
}
detail::shared_ptr<detail::processor> current_processor()//注意不是系统的processor
{
return curm_ptr()->curproc();
}
detail::shared_ptr<detail::goroutine> current_goroutine()
{
auto ptr = curm_ptr();
return ptr ? ptr->curg(): detail::shared_ptr<detail::goroutine>();
}
//暂时没有办法实现全局wait..
void wait_exit()
{
_each_procmgr([](const processor_ptr& p)
{
p->wait_exit();
});
}
void stop_world()
{
}
void resume_world()
{
}
const bool at_goroutine()
{
return current_goroutine().get() != nullptr;
}
const std::size_t max_processors()
{
return detail::global_processor_manager()->maxproc();
}
const std::size_t processor_count()
{
return detail::global_processor_manager()->proc_size();
}
void max_processors(const std::size_t size)
{
detail::global_processor_manager()->maxproc(size);
}
const std::size_t syscall_machine()
{
return detail::global_machine_manager()->syscall();
}
const std::size_t runing_machine()
{
return detail::global_machine_manager()->runing();
}
const std::size_t idled_machine()
{
return detail::global_machine_manager()->idleing();
}
const std::size_t runableg()
{
return detail::global_goroutine_manager()->runableg_size();
}
const std::size_t freeg()
{
return detail::global_goroutine_manager()->freeg_size();
}
const std::size_t gid()
{
return current_goroutine()->id();
}
const std::size_t mid()
{
return current_machine()->id();
}
void yield()
{
auto g = current_goroutine();
g->yield();
}
}
}
|
04dcc08116ed7a1d2a022433c3cc3e7f9fc37423
|
0b69a011c9ffee099841c140be95ed93c704fb07
|
/problemsets/UVA/UVA344.cpp
|
b460aaaa981c1e4ca68d40c79277771d3a473f01
|
[
"Apache-2.0"
] |
permissive
|
juarezpaulino/coderemite
|
4bd03f4f2780eb6013f07c396ba16aa7dbbceea8
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
refs/heads/main
| 2023-01-31T11:35:19.779668
| 2020-12-18T01:33:46
| 2020-12-18T01:33:46
| 320,931,351
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,440
|
cpp
|
UVA344.cpp
|
/**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <map>
using namespace std;
string fill(char c, int n) {
string s; while(n--) s += c; return s;
}
string toRoman(int n) {
if(n < 4) return fill('i', n);
if(n < 6) return fill('i', 5-n) + "v";
if(n < 9) return string("v") + fill('i', n-5);
if(n < 11) return fill('i', 10-n) + "x";
if(n < 40) return fill('x', n/10) + toRoman(n%10);
if(n < 60) return fill('x', 5-n/10) + 'l' + toRoman(n%10);
if(n < 90) return string("l") + fill('x', n/10-5) + toRoman(n%10);
if(n < 110) return fill('x', 10-n/10) + "c" + toRoman(n%10);
if(n < 400) return fill('c', n/100) + toRoman(n%100);
if(n < 600) return fill('c', 5-n/100) + 'D' + toRoman(n%100);
if(n < 900) return string("D") + fill('c', n/100-5) + toRoman(n%100);
if(n < 1100) return fill('c', 10-n/100) + "M" + toRoman(n%100);
if(n < 4000) return fill('M', n/1000) + toRoman(n%1000);
return "?";
}
int main() {
int N;
while (scanf("%d", &N)) {
if (!N) break;
map<char, int> M;
for (int k = 1; k <= N; k++) {
string S = toRoman(k);
for (int i = 0; i < S.size(); i++) M[S[i]]++;
}
printf("%d: %d i, %d v, %d x, %d l, %d c\n", N, M['i'], M['v'], M['x'], M['l'], M['c']);
}
return 0;
}
|
892743971f4734f586cbc0f43e90644c2385182d
|
76d188c8bac65167ae7880a0975afa6bc0906f54
|
/include/afml/util/common.hpp
|
a9d71233c2b451c98c3b20fe2bbf1630b3f6baa4
|
[] |
no_license
|
pavanky/arrayfire-ml
|
4b8dedfd68bfb8fc700386d0dd25f330f27e0446
|
815a6679dae5df23223214e8e07b3eb6e6e08cf7
|
refs/heads/master
| 2020-04-05T13:39:39.531586
| 2015-08-19T21:43:16
| 2015-08-19T21:43:16
| 39,900,572
| 0
| 0
| null | 2015-07-29T15:18:05
| 2015-07-29T15:18:05
|
C++
|
UTF-8
|
C++
| false
| false
| 530
|
hpp
|
common.hpp
|
/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <arrayfire.h>
#include <vector>
namespace afml
{
const int MAX_NAME_SIZE = 32;
typedef std::vector<int> IntVector;
typedef std::vector<af::array> ArrayVector;
}
|
879501e48aa8d72147e313b53c39195f7881b824
|
45e3db0198fec82c24c6b95a58c3553c5fe67f9c
|
/leetcode/problem141_160/min_stack_155/minStack_slow.cpp
|
93afed476bc5ebbf6b1bff53294762602b9f39cb
|
[] |
no_license
|
yezhang4528/cpp_exercise
|
6f4506cb0d7d7b79f111b321a1b5467fc1124f92
|
5d59a1fcaf47e979eacfb521c3874c229231ab1f
|
refs/heads/master
| 2020-04-07T01:45:25.748926
| 2020-04-03T22:04:00
| 2020-04-03T22:04:00
| 157,951,025
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,771
|
cpp
|
minStack_slow.cpp
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<exception>
using namespace std;
struct StackNode
{
int val;
StackNode *next;
StackNode(int x) : val(x), next(NULL) {}
};
class MinStack {
private:
StackNode *topNode;
vector<int> sortedList;
void removeFromSortedList(int val) {
vector<int>::iterator it;
for (it = sortedList.begin(); it != sortedList.end(); ++it) {
if (*it == val)
break;
}
sortedList.erase(it, it + 1);
}
public:
/** initialize your data structure here. */
MinStack(): topNode(NULL) {
sortedList = {};
}
void push(int x) {
StackNode *newNode = new StackNode(x);
newNode->next = topNode;
topNode = newNode;
sortedList.push_back(x);
sort(sortedList.begin(), sortedList.end());
}
void pop() {
if (!topNode)
return;
StackNode *toDeleteNode = topNode;
removeFromSortedList(toDeleteNode->val);
topNode = topNode->next;
delete toDeleteNode;
}
int top() {
if (topNode)
return topNode->val;
else
throw ("Stack is empty");
}
int getMin() {
if (topNode)
return sortedList[0];
else
throw ("Stack is empty");
}
};
int main()
{
MinStack minStack;
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
int minVal = minStack.getMin();
cout << "Mimimum value on stack is " << minVal << endl;
minStack.pop();
int topVal = minStack.top();
cout << "Top value on stack is " << topVal << endl;
minVal = minStack.getMin();
cout << "Mimimum value on stack is " << minVal << endl;
return 0;
}
|
9480e8867cdc5c889fbd5f5fc01aa8d4913dc78d
|
5880a8168b8001a1f39f8be102d1aad6e3e76d53
|
/03Mesh/src/view/imgui.h
|
27de532f4998f5c01db76abb5eb720c39de34b5d
|
[] |
no_license
|
xinguo2015/GlutTutorial
|
7e09ff30e5a7156b71b6f6e7a6d8196e9bf1e36d
|
f570b49baf75b14acf00ce7c1533ec51ca8862d0
|
refs/heads/master
| 2021-01-22T23:10:42.887190
| 2018-09-03T14:29:15
| 2018-09-03T14:29:15
| 92,803,565
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,736
|
h
|
imgui.h
|
#ifndef ________i_m_g_u_i_____h_____________________
#define ________i_m_g_u_i_____h_____________________
#include <stdlib.h>
#include <stdio.h>
//===========================================================================
//
// Generate a *fake* unique ID for gui controls at compiling/run time
//
// [L:16-1][N:16-1]
// XOR
// [F:32 --------1]
//
#define GenUIID(N) ( ((__LINE__<<16) | ( N & 0xFFFF))^((long)&__FILE__) )
//
// GenUIID(0) will give a unique ID at each source code line.
// If you need one UI ID per line, just call GenUIID with 0
//
// GenUIID(0)
//
// But, two GenUIID(0) calls at the same line will give the same ID.
// So, in a while/for loop body, GenUIID(0) will give you the same ID.
// In this case, you need call GenUIID with different N parameter:
//
// GenUIID(N)
//
//===========================================================================
namespace xglm {
class GuiFont
{
public:
GuiFont(void *f) { setFont(f); }
int setFont(void *f);
public:
void * mGlutFont;
int mFontHeight;
};
class ImGUIState
{
public:
ImGUIState();
public:
int mousex; // x - mouse position
int mousey; // y - mouse position
int buttondown; // 1 - down, 0 - otherwise
int clickxy[2]; // click down mouse position
int wheel; // 1 and -1 for up/down wheel direction
int hotitem; // widget below the mouse cursor
int activeitem; // widget under interaction
int key; // key pressed
int keychar; // char input
int modifier; // modifier key
int lastkeys[3];// last key, keychar, modifier
int kboarditem; // widget with keyboard focus
int lastkbitem; // last widget that was processed
};
class ImGUI
{
public:
ImGUI() { initialize(); mFlags = 1; }
const ImGUIState & getGUIState() const { return mGuiState; }
ImGUIState & getGUIState() { return mGuiState; }
int flags() { return mFlags; }
public:
void setfont(void* font);
void initialize();
void prepare();
void finish();
// glut keyboard and mouse
void onKeyboardUp(unsigned char key, int modifier, int x, int y);
void onKeyboard(unsigned char key, int modifier, int x, int y);
void onSpecialUp(unsigned char key, int modifier, int x, int y);
void onSpecial(unsigned char key, int modifier, int x, int y);
void onMouse(int button, int state, int x, int y);
void onMotion(int x, int y);
int hitRect(int x, int y, int w, int h);
// widgets
int button (int id, int x, int y, int w, int h, char label[]);
int checkbox (int id, int x, int y, int w, int h, char label[], int *value);
int radio (int id, int x, int y, int w, int h, char label[], int reference, int *value);
int listbox (int id, int x, int y, int w, int h, char*items[], int nitem, int *liststart, int *value);
int slider (int id, int x, int y, int w, int h, double minv, double maxv, double delta, double * value);
int slider (int id, int x, int y, int w, int h, float minv, float maxv, float delta, float * value);
int slider (int id, int x, int y, int w, int h, int minv, int maxv, int delta, int * value);
int editbox (int id, int x, int y, int w, int h, char textbuf[], int maxbuf);
int textlabel(int id, int x, int y, int w, int h, char text[]);
void groupbox(int x, int y, int w, int h);
protected:
int listitem(int id, int x, int y, int w, int h, char label[], int selected);
int slider_base(int id, int x, int y, int w, int h, double minv, double maxv, double delta, double * value);
protected:
ImGUIState mGuiState;
int mFlags;
};
} //namespace xglm {
#endif // ifndef ________i_m_g_u_i_____h_____________________
|
64102e62d962ba230bae25d0ca9288c9a0d1c303
|
0bb5a59aa280e77df2770d8c6c85aa1f69ecbdc2
|
/CastleWar/CastleWar/Posicao.cpp
|
ec34558fd69c0c21340c400e75790b3eb3ba3b6b
|
[
"Apache-2.0"
] |
permissive
|
dyaremyshyn/POO_Colonia
|
6b1ab2942c61b47e67485507337924a594c9073c
|
dab332f4acbdff95c7bba9d0339563f45f35cf6c
|
refs/heads/master
| 2020-06-11T14:52:22.726458
| 2017-01-30T16:19:50
| 2017-01-30T16:19:50
| 75,645,188
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 691
|
cpp
|
Posicao.cpp
|
#include "Posicao.h"
Edificio* Posicao::getEdifico()
{
return e;
}
void Posicao::setEdificio(Edificio * e)
{
this->e = e;
}
Ser* Posicao::getSer()
{
return s;;
}
void Posicao::setSer(Ser * s)
{
this->s = s;
}
//char Posicao::getColonia()
//{
// return c->getNome();
//}
//void Posicao::setColonia(Colonia * c)
//{
// this->c = c;
//}
//bool Posicao::verificaColonia()
//{
// if (c != NULL)
// return true;
// return false;
//}
bool Posicao::verificaEdifico()
{
if (e != NULL)
return true;
return false;
}
bool Posicao::verificaSer()
{
if (s != NULL)
return true;
return false;
}
Posicao::Posicao()
{
e = nullptr;
s = nullptr;
//c = NULL;
}
Posicao::~Posicao()
{
}
|
1bed65962e07cf214f1442997d59e6bc7eba1590
|
ea38d3b832a578614b2bd2fa5854ca3c689a9f46
|
/src/main.cpp
|
086cf9b65b54985dd21a93e775346cd601a1d041
|
[
"MIT"
] |
permissive
|
kmikolaj/explayer
|
a8be1910d5d3f9384772d2606ac620130c556e6e
|
1b521ef80c5108ff10a9e910d6163a9940de5599
|
refs/heads/master
| 2021-01-20T10:56:35.675005
| 2019-11-16T14:25:18
| 2019-11-16T14:25:18
| 18,986,657
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 326
|
cpp
|
main.cpp
|
#include "ui/mainwindow.h"
#include <QApplication>
#include <iostream>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// create main window
MainWindow w;
w.show();
std::cout << qPrintable(MainWindow::GetVersionInfo()) << std::endl;
if (argc > 1)
{
w.startPlaying(argv[1]);
}
return a.exec();
}
|
a749302ec17d2041ada0eb04950191abf42ca95e
|
bed217b9beaeaa52a38ccc82179ab05b2a5e33a0
|
/lib/bt_socket.cpp
|
1c38ca1bcceb7c2f7fd378f8a1ef04526d831b01
|
[
"Apache-2.0"
] |
permissive
|
comarius/bunget
|
734c6bafdba82522fd327eb60d20d84a30bfd2fa
|
22f7fd70bb6b5d1e5c7ad290ff3790e8c0f53c94
|
refs/heads/master
| 2020-12-24T08:01:43.259746
| 2020-08-28T17:07:20
| 2020-08-28T17:07:20
| 71,477,231
| 26
| 15
|
NOASSERTION
| 2018-10-15T17:53:21
| 2016-10-20T15:30:51
|
C++
|
UTF-8
|
C++
| false
| false
| 1,507
|
cpp
|
bt_socket.cpp
|
/**
Copyright: zirexix 2016
This program is distributed
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
The library or code from is restricted to be used in commercial products
without bunget.cert file. Please obtain a custom cert file from admin@meeiot.org
*/
#include "uguid.h"
#include "hci_socket.h"
#include "bu_hci.h"
#include "libbungetpriv.h"
/****************************************************************************************
*/
typedef enum
{
BT_IO_L2CAP,
BT_IO_RFCOMM,
BT_IO_SCO,
BT_IO_INVALID,
} BtIOType;
/****************************************************************************************
*/
bt_socket::~bt_socket()
{
close();
}
/****************************************************************************************
*/
void bt_socket::close()
{
if(_sock>0)
{
::close(_sock);
_sock = 0;
}
}
/****************************************************************************************
*/
int bt_socket::read(uint8_t* buffer, int sizeb)
{
return ::read(this->_sock, buffer, sizeb);
}
/****************************************************************************************
*/
int bt_socket:: writeocts(const uint8_t* buffer, int sizeb)
{
bybuff data(buffer,sizeb);
int r = ::write(this->_sock, buffer, sizeb);
TRACE("\n<--[" <<int(data.length())<<"/"<<r<<"]" << data.to_string());
::fsync(this->_sock);
return r;
}
|
f4da5c757d7dd212ecfb406c20fe01004f6d0b55
|
61e7696056ed6fee7dfbbdaa86e04aa9ed48a137
|
/voronoi_area_estimator.h
|
a464c94ffac4d4d6fbff66819dd1c64102cf041a
|
[] |
no_license
|
xingyu-wang/LPFluidCode
|
aab04e9376859a5c07676a855e84671f761cee1e
|
b69efba81ca0f647c8518e1c3b96953b17a629d8
|
refs/heads/master
| 2021-07-24T05:57:24.796111
| 2017-11-02T17:53:14
| 2017-11-02T17:53:14
| 108,578,815
| 1
| 0
| null | 2017-10-27T18:06:48
| 2017-10-27T18:06:48
| null |
UTF-8
|
C++
| false
| false
| 1,407
|
h
|
voronoi_area_estimator.h
|
#ifndef __VORONOI_AREA_ESTIMATOR__
#define __VORONOI_AREA_ESTIMATOR__
#include "libqhullcpp/RboxPoints.h"
#include "libqhullcpp/QhullError.h"
#include "libqhullcpp/QhullQh.h"
#include "libqhullcpp/QhullFacet.h"
#include "libqhullcpp/QhullFacetList.h"
#include "libqhullcpp/QhullLinkedList.h"
#include "libqhullcpp/QhullVertex.h"
#include "libqhullcpp/QhullVertexSet.h"
#include "libqhullcpp/QhullSet.h"
#include "libqhullcpp/Qhull.h"
#include "libqhullcpp/QhullPoint.h"
#include <cstdio>
#include <ostream>
#include <stdexcept>
#include <vector>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using orgQhull::Qhull;
using orgQhull::QhullError;
using orgQhull::QhullFacet;
using orgQhull::QhullFacetList;
using orgQhull::QhullQh;
using orgQhull::RboxPoints;
using orgQhull::QhullVertex;
using orgQhull::QhullVertexSet;
using orgQhull::QhullVertexList;
using orgQhull::QhullPoint;
using orgQhull::QhullPoints;
class VoronoiAreaEstimator{
private:
int dimension;
int number_of_points;
const double* x_coord;
const double* y_coord;
const double* z_coord;
const double* mass;
double* area;
public:
VoronoiAreaEstimator(int d, int N, const double* x, const double* y, const double* z, const double* m, double* a): dimension(d),number_of_points(N), x_coord(x), y_coord(y), z_coord(z), area(a) {};
virtual ~VoronoiAreaEstimator() {};
int ComputeVoronoiArea();
};
#endif
|
c569ee9d1aa2668bd48e82a518e8f7c9a6f075d1
|
248ad1e409c75bcf277633444979221ecf0b2ad4
|
/src/Core/Query/TranslationVisitor.cpp
|
78e8688d4a41c4749c986b388ad7cb87caed1a03
|
[] |
no_license
|
TAPAAL/verifydtapn
|
abb6eda4e4ba2303fa36becc9a0e1415dcd9f87b
|
32515f04c1ce33d89771159b5200582e85a6cbcb
|
refs/heads/main
| 2023-05-26T19:41:28.137695
| 2023-05-11T20:30:59
| 2023-05-11T20:30:59
| 310,008,166
| 3
| 4
| null | 2023-02-01T11:48:21
| 2020-11-04T13:18:03
|
C++
|
UTF-8
|
C++
| false
| false
| 9,355
|
cpp
|
TranslationVisitor.cpp
|
#include "Core/Query/TranslationVisitor.h"
#include "Core/TAPN/TAPN.hpp"
namespace VerifyTAPN {
namespace AST {
void TranslationVisitor::check_first(bool is_quant) {
if (!_first_element && is_quant) {
std::cerr << "Quantifiers only allowed as topmost element" << std::endl;
std::exit(-1);
} else if (_first_element && !is_quant) {
std::cerr << "Topmost element must be a quantifier" << std::endl;
std::exit(-1);
}
_first_element = false;
}
AST::Expression* TranslationVisitor::get_e_result() {
if (!_e_result) {
std::cerr << "Could not translate query" << std::endl;
std::exit(-1);
}
auto r = _e_result;
_e_result = nullptr;
return r;
}
AST::ArithmeticExpression* TranslationVisitor::get_a_result() {
if (!_a_result) {
std::cerr << "Could not translate query" << std::endl;
std::exit(-1);
}
auto r = _a_result;
_a_result = nullptr;
return r;
}
TranslationVisitor::TranslationVisitor(const TAPN::TimedArcPetriNet& net)
: _net(net) {
}
std::unique_ptr<Query> TranslationVisitor::translate(const unfoldtacpn::PQL::Condition& condition) {
condition.visit(*this);
return std::unique_ptr<Query>(_result.release());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::NotCondition *element) {
check_first();
(*element)[0]->visit(*this);
_e_result = new AST::NotExpression(get_e_result());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::AndCondition *element) {
check_first();
AST::Expression* old = nullptr;
for (auto& sub : *element) {
sub->visit(*this);
if (old != nullptr)
old = new AST::AndExpression(get_e_result(), old);
else
old = get_e_result();
}
_e_result = old;
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::OrCondition *element) {
check_first();
AST::Expression* old = nullptr;
for (auto& sub : *element) {
sub->visit(*this);
if (old != nullptr)
old = new AST::OrExpression(get_e_result(), old);
else
old = get_e_result();
}
_e_result = old;
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::LessThanCondition *element) {
check_first();
(*element)[0]->visit(*this);
auto lhs = get_a_result();
(*element)[1]->visit(*this);
auto rhs = get_a_result();
_e_result = new AST::AtomicProposition(lhs, AtomicProposition::LT, rhs);
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::LessThanOrEqualCondition *element) {
check_first();
(*element)[0]->visit(*this);
auto lhs = get_a_result();
(*element)[1]->visit(*this);
auto rhs = get_a_result();
_e_result = new AST::AtomicProposition(lhs, AtomicProposition::LE, rhs);
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::EqualCondition *element) {
check_first();
(*element)[0]->visit(*this);
auto lhs = get_a_result();
(*element)[1]->visit(*this);
auto rhs = get_a_result();
_e_result = new AST::AtomicProposition(lhs, AtomicProposition::EQ, rhs);
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::NotEqualCondition *element) {
check_first();
(*element)[0]->visit(*this);
auto lhs = get_a_result();
(*element)[1]->visit(*this);
auto rhs = get_a_result();
_e_result = new AST::AtomicProposition(lhs, AtomicProposition::NE, rhs);
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::DeadlockCondition *element) {
check_first();
_e_result = new DeadlockExpression();
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::ControlCondition *condition) {
if(_is_synth)
{
std::cerr << "control-tag used twice in query!" << std::endl;
std::exit(-1);
}
if(!_first_element)
{
std::cerr << "control-tag must be top-most element" << std::endl;
std::exit(-1);
}
_is_synth = true;
(*condition)[0]->visit(*this);
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::EFCondition *condition) {
if(_is_synth)
{
std::cerr << "Synthesis only enabled for AG and AF propositions" << std::endl;
std::exit(-1);
}
check_first(true);
(*condition)[0]->visit(*this);
_result = std::make_unique<Query>(Quantifier::EF, get_e_result());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::EGCondition *condition) {
if(_is_synth)
{
std::cerr << "Synthesis only enabled for AG and AF propositions" << std::endl;
std::exit(-1);
}
check_first(true);
(*condition)[0]->visit(*this);
_result = std::make_unique<Query>(Quantifier::EG, get_e_result());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::AGCondition *condition) {
check_first(true);
(*condition)[0]->visit(*this);
_result = std::make_unique<Query>(_is_synth ? Quantifier::CG : Quantifier::AG, get_e_result());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::AFCondition *condition) {
check_first(true);
(*condition)[0]->visit(*this);
_result = std::make_unique<Query>(_is_synth ? Quantifier::CF : Quantifier::AF, get_e_result());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::BooleanCondition *element) {
check_first();
_e_result = new BoolExpression(element->value());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::UnfoldedIdentifierExpr *element) {
check_first();
auto id = _net.getPlaceIndex(element->name());
if (id == TAPN::TimedPlace::BottomIndex()) {
std::cerr << "Could not find " << element->name() << std::endl;
std::exit(-1);
}
_a_result = new IdentifierExpression(id);
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::LiteralExpr *element) {
check_first();
_a_result = new NumberExpression(element->value());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::PlusExpr *element) {
ArithmeticExpression* old = nullptr;
check_first();
for (auto& e : (*element)) {
e->visit(*this);
if (old != nullptr)
old = new PlusExpression(old, get_a_result());
else
old = get_a_result();
}
_a_result = old;
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::MultiplyExpr *element) {
ArithmeticExpression* old = nullptr;
check_first();
for (auto& e : (*element)) {
e->visit(*this);
if (old != nullptr)
old = new MultiplyExpression(old, get_a_result());
else
old = get_a_result();
}
_a_result = old;
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::MinusExpr *element) {
check_first();
(*element)[0]->visit(*this);
_a_result = new AST::MinusExpression(get_a_result());
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::SubtractExpr *element) {
ArithmeticExpression* old = nullptr;
check_first();
for (auto& e : (*element)) {
e->visit(*this);
if (old != nullptr)
old = new SubtractExpression(old, get_a_result());
else
old = get_a_result();
}
_a_result = old;
}
void TranslationVisitor::_accept(const unfoldtacpn::PQL::IdentifierExpr *element) {
check_first();
if (element->compiled()) {
element->compiled()->visit(*this);
} else {
auto id = _net.getPlaceIndex(element->name());
if (id == TAPN::TimedPlace::BottomIndex()) {
std::cerr << "Could not find " << element->name() << std::endl;
std::exit(-1);
}
_a_result = new IdentifierExpression(id);
}
}
}
}
|
957c821e5a1682103a69bbc83af5a1a47d866bbc
|
10339a5ad20958f6ddd347f7adafdc0203bfd147
|
/.svn/text-base/SitRun.h.svn-base
|
0ee307438f0abfb90e726e0e0e3554c61be2d0d2
|
[] |
no_license
|
hyperchi/Cpp
|
536132ad8e4b1f5126db5f4727488cc062ff2acd
|
ddfbd9b2be71aa92ea22c62838442f0ea8166a53
|
refs/heads/master
| 2020-05-31T15:09:57.173302
| 2014-12-03T16:41:20
| 2014-12-03T16:41:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 676
|
SitRun.h.svn-base
|
#ifndef __SITRUN_H__
#define __SITRUN_H__
#include "WorldModel.h"
#include "AgentInfo.h"
#include "SitUnitSquare.h"
#include "ConfFileRead.h"
#include "Logger.h"
class SitRun
{
public:
SitRun( WorldModel *wm, FieldSquare *square, AgentInfo *agentInfo );
~SitRun();
private:
WorldModel *mWorldModel;
FieldSquare *mFieldSquare;
AgentInfo *mAgentInfo;
public:
Vector3f AttackRunPos( AttDefkTrend attDefTrend );
private:
Vector3f FullAttackRunPos();
Vector3f TrendAttackRunPos();
Vector3f NormalAttackRunPos();
Vector3f FullDefenceRunPos();
Vector3f TrendDefenceRunPos();
Vector3f NormalDefenceRunPos();
};
#endif //__SITRUN_H__
|
|
a5a7a0ef0092f5f166dafc1dfcf0ef01e472ac7b
|
12859d9f634a6d6e67a346aa95135b94ec2b000d
|
/Sail/src/Sail/api/Mesh.cpp
|
84a3666ead71c500ba83f744dc017814abc1e8ec
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
Piratkopia13/Sail
|
ba2add46a5332f3aa1d19f54f053be9bf9e909c6
|
c428024967cd7aa75e45d5fe9418a1d565881279
|
refs/heads/master
| 2021-05-25T11:01:39.408492
| 2020-10-10T19:39:34
| 2020-10-10T19:39:34
| 127,143,207
| 10
| 5
|
MIT
| 2020-10-14T15:04:23
| 2018-03-28T13:18:42
|
C++
|
UTF-8
|
C++
| false
| false
| 3,271
|
cpp
|
Mesh.cpp
|
#include "pch.h"
#include "Mesh.h"
#include "VertexBuffer.h"
#include "IndexBuffer.h"
#include "Sail/Application.h"
#include "Sail/api/shader/PipelineStateObject.h"
#include "Sail/api/shader/Shader.h"
Mesh::Mesh(Data& buildData)
: meshData(buildData)
{ }
Mesh::~Mesh() {
Memory::SafeDeleteArr(meshData.indices);
Memory::SafeDeleteArr(meshData.positions);
Memory::SafeDeleteArr(meshData.normals);
Memory::SafeDeleteArr(meshData.bitangents);
Memory::SafeDeleteArr(meshData.colors);
Memory::SafeDeleteArr(meshData.tangents);
Memory::SafeDeleteArr(meshData.texCoords);
}
unsigned int Mesh::getAttributesHash() {
unsigned int hash = 0;
unsigned int mul = 1;
if (meshData.positions) {
hash = InputLayout::POSITION;
mul *= 10;
}
if (meshData.texCoords) {
hash += InputLayout::TEXCOORD * mul;
mul *= 10;
}
if (meshData.normals) {
hash += InputLayout::NORMAL * mul;
mul *= 10;
}
if (meshData.tangents) {
hash += InputLayout::TANGENT * mul;
mul *= 10;
}
if (meshData.bitangents) {
hash += InputLayout::BITANGENT * mul;
mul *= 10;
}
return hash;
}
unsigned int Mesh::getNumVertices() const {
return meshData.numVertices;
}
unsigned int Mesh::getNumIndices() const {
return meshData.numIndices;
}
unsigned int Mesh::getNumInstances() const {
return meshData.numInstances;
}
VertexBuffer& Mesh::getVertexBuffer() const {
return *vertexBuffer;
}
IndexBuffer& Mesh::getIndexBuffer() const {
return *indexBuffer;
}
void Mesh::Data::deepCopy(const Data& other) {
this->numIndices = other.numIndices;
this->numVertices = other.numVertices;
this->numInstances = other.numInstances;
if (other.indices) {
this->indices = SAIL_NEW unsigned long[other.numIndices];
for (unsigned int i = 0; i < other.numIndices; i++)
this->indices[i] = other.indices[i];
}
unsigned int numVerts = (other.numIndices > 0) ? other.numIndices : other.numVertices;
if (other.positions) {
this->positions = SAIL_NEW Mesh::vec3[numVerts];
for (unsigned int i = 0; i < numVerts; i++)
this->positions[i] = other.positions[i];
}
if (other.normals) {
this->normals = SAIL_NEW Mesh::vec3[numVerts];
for (unsigned int i = 0; i < numVerts; i++)
this->normals[i] = other.normals[i];
}
if (other.colors) {
this->colors = SAIL_NEW Mesh::vec4[numVerts];
for (unsigned int i = 0; i < numVerts; i++)
this->colors[i] = other.colors[i];
}
if (other.texCoords) {
this->texCoords = SAIL_NEW Mesh::vec2[numVerts];
for (unsigned int i = 0; i < numVerts; i++)
this->texCoords[i] = other.texCoords[i];
}
if (other.tangents) {
this->tangents = SAIL_NEW Mesh::vec3[numVerts];
for (unsigned int i = 0; i < numVerts; i++)
this->tangents[i] = other.tangents[i];
}
if (other.bitangents) {
this->bitangents = SAIL_NEW Mesh::vec3[numVerts];
for (unsigned int i = 0; i < numVerts; i++)
this->bitangents[i] = other.bitangents[i];
}
}
//unsigned int Mesh::Data::calculateVertexStride() const {
// unsigned int stride = 0.f;
// if (positions) stride += sizeof(Mesh::vec3);
// if (normals) stride += sizeof(Mesh::vec3);
// if (colors) stride += sizeof(Mesh::vec4);
// if (texCoords) stride += sizeof(Mesh::vec2);
// if (tangents) stride += sizeof(Mesh::vec3);
// if (bitangents) stride += sizeof(Mesh::vec3);
// return stride;
//}
|
7ba84c4722e5abf8b87f2c04bbf6f858c86f48ca
|
1fe9d08e20ad45de86a60e3fd5e044f779539808
|
/VectorsAndIOmanip/Gas_vehicle.cpp
|
97396facf4f1e4d5a08f14f0b950b103d8c4f494
|
[] |
no_license
|
bailey-brown/Object-Oriented-Programming-CPP
|
12e0328a2ba6ff0834467bd2da750cde8d76bbda
|
ac01bc82a17c8d5af85169c8cfe388dee820cefc
|
refs/heads/master
| 2020-12-05T17:54:42.603793
| 2020-01-06T23:46:25
| 2020-01-06T23:46:25
| 232,197,419
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 416
|
cpp
|
Gas_vehicle.cpp
|
#include <string>
#include "gas_vehicle.h"
Gas_vehicle::Gas_vehicle(int year, std::string make, std::string model, Body_style body_style, double miles_per_gallon, double max_gallons)
: Vehicle(year, make, model, body_style), _miles_per_gallon{miles_per_gallon}, _max_gallons{max_gallons} { }
double Gas_vehicle::gallons_consumed(double miles) {
return miles / _miles_per_gallon;
}
|
d55b22b1ae59964f72f8f660d9475e3941fc9395
|
84dc2c53b76c3193899e325f9ac95dace0284257
|
/my_utils.h
|
22b5fc545b25bcef02c3fcb511290a7fe2596d3a
|
[] |
no_license
|
NatPath/MatamFinalProject
|
9ce14d525c5ba9c0139bf03cecab0b346c4be258
|
38ebae0a02fd290ebd57eb8ad015e024e63fd271
|
refs/heads/master
| 2022-12-11T04:59:56.904225
| 2020-08-27T16:34:01
| 2020-08-27T16:34:01
| 284,483,279
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,292
|
h
|
my_utils.h
|
#ifndef _MY_UTILS_H
#define _MY_UTILS_H
#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <map>
#include <utility>
#include <exception>
#include <regex>
#include <algorithm>
//"Naming things is useful for readability and sanity"- Albert Einstein
typedef std::vector<std::string> Tokens;
typedef std::string Vertex;
typedef std::pair<Vertex,Vertex> Edge;
typedef std::set<Vertex> Vertices;
typedef std::set<Edge> Edges;
//template print for printable objects, assumes T is printable
template<class T>
void print(T str){
std::cout<<str<<std::endl;
}
//checks if a set contains an element. assumes T is comparable
template<class T>
bool setContains(const std::set<T>& s,const T& elem){
return s.find(elem)!=s.end();
}
//compare between two pairs, see if there is a Match of both their fields, assumes T and S are comparble
template<class T,class S>
bool operator==(std::pair<T,S> a,std::pair<T,S> b){
return a.first==b.first&&a.second==b.second;
}
//returns sub-Tokens starting with element in index of "start" and of the size of "size"
Tokens inRange(const Tokens& vec,int start,int size);
//returns sub-Tokens from iterators , from begin to end
Tokens inRange(const Tokens& vec, Tokens::const_iterator& begin,Tokens::const_iterator& end);
#endif
|
0ea8ab9d8b51f1569ef2798b7f84548ad41c9c2e
|
317f2542cd92aa527c2e17af5ef609887a298766
|
/tools/target_10_2_0_1155/qnx6/usr/include/bb/cascades/animation/abstractanimation.h
|
3e9f90d6b41208862ef40c6003062881766fb7f5
|
[] |
no_license
|
sborpo/bb10qnx
|
ec77f2a96546631dc38b8cc4680c78a1ee09b2a8
|
33a4b75a3f56806f804c7462d5803b8ab11080f4
|
refs/heads/master
| 2020-07-05T06:53:13.352611
| 2014-12-12T07:39:35
| 2014-12-12T07:39:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,835
|
h
|
abstractanimation.h
|
/* Copyright (C) 2011-2013 Research In Motion Limited. Proprietary and confidential. */
#ifndef cascades_abstractanimation_h
#define cascades_abstractanimation_h
#include <QtDeclarative/QtDeclarative>
#include <QtDeclarative/QDeclarativeListProperty>
#include <bb/cascades/bbcascades_global.h>
#include <bb/cascades/core/uiobject.h>
#include <bb/cascades/core/visualnode.h>
#include <bb/cascades/animation/animationstate.h>
#include <bb/cascades/animation/animationrepeatcount.h>
namespace bb {
namespace cascades {
class AbstractAnimationPrivate;
/*!
*
* @brief Abstract class containing properties inherited by all animations.
*
* Animations represent a change, over time, of a property or set of properties according to specified rules.
* Each animation that inherits this class has a @c #target property (the node that the animation changes),
* a @c #delay property (the time between initiation and when the animation actually starts)
* and a @c #repeatCount property (the number of times the animation is repeated).
*
* Once an animation is playing, changing its properties will not take effect
* until the next time animation is re-started (either stopped and started, or ended
* and started).
*
* @xmlonly
* <apigrouping group="User interface/Animations"/>
* @endxmlonly
*
* @since BlackBerry 10.0.0
*/
class BBCASCADES_EXPORT AbstractAnimation : public UIObject {
Q_OBJECT
/*!
* @brief The target for the animation.
*
* Even if a target is not explicitly set, the animation
* can have an implicit target in the following instances:
*
* - If the animation is a child of a @c VisualNode object, the parent is assumed to be the
* animation's implicit target
* - If the animation is a child of a @c GroupAnimation object, the @c GroupAnimation
* object's target is assumed to be the animation's implicit target
*
* If an animation has children, setting the explicit target for the animation causes the children's
* implicit targets to change accordingly.
*
* When the target node is explicitly set on the animation, the node it is attached to
* does not take ownership, meaning that if the target node is destroyed, the animation
* is not removed with it. To help manage the animation lifecycle, the ownership of an
* animation can assigned to a @c VisualNode by calling @c VisualNode::addAnimation().
* This can help ensure that the animation's memory is cleaned up properly.
*
* Once an animation is playing, changing its properties will not take effect
* until the next time animation is started.
*
* The default value of this property is @c 0.
*
* @since BlackBerry 10.0.0
*/
Q_PROPERTY(bb::cascades::VisualNode* target READ target WRITE setTarget RESET resetTarget NOTIFY targetChanged FINAL)
/*!
* @brief The delay (in milliseconds) before an animation executes when the @c play()
* function is invoked.
*
* Once an animation is playing, changing its properties will not take effect
* until the next time animation is started.
*
* The default delay is @c 0.
*
* @since BlackBerry 10.0.0
*/
Q_PROPERTY(int delay READ delay WRITE setDelay RESET resetDelay NOTIFY delayChanged FINAL)
/*!
* @brief The number of times that an animation runs.
*
* Once an animation is playing, changing its properties will not take effect
* until the next time animation is started.
*
* To have an animation run forever, you can specify @c AnimationRepeatCount::Forever. Here's
* how you can set an animation to run forever in QML:
*
* @snippet tad/examples/animation/abstractanimation/assets/main.qml abstractanimation_repeatforever
*
* The default value is @c 1. This must not be a negative value.
*
* @since BlackBerry 10.0.0
*/
Q_PROPERTY(int repeatCount READ repeatCount WRITE setRepeatCount RESET resetRepeatCount NOTIFY repeatCountChanged FINAL)
/*!
* @brief The current state of the animation.
*
* The default value is @c bb::cascades:AnimationState::Stopped.
*
* @since BlackBerry 10.0.0
*/
Q_PROPERTY(bb::cascades::AnimationState::Type state READ state NOTIFY stateChanged FINAL)
public:
/*!
* @brief Destructs an @c %AbstractAnimation object.
*
* @since BlackBerry 10.0.0
*/
virtual ~AbstractAnimation();
/*!
* @brief Returns the explicit target for the animation.
*
* Once the operation is completed, ownership of the animation does not change.
* This function only works for explicit targets; implicit targets are not returned.
*
* @return The explicit target for the animation, or @c 0 if a target is not set.
*
* @since BlackBerry 10.0.0
*/
bb::cascades::VisualNode *target() const;
/*!
* @brief Sets the explicit target for the animation.
*
* Once the operation is completed, ownership of the passed object does not change.
* The animation does not become a child of the target @c VisualNode.
*
* Once an animation is playing, changing its properties will not take effect
* until the next time animation is started.
*
* If an animation has children, setting the explicit target for the animation causes
* the children's implicit targets to change accordingly (unless they already have
* an explicit target).
*
* @param target The explicit target for the animation, or @c 0 to remove the current target.
*
*
* @since BlackBerry 10.0.0
*/
Q_SLOT void setTarget(bb::cascades::VisualNode * target);
/*!
* @brief Resets the @c #target to its default value of @c 0.
*
* @since BlackBerry 10.0.0
*/
Q_SLOT void resetTarget();
/*!
* @brief Returns the current state.
*
* @since BlackBerry 10.0.0
*/
bb::cascades::AnimationState::Type state() const;
/*!
* @brief Indicates whether the animation has been started but is not yet playing.
*
* If the animation is a child of a @c GroupAnimation object, this
* function cannot be used to determine the state of this animation
* node. Only the root @c %GroupAnimation in an animation tree will indicate
* its state correctly.
*
* @return @c true if the animation is started, but not yet playing,
* @c false otherwise.
*
* @since BlackBerry 10.0.0
*/
Q_INVOKABLE bool isStarted() const;
/*!
* @brief Indicates whether the animation is currently playing.
*
* Note that if this node is a child of @c GroupAnimation this
* method cannot be used to determine the state of this animation
* node. Only the root @c %GroupAnimation in an animation tree will indicate
* its state correctly.
*
* @return @c true if the animation is currently playing, @c false otherwise.
*
* @since BlackBerry 10.0.0
*/
Q_INVOKABLE bool isPlaying() const;
/*!
* @brief Indicates whether the animation was interrupted by the @c stop() function.
*
* It should be noted that if this node is a child of @c GroupAnimation this
* method cannot be used to determine the state of this animation
* node. Only the root @c %GroupAnimation in an animation tree will indicate
* its state correctly.
*
* @return @c true if the animation was interrupted, @c false otherwise.
*
* @since BlackBerry 10.0.0
*/
Q_INVOKABLE bool isStopped() const;
/*!
* @brief Indicates whether the animation has ended.
*
* An animation has ended if it has run its course without being stopped.
* It should be noted that if this node is a child of @c GroupAnimation this
* method cannot be used to determine the state of this animation
* node. Only the root @c %GroupAnimation in an animation tree will indicate
* its state correctly.
*
* @return @c true if the animation has ended, @c false otherwise.
*
* @since BlackBerry 10.0.0
*/
Q_INVOKABLE bool isEnded() const;
/*!
* @brief Returns the delay (in milliseconds) before an animation executes after the
* @c play() function is invoked.
*
* @return A non-negative number indicating the delay of this animation.
*
* @since BlackBerry 10.0.0
*/
int delay() const;
/*!
* @brief Sets the delay (in milliseconds) before an animation executes after the
* @c play() function is invoked.
*
* The passed argument must be non-negative or it is ignored.
*
* @param delay A non-negative number representing animation delay in milliseconds.
*
* @since BlackBerry 10.0.0
*/
void setDelay(int delay);
/*!
* @brief Resets the @c #delay to its default value of @c 0 milliseconds.
*
* @since BlackBerry 10.0.0
*/
Q_SLOT void resetDelay();
/*!
* @brief Returns the value of the @c #repeatCount property.
*
* The @c repeatCount property is the number of times the
* animation will be repeated after it started.
*
* @return A positive number indicating the number of times this animation will
* be repeated. If @c #repeatCount is equal to @c bb::cascades::AnimationRepeatCount::Forever,
* the animation will repeat indefinitely.
*
* @since BlackBerry 10.0.0
*/
int repeatCount() const;
/*!
* @brief Sets the value of the @c #repeatCount property.
*
* The @c repeatCount property is the number of times that the
* animation will be repeated after it started. The passed argument must be
* positive or it is ignored.
*
* @c #bb::cascades::AnimationRepeatCount::Forever can be used to specify an animation that repeats forever.
*
* @param repeatCount A positive number representing number of times animation will be repeated.
*
* @since BlackBerry 10.0.0
*/
void setRepeatCount(int repeatCount);
/*!
* @brief Resets the @c #repeatCount property to its default value of @c 1.
*
* @since BlackBerry 10.0.0
*/
Q_SLOT void resetRepeatCount();
/*!
* @brief A constant to be used for specifying an animation that repeats forever.
*
* @deprecated Use @c bb::cascades::AnimationRepeatCount::Forever instead.
*
* @see #setRepeatCount()
*
* @since BlackBerry 10.0.0
*/
static const int RepeatForever;
/*!
* @brief Plays the animation.
*
* Only the root animation in a tree of animations can be played explicitly. If
* this function is called on a child animation, the function is ignored.
*
* If more than one animation is affecting the same property, calling @c play() on more
* than one will stop the running one.
*
* @since BlackBerry 10.0.0
*/
Q_SLOT void play();
/*!
* @brief Stops this animation.
*
* If the animation is started again it will restart from the beginning.
*
* Only the root animation in a tree of animations can be stopped explicitly. If
* this function is called on a child animation, the function is ignored.
*
* @since BlackBerry 10.0.0
*/
Q_SLOT void stop();
Q_SIGNALS:
/*!
* @brief Emitted when the animation is started.
*
* Note that this may happen sometimes after the @c play() method is invoked.
*
* This signal is not emitted for child animations.
*
* @since BlackBerry 10.0.0
*/
void started();
/*!
* @brief Emitted when the animation is stopped.
*
* Note that this may happen sometimes after the @c stop() method is invoked.
* It will also be emitted if an animation is stopped because a different
* animation, implicit or explicit, is started on the same value.
*
* The animation can be deleted from this signal only using
* @c QObject::deleteLater() signal.
*
* This signal is not emitted for child animations.
*
* @since BlackBerry 10.0.0
*/
void stopped();
/*!
* @brief Emitted when the animation has ended.
*
* The animation can be deleted from this signal only using
* @c QObject::deleteLater() signal.
*
* This signal is not emitted for child animations.
*
* @since BlackBerry 10.0.0
*/
void ended();
/*!
* @brief Emitted when the @c #target property changed.
*
* @param target The new target or @c 0 if it was unset.
*
* @since BlackBerry 10.0.0
*/
void targetChanged(bb::cascades::VisualNode *target);
/*!
* @brief Emitted when the @c #delay of the animation changes.
*
* @param delay The new delay for the animation.
*
* @since BlackBerry 10.0.0
*/
void delayChanged(int delay);
/*!
* @brief Emitted when the @c #repeatCount of the animation changes.
*
* @param repeatCount The new repeat count for the animation.
*
* @since BlackBerry 10.0.0
*/
void repeatCountChanged(int repeatCount);
/*!
* @brief Emitted when the @c #state of the animation changes.
*
* @param newState The new state of the animation.
*
* @since BlackBerry 10.0.0
*/
void stateChanged(bb::cascades::AnimationState::Type newState);
protected:
/*! @cond PRIVATE */
AbstractAnimation(AbstractAnimationPrivate &_d_ptr);
/*! @endcond */
private:
/*! @cond PRIVATE */
void setAutoDeleted(bool autoDeleted);
Q_DECLARE_PRIVATE(AbstractAnimation)
Q_DISABLE_COPY(AbstractAnimation)
/*! @endcond */
// BUILDER ---------------------------------
public:
/*! @cond PRIVATE */
typedef AbstractAnimation ThisClass;
typedef UIObject BaseClass;
/*! @endcond */
/*!
* @brief A base builder template for constructing AbstractAnimation descendants
*
* @since BlackBerry 10.0.0
*/
template <typename BuilderType, typename BuiltType>
class TBuilder : public BaseClass::TBuilder<BuilderType, BuiltType> {
protected:
TBuilder(BuiltType* node) : BaseClass::TBuilder<BuilderType, BuiltType>(node) {
}
public:
/*!
* @copydoc AbstractAnimation::setTarget()
*/
BuilderType& target(VisualNode *target) {
this->instance().setTarget(target);
return this->builder();
}
/*!
* @copydoc AbstractAnimation::setDelay()
*/
BuilderType& delay(int delay) {
this->instance().setDelay(delay);
return this->builder();
}
/*!
* @copydoc AbstractAnimation::setRepeatCount()
*/
BuilderType& repeatCount(int repeatCount) {
this->instance().setRepeatCount(repeatCount);
return this->builder();
}
/*!
* @brief Specifies whether this animation should be automatically deleted
* when it ends.
*
* This setting is ignored for non-child animations. If the animation is interrupted
* (stopped) it will not be auto-deleted.
*
* If an auto-deleted animation is stopped the application is expected to
* delete the animation in response to the @c stopped() signal
* using @c QObject::deleteLater() signal.
*
*
* @since BlackBerry 10.0.0
*/
BuilderType& autoDeleted(bool autoDeleted = true) {
this->instance().setAutoDeleted(autoDeleted);
return this->builder();
}
};
};
}
}
QML_DECLARE_TYPE(bb::cascades::AbstractAnimation)
#endif // cascades_abstractanimation_h
|
ff910cfdac2ef4458a1886ce6b73471fb4e6a0a0
|
5ec06dab1409d790496ce082dacb321392b32fe9
|
/clients/cpp-pistache-server/generated/model/OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties.h
|
1ba4e3a81a17aaa711feeabca905f6a8e1fcffeb
|
[
"Apache-2.0"
] |
permissive
|
shinesolutions/swagger-aem-osgi
|
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
|
c2f6e076971d2592c1cbd3f70695c679e807396b
|
refs/heads/master
| 2022-10-29T13:07:40.422092
| 2021-04-09T07:46:03
| 2021-04-09T07:46:03
| 190,217,155
| 3
| 3
|
Apache-2.0
| 2022-10-05T03:26:20
| 2019-06-04T14:23:28
| null |
UTF-8
|
C++
| false
| false
| 5,209
|
h
|
OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties.h
|
/**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties.h
*
*
*/
#ifndef OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties_H_
#define OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties_H_
#include "ModelBase.h"
#include "ConfigNodePropertyBoolean.h"
#include "ConfigNodePropertyDropDown.h"
#include "ConfigNodePropertyString.h"
namespace org {
namespace openapitools {
namespace server {
namespace model {
/// <summary>
///
/// </summary>
class OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties
: public ModelBase
{
public:
OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties();
virtual ~OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties members
/// <summary>
///
/// </summary>
ConfigNodePropertyString getName() const;
void setName(ConfigNodePropertyString const& value);
bool nameIsSet() const;
void unsetName();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getTitle() const;
void setTitle(ConfigNodePropertyString const& value);
bool titleIsSet() const;
void unsetTitle();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getDetails() const;
void setDetails(ConfigNodePropertyString const& value);
bool detailsIsSet() const;
void unsetDetails();
/// <summary>
///
/// </summary>
ConfigNodePropertyBoolean getEnabled() const;
void setEnabled(ConfigNodePropertyBoolean const& value);
bool enabledIsSet() const;
void unsetEnabled();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getServiceName() const;
void setServiceName(ConfigNodePropertyString const& value);
bool serviceNameIsSet() const;
void unsetServiceName();
/// <summary>
///
/// </summary>
ConfigNodePropertyDropDown getLogLevel() const;
void setLogLevel(ConfigNodePropertyDropDown const& value);
bool logLevelIsSet() const;
void unsetLog_level();
/// <summary>
///
/// </summary>
ConfigNodePropertyBoolean getQueueProcessingEnabled() const;
void setQueueProcessingEnabled(ConfigNodePropertyBoolean const& value);
bool queueProcessingEnabledIsSet() const;
void unsetQueue_processing_enabled();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getPackageExporterTarget() const;
void setPackageExporterTarget(ConfigNodePropertyString const& value);
bool packageExporterTargetIsSet() const;
void unsetPackageExporter_target();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getPackageImporterTarget() const;
void setPackageImporterTarget(ConfigNodePropertyString const& value);
bool packageImporterTargetIsSet() const;
void unsetPackageImporter_target();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getRequestAuthorizationStrategyTarget() const;
void setRequestAuthorizationStrategyTarget(ConfigNodePropertyString const& value);
bool requestAuthorizationStrategyTargetIsSet() const;
void unsetRequestAuthorizationStrategy_target();
/// <summary>
///
/// </summary>
ConfigNodePropertyString getTriggersTarget() const;
void setTriggersTarget(ConfigNodePropertyString const& value);
bool triggersTargetIsSet() const;
void unsetTriggers_target();
protected:
ConfigNodePropertyString m_Name;
bool m_NameIsSet;
ConfigNodePropertyString m_Title;
bool m_TitleIsSet;
ConfigNodePropertyString m_Details;
bool m_DetailsIsSet;
ConfigNodePropertyBoolean m_Enabled;
bool m_EnabledIsSet;
ConfigNodePropertyString m_ServiceName;
bool m_ServiceNameIsSet;
ConfigNodePropertyDropDown m_Log_level;
bool m_Log_levelIsSet;
ConfigNodePropertyBoolean m_Queue_processing_enabled;
bool m_Queue_processing_enabledIsSet;
ConfigNodePropertyString m_PackageExporter_target;
bool m_PackageExporter_targetIsSet;
ConfigNodePropertyString m_PackageImporter_target;
bool m_PackageImporter_targetIsSet;
ConfigNodePropertyString m_RequestAuthorizationStrategy_target;
bool m_RequestAuthorizationStrategy_targetIsSet;
ConfigNodePropertyString m_Triggers_target;
bool m_Triggers_targetIsSet;
};
}
}
}
}
#endif /* OrgApacheSlingDistributionAgentImplSimpleDistributionAgentFactorProperties_H_ */
|
0b4a84b95b43fc33056cfa819bcd7aceb09e3585
|
3117b8eeb7f787a0713fb9bd62fd30d98c01e014
|
/SandBox/SpinComponent.cpp
|
5af6f7530e25af6153242825f25f85d215f7885e
|
[] |
no_license
|
EmilioLapointe/ProjectNotSummer
|
1ecbcc8e19f997432dc6bab4372bf5bcbf050840
|
4db725d3021463920041394a0c057b5ccb6122e5
|
refs/heads/master
| 2020-04-09T21:22:25.781723
| 2019-04-04T01:32:22
| 2019-04-04T01:32:22
| 160,600,185
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 831
|
cpp
|
SpinComponent.cpp
|
#include "SpinComponent.h"
SpinComponent::SpinComponent(TLGE::GameObject* objectInCharge):
Component(objectInCharge)
{
objectInCharge->RequireComponent<TLGE::Transform>();
}
SpinComponent::~SpinComponent()
{
//nothing to do
}
void SpinComponent::Update(float deltaTime)
{
TLGE::Transform* trans = m_objectInCharge->GetComponent<TLGE::Transform>();
trans->RotateX(1.0f * deltaTime * m_x);
trans->RotateY(1.0f * deltaTime * m_y);
trans->RotateZ(1.0f * deltaTime * m_z);
}
void SpinComponent::HandleEvent(TLGE::Event* aEvent)
{
if (strcmp(aEvent->GetType(), "KEY") == 0 && ((TLGE::KeyEvent*)(aEvent))->GetState() == TLGE::KeyState_JustPressed)
{
switch (((TLGE::KeyEvent*)(aEvent))->GetKey())
{
case 0x58:
m_x = !m_x;
break;
case 0x59:
m_y = !m_y;
break;
case 0x5A:
m_z = !m_z;
break;
}
}
}
|
f8f46c76628997a72ab42e87fd8b34d0e4d29aca
|
8898636e2bee1c31b28ed6ae8518f8d53fbce9b7
|
/manyfriends/src/manyfriends.cpp
|
b0166c31e1d700e92913ba5e5f199c1a1320d159
|
[] |
no_license
|
Yuanzjls/Cplusplus6th
|
423bb18ae861c779a864c1ad73f95a153469405f
|
1436e2cbb07ae1fb3b793c0152a6e9478a13750e
|
refs/heads/master
| 2021-08-14T08:10:18.063975
| 2017-11-15T02:32:04
| 2017-11-15T02:32:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 840
|
cpp
|
manyfriends.cpp
|
//============================================================================
// Name : manyfriends.cpp
// Author : Yuan
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
template <typename T>
class ManyFriend
{
private:
T item;
public:
ManyFriend(const T & i) : item(i) {}
template <typename C, typename D> friend void show2(C &, D &);
};
template <typename C, typename D> void show2(C &c, D &d)
{
cout << c.item << ", " << d.item << endl;
}
int main()
{
ManyFriend<int> hfi1(10);
ManyFriend<int> hfi2(20);
ManyFriend<double> hfdb(10.5);
cout << "hfi1, hfi2: ";
show2(hfi1, hfi2);
cout << "hfdb, hfi2: ";
show2(hfdb, hfi2);
return 0;
}
|
22a3c8ceb58efd0b8fd6819afb1e69127d0c17fd
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_repos_function_2459_httpd-2.4.25.cpp
|
5f5738f2711783368c297810bc0260e94994e314
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 567
|
cpp
|
httpd_repos_function_2459_httpd-2.4.25.cpp
|
static void calc_sha256_hash(h2_push_diary *diary, apr_uint64_t *phash, h2_push *push)
{
SHA256_CTX sha256;
apr_uint64_t val;
unsigned char hash[SHA256_DIGEST_LENGTH];
int i;
SHA256_Init(&sha256);
sha256_update(&sha256, push->req->scheme);
sha256_update(&sha256, "://");
sha256_update(&sha256, push->req->authority);
sha256_update(&sha256, push->req->path);
SHA256_Final(hash, &sha256);
val = 0;
for (i = 0; i != sizeof(val); ++i)
val = val * 256 + hash[i];
*phash = val >> (64 - diary->mask_bits);
}
|
18c357c1b5a7c326246c61e59d6a1a7de09a2e19
|
38cadc0ea0c82b07ab67bf0d471ef560da81d827
|
/lab 6/ComputeShaders2/ComputeShaders2/framework/traceRay.h
|
2338ad36ea94ad23d6c8d50f72437441f7c3c36b
|
[] |
no_license
|
ThomasMGilman/ETGG-4804
|
fea022fc0f06a25d6ccd02db8d5aa7419e8f815f
|
f0f455b7cbfe9de0cbd7d71be729c4aad8be8e5d
|
refs/heads/master
| 2022-07-10T01:19:44.270304
| 2020-05-19T20:41:03
| 2020-05-19T20:41:03
| 204,701,861
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,812
|
h
|
traceRay.h
|
//Thomas Gilman
//Jim Hudson
//ETGG 4804_1
//Optomization Techniques
//3rd September, 2019
#pragma once
#include "Scene.h"
//s : ray start
//v : ray direction
//N : normal
//ip : intersection point
void traceSpheres(Scene& scene, vec3& s, vec3& v, vec3& ip, vec3& N, vec3& color, float& closestT, bool& inter)
{
unsigned ci=(unsigned)-1;
//go through the list of spheres in the scene
//and determine if the viewer is intersecting the object
for(unsigned i=0;i<scene.spheres.size();++i){
//q = rayStart - sphereCenter
//q * q - r^2 + 2(q * v)t + t^2(v * v) = 0
vec3 q = s - scene.spheres[i].c;
float radius = scene.spheres[i].r;
float A = dot(v, v);
float B = 2 * dot(q, v);
float C = dot(q, q) - (radius * radius);
float discriminant = (B * B) - (4 * A * C);
if (discriminant >= 0) //if the discriminant is less than zero, there is no intersection
{
float sqrtDiscrim = sqrt(discriminant);
float denom = 2 * A;
//use Quadratic Formula to check if a spheres t's are closer and update closestT if they are
float t1 = (-B + sqrtDiscrim) / denom;
float t2 = (-B - sqrtDiscrim) / denom;
if (t1 < 0 && t2 >= 0) //t2 is closer than ClosestT
{
if (closestT > t2)
{
closestT = t2;
ci = i;
}
}
else if (t1 >= 0 && t2 < 0) //t1 is closer than ClosestT
{
if (closestT > t1)
{
closestT = t1;
ci = i;
}
}
else if (t1 >= 0 && t2 >= 0) //one of the t's is closer than ClosestT
{
float minT = fminf(t1, t2);
if (closestT > minT)
{
closestT = minT;
ci = i;
}
}
}
}
if( ci == (unsigned)-1 ){
if (!inter) //already true for another object
inter = false;
return;
}
else
{
ip = s + closestT * v; //intersection point
N = normalize(ip - scene.spheres[ci].c); //Normal at intersection point
color = scene.spheres[ci].color;
inter = true;
}
}
void traceTriangles(Scene& scene, vec3& s, vec3& v, vec3& ip, vec3& N,
vec3& color, float& closestT, bool& inter)
{
unsigned ti = (unsigned)-1; //triangle intersection
Mesh *cm = nullptr; //closest mesh to draw pointer
//check meshes for closest triangle
for(auto& M : scene.meshes ){
for(unsigned i=0;i<M.triangles.size();++i){
Triangle& T = M.triangles[i];
vec3 p = T.p[0];
vec3 q = T.p[1];
vec3 r = T.p[2];
vec3 N = cross((q-r), (r-p)); //Triangles Normal
float D = -dot(N, p); //Distance of plane from origin
float denominator = dot(N, v);
//does the ray intersect the triangle
//No intersection if denominator is zero
if (denominator != 0)
{
float t = -(D + dot(N, s)) / denominator;
if (t >= 0)
{
//std::cout << "got intersection: " << t << std::endl;
if (closestT > t)
{
vec3 currentIP = s + (t*v); //intersection point
float sumQi = 0;
for (int i = 0; i < T.e->len(); i++) //make sure ip is intersecting the triangle
{
vec3 qi = cross(T.e[i], (currentIP - T.p[i]));
sumQi += qi.magnitude();
}
float A = sumQi * T.oneOverTwiceArea;
if (A <= 1.001)
{
ip = currentIP;
closestT = t;
ti = i;
cm = &M;
}
}
}
}
}
}
if ( cm == nullptr || ti == (unsigned)-1) { //no intersection
if(!inter) //already true for another object
inter = false;
return;
}
else
{
Triangle& T = cm->triangles[ti]; //get triangle to draw from closest mesh
N = T.N;
color = cm->color;
inter = true;
}
}
bool traceRay(Scene& scene, vec3& s, vec3& v, vec3& ip, vec3& N, vec3& color)
{
float closestT = 1E99;
bool inter;
traceSpheres(scene,s,v,ip,N,color,closestT,inter);
traceTriangles(scene,s,v,ip,N,color,closestT,inter);
return inter;
}
|
54bcef2e03edd6d1482c8ea7427703d095fbe71a
|
2beb738ff5ca7f8d851fc5dda65ca6d442cfd9cd
|
/char_arrays_pointers/main.cpp
|
d3a19ea87de2f9e6244dbaa1b61ec9f78b0b92f6
|
[] |
no_license
|
TomK111/CPPTutorialForBeginners
|
1f6ee4d4ff01a04c230380f998026b6c52f04984
|
52b99dc1116bae55c8666c0b9699818b56fb840e
|
refs/heads/master
| 2023-03-24T00:35:26.024901
| 2021-03-07T23:47:27
| 2021-03-07T23:47:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 828
|
cpp
|
main.cpp
|
#include <iostream>
int main() {
char first_name[] = "Tomislav";
std::cout << first_name << std::endl;
for(int i = 0; i < sizeof(first_name); i++){
std::cout << i << ": " << first_name[i] << std::endl;
}
int j = 0;
while(true) {
if(first_name[j] == 0) {
break;
}
std::cout << first_name[j] << std::flush;
j++;
}
std::cout << std::endl;
std::cout << std::endl;
char last_name[] = "Kraljic";
std::cout << last_name << std::endl;
for(int i = 0; i < sizeof(last_name); i++) {
std::cout << i << ": " << last_name[i] << std::endl;
}
int k = 0;
while(true) {
if(last_name[k] == 0) {
break;
}
std::cout << last_name[k] << std::flush;
k++;
}
return 0;
}
|
d431201a96fd6a1281dec01c9959262f24e96631
|
eecd5508e9d16cc02bc8f9f7c0339aae5de2261c
|
/src/common/common.h
|
a7a195c8305a019c94b72d56f075a958a74bf615
|
[] |
no_license
|
sahwar/cyan
|
238d52286652c47c8e4cd8ce153cf91c6f2bf168
|
32cfee188255108d523711940e9131ad4b7f7389
|
refs/heads/master
| 2020-04-14T05:32:08.774661
| 2018-12-31T05:01:24
| 2018-12-31T05:01:24
| 163,662,974
| 1
| 0
| null | 2018-12-31T11:18:54
| 2018-12-31T11:18:54
| null |
UTF-8
|
C++
| false
| false
| 9,227
|
h
|
common.h
|
/*
# Copyright Ole-André Rodlie.
#
# ole.andre.rodlie@gmail.com
#
# This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and / or redistribute the software under the terms of the CeCILL
# license as circulated by CEA, CNRS and INRIA at the following URL
# "https://www.cecill.info".
#
# As a counterpart to the access to the source code and rights to
# modify and redistribute granted by the license, users are provided only
# with a limited warranty and the software's author, the holder of the
# economic rights and the subsequent licensors have only limited
# liability.
#
# In this respect, the user's attention is drawn to the associated risks
# with loading, using, modifying and / or developing or reproducing the
# software by the user in light of its specific status of free software,
# that can mean that it is complicated to manipulate, and that also
# so that it is for developers and experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to test and test the software's suitability
# Requirements in the conditions of their systems
# data to be ensured and, more generally, to use and operate
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL license and that you accept its terms.
*/
#ifndef COMMON_H
#define COMMON_H
#include <QObject>
#include <QMap>
#include <QDateTime>
#include <QMenu>
#include <list>
#include <lcms2.h>
#include <Magick++.h>
#ifdef WITH_FFMPEG
extern "C" {
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libavdevice/avdevice.h>
#include <libswscale/swscale.h>
}
#endif
#include "tileitem.h"
#define CYAN_PROJECT_VERSION 1.0
#define CYAN_LAYER_VERSION 1.0
#define CYAN_PROJECT "cyan-project"
#define CYAN_LAYER "cyan-layer"
#define CYAN_LAYER_VISIBILITY "cyan-visibility"
#define CYAN_LAYER_OPACITY "cyan-opacity"
#define CYAN_LAYER_COMPOSE "cyan-compose"
#define CYAN_LAYER_X "cyan-layer-x"
#define CYAN_LAYER_Y "cyan-layer-y"
class Common: public QObject
{
Q_OBJECT
public:
enum MoveLayer {
MoveLayerUp,
MoveLayerDown,
MoveLayerLeft,
MoveLayerRight
};
enum ICCTag {
ICCDescription,
ICCManufacturer,
ICCModel,
ICCCopyright
};
enum Colorspace
{
NoColorspace,
RGBColorspace,
CMYKColorspace,
GRAYColorspace
};
enum newDialogType
{
newImageDialogType,
newLayerDialogType
};
enum RenderingIntent
{
UndefinedRenderingIntent,
SaturationRenderingIntent,
PerceptualRenderingIntent,
AbsoluteRenderingIntent,
RelativeRenderingIntent
};
struct Tile
{
TileItem *rect;
};
struct Layer
{
Magick::Image image;
QMap<int, Common::Layer> layers;
Magick::CompositeOperator composite = Magick::OverCompositeOp;
QSize pos = QSize(0, 0);
bool visible = true;
double opacity = 1.0;
QString label = QObject::tr("New Layer");
};
struct Canvas
{
Magick::Image image;
QMap<int, Common::Layer> layers;
QString error;
QString warning;
QString label = QObject::tr("New Image");
QMap<int, Common::Tile> tiles;
QSize tileSize;
QColor brushColor;
bool brushAA = true;
Magick::LineCap brushLineCap = Magick::RoundCap;
Magick::LineJoin brushLineJoin = Magick::MiterJoin;
QString timestamp;
Magick::Blob profile;
};
Common(QObject *parent = nullptr);
static QString timestamp();
static QMap<Magick::CompositeOperator, QString> compositeModes();
static Magick::CompositeOperator compositeModeFromString(const QString &name);
static Magick::Image compLayers(Magick::Image canvas,
QMap<int, Common::Layer> layers,
Magick::Geometry crop = Magick::Geometry());
static const QString canvasWindowTitle(Magick::Image image);
static int getDiskResource();
static void setDiskResource(int gib);
static int getMemoryResource();
static void setMemoryResource(int gib);
static void setThreadResources(int thread);
static bool writeCanvas(Common::Canvas canvas,
const QString &filename,
Magick::CompressionType compress = Magick::LZMACompression);
static Common::Canvas readCanvas(const QString &filename);
static Magick::Image renderCanvasToImage(Common::Canvas canvas);
static bool renderCanvasToFile(Common::Canvas canvas,
const QString &filename,
Magick::CompressionType compress = Magick::NoCompression,
QMap<QString, QString> attr = QMap<QString, QString>(),
QMap<QString, QString> arti = QMap<QString, QString>());
static bool isValidCanvas(const QString &filename);
static bool isValidImage(const QString &filename);
static int hasLayers(const QString &filename);
static Common::Canvas readImage(const QString &filename);
static Magick::Image convertColorspace(Magick::Image image,
Magick::Blob input,
Magick::Blob output,
Magick::RenderingIntent intent = Magick::PerceptualIntent,
bool blackpoint = true);
static Magick::Image convertColorspace(Magick::Image image,
const QString &input,
const QString &output,
Magick::RenderingIntent intent = Magick::PerceptualIntent,
bool blackpoint = true);
static Magick::Image convertColorspace(Magick::Image image,
Magick::Blob input,
const QString &output,
Magick::RenderingIntent intent = Magick::PerceptualIntent,
bool blackpoint = true);
static Magick::Image convertColorspace(Magick::Image image,
const QString &input,
Magick::Blob output,
Magick::RenderingIntent intent = Magick::PerceptualIntent,
bool blackpoint = true);
static QStringList getColorProfilesPath();
static QMap<QString, QString> getColorProfiles(Magick::ColorspaceType colorspace);
static Magick::ColorspaceType getProfileColorspace(const QString &filename);
static Magick::ColorspaceType getProfileColorspace(cmsHPROFILE profile);
static const QString getProfileTag(const QString filename,
Common::ICCTag tag = Common::ICCDescription);
static const QString getProfileTag(cmsHPROFILE profile,
Common::ICCTag tag = Common::ICCDescription);
static const QString supportedWriteFormats();
static const QString supportedReadFormats();
static int supportedQuantumDepth();
static bool supportsJpeg();
static bool supportsPng();
static bool supportsTiff();
static bool supportsLcms();
static bool supportsHdri();
static bool supportsOpenMP();
static bool supportsBzlib();
static bool supportsCairo();
static bool supportsFontConfig();
static bool supportsFreeType();
static bool supportsJP2();
static bool supportsLzma();
static bool supportsOpenExr();
static bool supportsPangoCairo();
static bool supportsRaw();
static bool supportsRsvg();
static bool supportsWebp();
static bool supportsXml();
static bool supportsZlib();
static bool supportsJng();
static const QString humanFileSize(float num,
bool mp = false,
bool are = false);
/*void populateColorProfileMenu(QMenu *menu,
Magick::ColorspaceType colorspace);
void setDefaultColorProfileFromFilename(QMenu *menu,
const QString &filename);
void setDefaultColorProfileFromTitle(QMenu *menu,
const QString &title);
Magick::Blob selectedDefaultColorProfileData(QMenu *menu);
const QString selectedDefaultColorProfile(QMenu *menu);
signals:
void errorMessage(const QString &message);
void warningMessage(const QString &message);*/
#ifdef WITH_FFMPEG
static QByteArray getEmbeddedCoverArt(const QString &filename);
static int getVideoMaxFrames(const QString &filename);
static Magick::Image getVideoFrame(const QString &filename,
int frame = 0);
#endif
};
#endif // COMMON_H
|
6b211ecb190761328b2419f00b90285bf2f76b74
|
39028070ff3b61fb28d0d2bd88cfa01e8b861cf8
|
/code/flist_messenger/flist_global.h
|
b808947d88bede23b382331c00a34aa8d8d9ac86
|
[] |
no_license
|
kythyria/flist-messenger
|
8e750ba7b1f331e92656a231348ab29dd59fa34c
|
ac9fd1fc938771fd41b75c44563ed21567458e4c
|
refs/heads/master
| 2021-01-16T21:08:56.815279
| 2018-05-08T02:30:03
| 2018-05-08T02:30:03
| 20,154,945
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,259
|
h
|
flist_global.h
|
#ifndef FLIST_GLOBAL_H
#define FLIST_GLOBAL_H
#include <QNetworkAccessManager>
#include "flist_api.h"
class BBCodeParser;
class FSettings;
extern QNetworkAccessManager *networkaccessmanager;
extern BBCodeParser *bbcodeparser;
extern FHttpApi::Endpoint *fapi;
extern FSettings *settings;
void debugMessage(QString str);
void debugMessage(std::string str);
void debugMessage(const char *str);
void globalInit();
void globalQuit();
bool is_broken_escaped_apos(std::string const &data, std::string::size_type n);
void fix_broken_escaped_apos (std::string &data);
QString escapeFileName(QString infilename);
QString htmlToPlainText(QString input);
// Centre a window on the screen it's mostly on. No idea what happens if
// the window is not on any screen.
void centerOnScreen(QWidget *widge);
#define QSL(text) QStringLiteral(text)
#define QSLE QStringLiteral("")
#define FLIST_NAME "F-List Messenger [Beta]"
#define FLIST_VERSIONNUM "0.10.0." GIT_HASH
#define FLIST_PRETTYVERSION "0.10.0." GIT_REV " (commit " GIT_HASH ")"
#define FLIST_SHORTVERSION "0.10.0." GIT_REV
#define FLIST_VERSION FLIST_NAME " " FLIST_SHORTVERSION
#define FLIST_CLIENTID "F-List Desktop Client"
#define FLIST_CHAT_SERVER "wss://chat.f-list.net:9799/"
#endif // FLIST_GLOBAL_H
|
e3d9b2f28c6ffb5b666a8d0a62e6aca20428fa64
|
767419ca9e6a899d84db512e165c07c5842b6b27
|
/aurobotservers/trunk/libs/urob4/uimgpushtest.h
|
d5bfd40ab79724396d7f53bb65ad46240f42a967
|
[] |
no_license
|
savnik/LaserNavigation
|
3bf7a95519456a96b34488cd821d4da4bee3ceed
|
614fce06425c79e1d7e783aad4bbc97479798a7c
|
refs/heads/master
| 2021-01-16T20:55:33.441230
| 2014-06-26T21:55:19
| 2014-06-26T21:55:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,599
|
h
|
uimgpushtest.h
|
/***************************************************************************
* Copyright (C) 2004 by Christian Andersen *
* jca@oersted.dtu.dk *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef UIMGPUSHTEST_H
#define UIMGPUSHTEST_H
#include <ugen4/uimage2.h>
//#include <ugen4/urawimage.h>
#include "uimgsockserv.h"
#include "ucomcam.h"
#include "usockclient.h"
/**
Test for image push speed
@author Christian Andersen
*/
class UImgSockServPushTestConn : public UImgSockServConn
{
public:
/**
alled when new (possibly partial) message is received */
virtual void gotNewMessage(unsigned char * message, int length);
};
/////////////////////////////////////////////////////
/**
This is ... */
class UImgSockServPushTest : public UImgSockServ
{
public:
UImgSockServPushTest();
/**
Sets up pointers to client structures */
void initialize();
public:
UImgSockServPushTestConn * clients[MAX_CLIENTS_SERVED];
bool finished;
};
////////////////////////////////////////////////////////////
/**
Image client function */
class UImgClientTest : public USockClient
{
public:
/**
Constructor */
UImgClientTest();
virtual ~UImgClientTest();
/**
Send message block, but first log, what is transmitted. */
bool blockSend(const char * buffer, int length);
/**
Request camera time */
bool sendTimeRequest();
/**
Request camera information - such as device number,
frame speed, device name and frame size.
Returns true if send. */
bool sendCameraInfoRequest(bool allCams);
/**
Request camara parameter info, such as focus length,
radial error parameters and head point.
Returns true if send. */
bool sendCameraParameterRequest();
/**
Request a image metadata to be taken with default camera parameters.
NB! actual image is not send, but will have to be requested
separately. */
bool sendImageMetaRequest(int sourceNum);
/**
Send request to capture a new image, with or without
radial error removed.
Returns true if send. */
bool sendImageCaptureRequest(bool removeRadialError,
int imageFormat);
/**
Request image, either packed or unpacked.
Source number is image source at camera server.
Destination is saved until image is retrived.
If line number != -1, then just the specified line is send.
If format (color) is -1 then the default format is used
as set by tryColorFormat parameter.
Format can be 1 = YUV, 2 = RGB or 3 = BW.
Returns true if send. */
bool sendGetImage(int sourceNum,
unsigned int device,
bool tryPacked,
int line = -1,
int format = -1);
/**
Request new camera settings,
as defined in UComCam structure.
Returns true if send. */
bool sendNewCameraSettings2(UComCam * cs);
/**
Request that camera settings are changed to this
device ('/dev/videoX' with X = 0..5),
Width (w) and height (h) normally from 160x120 to 640x480.
(0,0) means no change. <br>
Frames per seconf (fps) normally 5, 10, 15 or 30. <br>
fps = -1 (0xff) means no change. <br>
Image number is camera serial number will be set to this number.<br>
Relative camera position on robot is used when reporting
estimated single camera positions of e.g. barchart position.
The position is set if 'newPosition' is true. <br>
The rotation is set if 'newRotation' is true. <br>
imNum = -1 means no change. <br>
Returns true if send. */
bool sendNewCameraSettings(int dev, int w, int h,
int fps, long imNum,
bool repeatNewImages,
bool newPosition,
UPosition newPos,
bool newRotation,
URotation newRot,
bool ensureOpen);
/**
Send specific camera settings.
Radial error parameters K1 must be larger than 1e-12 and
parameter K2 must be larger than 1e-15.
Focus length with 2 decomals in pixels.
headX center point in pixels.
headY center point in pixels. */
bool sendNewCameraParameters(
const float radialK1,
const float radialK2,
const float focalLength,
const float headX,
const float headY);
/**
Send camera calibration request for estimation of
radial error parameters */
bool sendCameraCalibrateRequest(
bool analyzeImage,
int imageSource,
bool clearAllData,
bool clearSpecificData,
float blockSize,
bool findCameraParams,
bool alsoFocalLength,
bool alsoK1, bool alsoK2,
unsigned long setsToUse,
bool extraImages);
/**
Send request for analyzing current image for barcode data.
Barcode frame size must be (frameSize), and each block is a
'blockSize' cm square. booleand flag indicates different
calculation and debugging options.
Returns true if send. */
bool sendBarcodeExecute(int sourceImage,
bool findCode,
bool extraImages,
bool nearGMK,
bool findPosition, bool findRotation,
bool findChartPosition,
bool clearOldData, bool findCameraParameters,
int frameSize, float blockSize, int codeBlockFactor,
int maxCodesToLookFor,
float chartHeight, // height of barcode center for cam calib
unsigned char specificCodeLng,
int specificCode[]);
/**
Send request to close device.
Returns true if send. */
bool sendCameraClose();
/**
Send request to be master for controlling this camera */
bool sendCameraMaster();
/**
Send request for pan-tilt position and range for this camera */
bool sendPantiltInfoRequest();
/**
Request a pan-tilt camera to move to a desired position */
bool sendPantiltPosRequest(
bool reset,
bool relative,
int pan, int tilt);
protected:
/**
Decode this time message */
bool decodeTimeMsg(unsigned char * msg);
/**
Decode message with camera info - like image size and
device name.
Returns true if no errors were found. */
bool decodeCameraInfoMsg(unsigned char * msg);
/**
Full camera device state message (replaces first version)
Returns true if no errors were found. */
bool decodeCameraInfoMsg2(unsigned char * msg);
/**
Decode message with camera parameters - like focus length and
radial error parameters.
Returns true if no errors were found. */
bool decodeCameraParamMsg(unsigned char * msg);
/**
Decode received image meta data */
bool decodeImageMetaData(unsigned char * msg);
/**
Decode message with image pixel data (packed or unpacked)
returns true if no format error were found.
The full message consist of several messages of this type.
The last message is marked, and could trigger further action. */
bool decodeImageData(unsigned char * msg);
/**
Called by receive thread every time some bytes have been received.
There is no garantee that data is separated at a message boundary. */
void processMessage(unsigned char * data, int length);
/**
Decode a received message.
Returns number of bytes used. */
int decodeMessages();
/**
Decode done message, that are the default
message, if no other data are returned.
This message may include a string. if so, then this is logged.
Returns true. */
bool decodeDone(unsigned char * msg);
/**
Decode message with barcode code.
Returns true if decoded OK. */
bool decodeBarcodeCode(unsigned char * msg);
/**
Decode message with pan-tilt support and position info.
Returns true if message is valid */
bool decodePantiltPosition(unsigned char * msg);
/**
Called when image meta data is updated */
virtual void imageMetaUpdated(int imageSlot);
/**
Called when image is updated.
if only one row, then row specified. if full image, then
row is -1.
If 'isBW' is true, then only Y channel is used (U,V is 128).
*/
virtual void imageUpdated(unsigned int serial,
int source,
int row, bool isBW);
/**
Called, when camera information is updated */
virtual void cameraDataUpdated(int device);
/**
Barcode data updated */
//virtual void barcodeDataUpdated(int codeNumber);
/**
Version or server time updated */
virtual void timeUpdated() {;};
/**
Called when something is to be displayed or logged.
if not handled by virtual function, then
messages are just printed to console. */
virtual void sInfo(const char * message, int type);
public:
/**
Received parameters */
/** server time (set when requested only) */
UTime timeServ;
/** server version major (set on connect) */
int formatMajor;
/** server version major (set on connect) */
int formatMinor;
//
// image format
// bool tryPacked;
/** This is ... */
int tryColorFormat;
/** requested image data */
bool reqOutstanding;
int reqMessageSerial;
UTime reqTime;
/** Timing test - time for received and unpacked */
UTime recvTime;
/** Timing test - time start of test */
UTime startTime;
/** Timing test sime of reception of first image meta */
UTime startTimeClient;
/**
Image count */
int imagesReceived;
// partially received image
UImage640 * rgbImage; // unpacked image data
URawImage * rawImage; // image in YUV:4:2:0 format
// received image data
bool dataBuffersCreated;
// debug and control
bool verboseMessages;
//
UComCam ccam;
protected:
bool receiving;
/** buffer for incomplete messages plus new full buffer of data */
unsigned char message[MAX_MESSAGE_LENGTH_FROM_CAM * 2];
/** bytes in buffer */
int messageCnt;
/** message serial number */
int serial;
/** Current device number for info-messages etc.
i.e. when a message is send or received without
explicit device number. */
int selectedDeviceNumber;
};
#endif
|
73777d00c6157ae08c8e02c3f902737b794139d4
|
b6607ecc11e389cc56ee4966293de9e2e0aca491
|
/acmp.ru/101...200/115/115.cpp
|
b0adbd7c0579b6f764fd28e174fb8427115ac860
|
[] |
no_license
|
BekzhanKassenov/olymp
|
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
|
e3013095a4f88fb614abb8ac9ba532c5e955a32e
|
refs/heads/master
| 2022-09-21T10:07:10.232514
| 2021-11-01T16:40:24
| 2021-11-01T16:40:24
| 39,900,971
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 898
|
cpp
|
115.cpp
|
#include <iostream>
#include <cstdio>
using namespace std;
int a[110][110], sum[110][110], n, m;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &a[i][j]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + a[i][j];
int ans = -1000000000;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
for (int k = i; k <= n; k++) {
for (int l = j; l <= m; l++) {
int s = sum[k][l] - sum[i - 1][l] - sum[k][j - 1] + sum[i - 1][j - 1];
ans = max(ans, s);
}
}
}
}
printf("%d", ans);
return 0;
}
|
a9d8834c2856876247eb1d9d068e6d7400ea0ee2
|
6523953eeacb926cee0089dcafab1d16c24bd7e1
|
/InteractiveOpenGLDemo/Vertex.h
|
6761568f18af5ce7d5e0f629d9d670c471fc1399
|
[] |
no_license
|
KepAmun/InteractiveOpenGLDemo
|
93956eac07561341c94c6ab39371785c619e89a2
|
3ffa2c549da66402261972c228dc08ef3ba0deeb
|
refs/heads/master
| 2021-01-23T10:00:32.772642
| 2013-03-17T21:21:16
| 2013-03-17T21:21:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
h
|
Vertex.h
|
#ifndef VERTEX_H_
#define VERTEX_H_
using namespace std;
class Vertex
{
private:
float m_coord3fv[3];
float m_texCoord2fv[2];
public:
Vertex();
Vertex(float* fv);
Vertex(double x, double y, double z);
void SetCoords(double x, double y, double z);
void SetTexCoord(float s, float t);
float* GetCoord3fv();
float* GetTexCoord2fv();
float GetX();
float GetY();
float GetZ();
void Offset(float dx, float dy, float dz);
};
#endif /* VERTEX_H_ */
|
01949bcb75f9fe53414199b2766a77a279219319
|
f9a8e812a0f8e8ddcae5a7da6576f376d5b4c100
|
/src/tools/StringTools.cpp
|
fe3600fa97449979ab0a731d29c3edcb1ed60270
|
[
"MIT"
] |
permissive
|
CapRat/APAL
|
d44bfbee74540e812ccd63901d47de401fefb672
|
a08f4bc6ee6299e8e370ef99750262ad23c87d58
|
refs/heads/master
| 2022-12-13T18:52:11.512432
| 2020-08-19T11:24:40
| 2020-08-19T11:24:40
| 290,733,218
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 943
|
cpp
|
StringTools.cpp
|
#include <tools/StringTools.hpp>
std::string
APAL::replaceInString(std::string strToChange,
const std::string itemToReplace,
const std::string substitute)
{
while (strToChange.find(itemToReplace) != std::string::npos)
strToChange.replace(strToChange.find(itemToReplace), 1, substitute);
return strToChange;
}
/*
*Get File Name from a Path with or without extension
*/
std::string
APAL::getFileName(std::string filePath, bool withExtension, char seperator)
{
// Get last dot position
std::size_t dotPos = filePath.rfind('.');
std::size_t sepPos = filePath.rfind(seperator);
if (sepPos != std::string::npos) {
return filePath.substr(sepPos + 1,
(!withExtension && dotPos != std::string::npos
? dotPos
: filePath.size()) -
sepPos - 1);
}
return filePath;
}
|
c1589fb41288787fcaea27a4ddcfb634695e8f48
|
56fe919cc075537a5a2d310e9a8c1cb0cee0f5bd
|
/nenequest/headers/randomCloud.hpp
|
526f4079ae788e8a78d5241d6c81f9a79a68f524
|
[
"MIT"
] |
permissive
|
codingwatching/nene-quest
|
e89b2e3fd3a8627c2caf1b18135a07537de16931
|
c3c8602d12ebdc25b667c195b7a454748027f3b6
|
refs/heads/master
| 2023-04-06T02:44:35.273202
| 2019-06-06T16:10:30
| 2019-06-06T16:10:30
| 411,963,234
| 2
| 0
|
MIT
| 2021-09-30T07:19:56
| 2021-09-30T07:19:55
| null |
UTF-8
|
C++
| false
| false
| 1,329
|
hpp
|
randomCloud.hpp
|
#ifndef RANDOMCLOUD_HPP_INCLUDED
#define RANDOMCLOUD_HPP_INCLUDED
#include <stdlib.h>
#include <time.h>
#include <SFML/Graphics.hpp>
#include <list>
#include "randomShape.hpp"
class RandomCloud : public RandomShape {
private:
static const int MAX_WIDTH = 200;
static const int MAX_HEIGHT = 100;
static const int BORDER_SIZE_MIN = 30;
static const int BORDER_SIZE_MAX = 45;
static const int BORDER_NUMBER = 12;
static const int BORDER_VARI = 10;
static const int LIFETIME = 10;
sf::RectangleShape *cloudBody;
std::vector<sf::CircleShape *> cloudBorder;
sf::Clock clock;
bool alive = true;
public:
RandomCloud();
~RandomCloud();
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const {
target.draw(*(this->cloudBody));
for (sf::CircleShape *var : this->cloudBorder) {
target.draw(*var);
}
}
virtual void setPosition(float x, float y) {
this->setPosition(sf::Vector2f(x, y));
}
virtual void setPosition(sf::Vector2f v) {
this->cloudBody->setPosition(v);
for (sf::CircleShape *var : this->cloudBorder) {
var->setPosition(v);
}
}
void generateBorder();
void update();
bool isAlive();
void translate(float x, float y);
};
#endif
|
056ec7e8850a46825d9079e46df4acdc37240f94
|
0345b456d898e073672ac1faf75c9b7ba0edda9f
|
/Formulars/Course_Roll_Pitch/Course_Roll_Pitch.h
|
3623ea4d52b188051a66096ff0aa3a4789507ea0
|
[] |
no_license
|
ORI-us/Aristarchus
|
c35ffeeacdfd8e8733960952b46fbfbe51dfff52
|
f2a3ca5e937be4c7448ff66302bacf48e870bcca
|
refs/heads/master
| 2021-01-10T16:00:53.915013
| 2016-03-15T15:22:42
| 2016-03-15T15:22:42
| 53,856,476
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 685
|
h
|
Course_Roll_Pitch.h
|
#ifndef COURSE_ROLL_PITCH_H
#define COURSE_ROLL_PITCH_H
#include <QWidget>
#include <QGraphicsItem>
#include <QGraphicsDropShadowEffect>
#include "NMEA_Struct.h"
namespace Ui {
class Course_Roll_Pitch;
}
class Course_Roll_Pitch : public QWidget
{
Q_OBJECT
public:
explicit Course_Roll_Pitch(QWidget *parent = 0);
~Course_Roll_Pitch();
private:
Ui::Course_Roll_Pitch *ui;
QGraphicsPixmapItem *Course_Pointer, *Roll_Pointer, *Pitch_Pointer;
QGraphicsTextItem *Course_Text, *Roll_Text, *Pitch_Text;
QGraphicsColorizeEffect *Course_effect, *Roll_effect, *Pitch_effect;
public slots:
void Get_Data();
};
#endif // COURSE_ROLL_PITCH_H
|
566d9c715c7a352b51c78a56361ef592b965a351
|
e8c4e8c3e4385b5ce8acd310acc24fffd117443b
|
/Tree/BTreeNode.h
|
e79563540c7214e7bd29783c1f459f26bb621b89
|
[] |
no_license
|
DhivyaNarayanan/ADS
|
3605af05ec0f48e32e0b748b183f65061a2cdbe5
|
14dc69e48373921963eb1387a31cb7fb582da222
|
refs/heads/master
| 2021-01-10T17:06:56.539488
| 2015-12-22T20:13:02
| 2015-12-22T20:13:02
| 44,499,635
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 914
|
h
|
BTreeNode.h
|
#include"Interfaces04.h"
class BTreeNode : public IBTreeNode
{
int * keys; //array of keys
int max_keys; // num_keys - max no_ of keys in the node - always 5
int min_deg_t; // minimum degree of the node
IBTreeNode **children; //array of child pointers
int no_of_keys; // no of keys in the node
int no_of_child; // no of children in the node
bool leaf; // is the node is leaf or not
public:
BTreeNode(int num_keys, bool leaf1)
{
min_deg_t = ((num_keys)+1) / 2;
max_keys = num_keys;
leaf = leaf1;
keys = new int[max_keys];
children = new IBTreeNode *[max_keys + 1];
no_of_keys = 0;
no_of_child = 0;
}
~BTreeNode(){}
int getKey(int index);
void setKey(int index, int key);
int getKeySize();
void setKeySize(int size);
int getChildSize();
void setChildSize(int size);
IBTreeNode * getChild(int index);
void setChild(int index, IBTreeNode * child);
bool isLeaf();
};
|
8a27261c0f179a258100370dfdfe70668cd96b2f
|
e0366e6e4ed0efc707eafac0884c1c55de040b25
|
/20101229/Q1/main.cpp
|
18a3a20e44016e7604525e856c0e3604c1e91f2c
|
[] |
no_license
|
Vdragon/NTOU_C_programming_lab
|
baa3f775022966fa2b66c970c14066fb6f5db223
|
5c268e857818f716a967f98b7fb342102a31249b
|
refs/heads/master
| 2016-09-06T03:28:10.300639
| 2012-06-12T17:39:54
| 2012-06-12T17:39:54
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 7,047
|
cpp
|
main.cpp
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main()
{
restart:
//prompt array to put value
double inputValue[50];
//prompt n
short int inputNumber;
scanf("%hd", &inputNumber);
{//assign
//declare a counter for for loop
unsigned short int forLoopC;
//for n times read value
for(forLoopC = 0; forLoopC < inputNumber; forLoopC++)
{
scanf("%lf", &inputValue[forLoopC]);
}
}
{//output max, min
//declare maxCurrent = first num
double maxCurrent = inputValue[0];
//declare minCurrent = first num
double minCurrent = inputValue[0];
//declare counter for forLoop
unsigned short int forLoopC;
//for loop read & compare
for(forLoopC = 1; forLoopC < inputNumber; forLoopC++)
{
//if greater then maxcurrent
if(inputValue[forLoopC] > maxCurrent)
{
//assign it
maxCurrent = inputValue[forLoopC];
}
//if greater then mincurrent
if(inputValue[forLoopC] < minCurrent)
{
//assign it
minCurrent = inputValue[forLoopC];
}
}
//output
printf("程%.2lf\n", maxCurrent);
printf("程%.2lf\n", minCurrent);
}
{//output average
//declare sum
double sum = 0;
//declare counter for forLoop
unsigned short int forLoopC;
//for loop add
for(forLoopC = 0; forLoopC < inputNumber; forLoopC++)
{
//add to sum
sum = sum + inputValue[forLoopC];
}
//output
printf("キА计%.2lf\n", sum / inputNumber);
}
{//output渤计
//declare int array for known number initial with 0
double knownNum[50];
//declare array for knownNumberCount default -1
short int knownNumC[50];
{//assign
//counter for initial for loop
unsigned short int initLoopC;
//for loop to init
for(initLoopC = 0; initLoopC < 50; initLoopC++)
{
knownNumC[initLoopC] = -1;
}
}
//read knwon from array
{
//declare counter for forLoop
unsigned short int forLoopC;
//for loop find known
for(forLoopC = 0; forLoopC < inputNumber; forLoopC++)
{
//counter for reading known number
unsigned short int readLoopC;
//bool for found known num
bool foundKnown = false;
//read known loop
for(readLoopC = 0; knownNumC[readLoopC] != -1; readLoopC++)
{
//if found known
if(knownNum[readLoopC] == inputValue[forLoopC])
{
knownNumC[readLoopC]++;
foundKnown = true;
}
}
//if don't found
if(foundKnown == false)
{
//assign
knownNum[readLoopC] = inputValue[forLoopC];
//change counter
knownNumC[readLoopC] = 1;
}
}
}
//find the max known
//declare maxCount
unsigned short int maxCount = 0;
{
//declare counter for for loop
unsigned short int readLoopC;
//for loop for finding the max count
for(readLoopC = 0; knownNumC[readLoopC] != -1; readLoopC++)
{
//if found greater count
if(maxCount < knownNumC[readLoopC])
{
//assign it
maxCount = knownNumC[readLoopC];
}
}
}
{//output
printf("渤计");
//print the number if max Count equals
//declare counter for read count loop
unsigned short int readLoopC;
//for loop for read count
for(readLoopC = 0; knownNumC[readLoopC] != -1; readLoopC++)
{
//if count same
if(maxCount == knownNumC[readLoopC])
{
//print numKnown & tab
printf("%.2lf\t", knownNum[readLoopC]);
}
}
//last print new line
printf("\n");
}
}
{//
//pause
printf("q挡祘Αr穝秨﹍");
char pauseChar;
while((pauseChar = getch()) != 'q')
{
//restart
if(pauseChar == 'r')
{
system("cls");
goto restart;
}
}
}
return 0;
}
|
12379c513eb838d249bfab32867777a0a52df376
|
9114fc236743bbec1dd5733275ab8d5604c844fc
|
/iterator/stl_iterator.h
|
fb29b64e66be2d6265fdbf23bb38d68c5283f843
|
[] |
no_license
|
zhangyl927/miniSTL
|
2bbc51aa487cc32e92b935060966d18b0d32a2e5
|
e21e5ac83568eef02d502aa371a96dec57278dd0
|
refs/heads/master
| 2023-02-13T01:15:06.087447
| 2021-01-11T08:40:17
| 2021-01-11T08:40:17
| 324,707,281
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,100
|
h
|
stl_iterator.h
|
#ifndef __STL_ITERATOR_H
#define __STL_ITERATOR_H
#include <cstddef>
namespace stl_iterator
{
struct input_iterator_tag {};
struct output_iterator_tag {};
struct forward_iterator_tag : public input_iterator_tag {};
struct bidirectional_iterator_tag : public forward_iterator_tag {};
struct random_access_iterator_tag : public bidirectional_iterator_tag {};
template <class Category, class T, class Distance = ptrdiff_t,
class Pointer = T*, class Reference = T&>
struct iterator
{
using iterator_category = Category;
using value_type = T;
using difference_type = Distance;
using pointer = Pointer;
using reference = Reference;
};
template <class Iterator>
struct iterator_traits
{
using iterator_category = typename Iterator::iterator_category;
using value_type = typename Iterator::value_type;
using difference_type = typename Iterator::difference_type;
using pointer = typename Iterator::pointer;
using reference = typename Iterator::reference;
};
template <class T>
struct iterator_traits<T*>
{
using iterator_category = random_access_iterator_tag;
using value_type = T;
using difference_type = ptrdiff_t;
using pointer = T*;
using reference = T&;
};
template <class T>
struct iterator_traits<const T*>
{
using iterator_category = random_access_iterator_tag;
using value_type = T;
using difference_type = ptrdiff_t;
using pointer = T*;
using reference = T&;
};
// --------------------- distance --------------------
template <class InputIterator>
inline typename iterator_traits<InputIterator>::difference_type
__distance(InputIterator first, InputIterator last, input_iterator_tag)
{
typename iterator_traits<InputIterator>::difference_type n = 0;
while (first != last)
{
++first;
++n;
}
return n;
}
template <class InputIterator>
inline typename iterator_traits<InputIterator>::difference_type
__distance(InputIterator first, InputIterator last, random_access_iterator_tag)
{
return last-first;
}
template <class InputIterator>
inline typename iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last)
{
using category = typename iterator_traits<InputIterator>::iterator_category;
__distance(first, last, category());
}
// ------------------------- advance ---------------------------
template <class InputIterator, class Distance>
inline void __advance(InputIterator& it, Distance n, input_iterator_tag)
{
while (n--)
{
++it;
}
}
template <class BidirectionalIterator, class Distance>
inline void __advance(BidirectionalIterator& it, Distance n, bidirectional_iterator_tag)
{
if (n >= 0)
{
while (n--) ++it;
}
else
{
while (n++ < 0) --it;
}
}
template <class RandomAccessIterator, class Distance>
inline void __advance(RandomAccessIterator& it, Distance n, random_access_iterator_tag)
{
it += n;
}
template <class InputIterator, class Distance>
inline void advance(InputIterator& it, Distance n)
{
using category = typename iterator_traits<InputIterator>::iterator_category;
__advance(it, n, category());
}
}
#endif
|
4a18fcb2a15391027719c26bcffdb9517d026d01
|
83d0ef351e8b525b612575d8bb459e9f29ae3c48
|
/inlupp1_1_o_2/MazeEvolver.cpp
|
5a52e4910232e524e8b93e77201a552ebe563bcd
|
[] |
no_license
|
kattfisk/spelai
|
261f616c641dd4f9a3adec2d61479325965d7b1e
|
bb88e9069578e296c4c19a3f6f163260dea6148a
|
refs/heads/master
| 2020-12-02T19:20:56.057568
| 2017-07-05T14:48:55
| 2017-07-05T14:48:55
| 96,329,016
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,645
|
cpp
|
MazeEvolver.cpp
|
#include "MazeEvolver.h"
#include "Solver.h"
#include "SearchResult.h"
#include "MazeCreator.h"
#include "libraries\EvolutionaryAlgorithm\EALEvolutionaryAlgorithm.h"
#include <vector>
namespace
{
// Population settings
const int POPULATION_SIZE = 10;
// Selection settings
const int TOURNAMENT_PARTICIPANTS = 8;
const EALTournamentSelectorImp SELECTOR_IMPLEMENTATION(TOURNAMENT_PARTICIPANTS);
// Combination settings
const double COMBINATON_PROBABILITY(0.0);
const EALDualCombinatorImp COMBINATOR_IMPLEMENTATION;
// Mutation settings
const double MUTATION_PROBABILTY(0.15);
const EALResetMutatorImp MUTATOR_IMPLEMENTATION;
std::vector<bool> to_bool_vector(const EALGenome& genome)
{
const int GENOME_LENGTH = genome.getGeneCount();
std::vector<bool> retval(GENOME_LENGTH);
for (int i = 0; i < GENOME_LENGTH; ++i)
{
retval[i] = genome[i].getBoolean();
}
return retval;
}
}
MazeEvolver::MazeEvolver(Position maze_start_pos, Position maze_goal_pos, int maze_width, int maze_height, std::shared_ptr<Solver> maze_evaluator)
: MAZE_START_POS(maze_start_pos),
MAZE_GOAL_POS(maze_goal_pos),
MAZE_WIDTH(maze_width),
MAZE_HEIGHT(maze_height),
maze_evaluator(maze_evaluator),
GENOME_LENGTH((maze_width - 2)*(maze_height - 2) - 2), // Number of tiles that are not outer walls or start/goal
generations_passed(0)
{
const EALEvaluator EVALUATOR(EALMemberEvaluatorImp<MazeEvolver>(*this, &MazeEvolver::evaluate));
const EALSelector SELECTOR(SELECTOR_IMPLEMENTATION);
const EALCombinator COMBINATOR(COMBINATOR_IMPLEMENTATION);
const EALMutator MUTATOR(MUTATOR_IMPLEMENTATION);
EALBasicEvolverImp evolverImplementation(EVALUATOR, SELECTOR, COMBINATOR, MUTATOR, COMBINATON_PROBABILITY, MUTATION_PROBABILTY);
evolver = EALEvolver(evolverImplementation);
populate(POPULATION_SIZE);
update_most_fit();
}
void MazeEvolver::evolve(int generations)
{
for (int i = 0; i < generations; ++i)
{
evolver.evolve(population);
++generations_passed;
}
update_most_fit();
}
Maze MazeEvolver::get_best_solution() const
{
return MazeCreator::from_bool_vector(MAZE_WIDTH, MAZE_HEIGHT, MAZE_START_POS, MAZE_GOAL_POS, to_bool_vector(most_fit.getGenome()));
}
void MazeEvolver::populate(int individuals)
{
for (int i = 0; i < individuals; ++i)
{
EALGenome genome(GENOME_LENGTH);
genome.randomize();
population.addIndividual(EALIndividual(genome, evaluate(genome)));
}
}
double MazeEvolver::evaluate(const EALGenome& genome)
{
Maze solution(MazeCreator::from_bool_vector(MAZE_WIDTH, MAZE_HEIGHT, MAZE_START_POS, MAZE_GOAL_POS, to_bool_vector(genome)));
SearchResult result(maze_evaluator->solve(solution));
double fitness;
// Measures how difficult the maze was to solve
if (result.solved)
{
fitness = double(result.steps_to_find) / double(maze_evaluator->get_upper_bound(solution));
}
else
{
fitness = 0.0;
}
// Measures how close it was to being solveable
// Theoretical max steps through every tile except outer walls
const double MAX_DISTANCE_TO_GOAL = (MAZE_WIDTH - 2) * (MAZE_HEIGHT - 2);
fitness += 1.0 / double(result.distance_to_goal) - 1.0 / MAX_DISTANCE_TO_GOAL;
// Return value between 0.0 and 1.0
return fitness /= 2.0;
}
void MazeEvolver::update_most_fit()
{
const int INDIVIDUALS = population.getIndividualCount();
const double HIGHEST_FITNESS = population.getMaximumFitness();
for (int i = 0; i < INDIVIDUALS; ++i)
{
if (population[i].getFitness() == HIGHEST_FITNESS)
{
most_fit = population[i];
return;
}
}
}
|
9b1cb27f27d7a2182ea3d2d0222294d186203a32
|
83857373cf14478a9db0002c9c17e317401dfd03
|
/LC_686_RepeatedStringMatch/main.cpp
|
023eb9577157965998dc71751d64c55749ab8671
|
[] |
no_license
|
neoVincent/LeetCodePlayground
|
acdefed387158f4c53b9199498d9cd1c62b5e50e
|
994b80108fd6dac8b413c858f5182a0e80adbf7b
|
refs/heads/master
| 2021-06-11T03:37:46.534237
| 2019-10-03T00:28:16
| 2019-10-03T00:28:16
| 128,283,607
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 769
|
cpp
|
main.cpp
|
#include <QCoreApplication>
#include <string>
#include <iostream>
using namespace std;
int repeatedStringMatch(string A, string B) {
if (A.find(B) != string::npos) return 1;
//concate A with itself til A.size >= B.size
int counter = 1;
string a = A;
while(a.size() < B.size())
{
a.append(A);
counter++;
}
if(a.find(B) != string::npos)
{
cout << a.size() << endl;
return counter;
}
if (a.append(A).find(B) != string::npos) return counter +1;
return -1;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
string a1 ="abc";
string a2 ="cabcabca";
string a3 = "abcabcabc";
cout << a3.find(a2)<<endl;
repeatedStringMatch(a1,a2);
return a.exec();
}
|
4e803c10eedc2bac977c74f455b45c49d5eeaacc
|
0318ccfb1b8f6a34b362567d2e57475f4965cf47
|
/Homework 1/Reservation.cpp
|
3f9db3343332cb1344cf1b69a38f6dd11a60d314
|
[] |
no_license
|
CanAvsar/CS201Homeworks
|
b31f2233da9f7a7609b88387a6793f9f02998172
|
2ef8445403ee50ef7a7eb6e9ccc127a922791238
|
refs/heads/main
| 2023-07-02T21:42:36.480909
| 2021-08-06T21:09:08
| 2021-08-06T21:09:08
| 393,502,948
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 714
|
cpp
|
Reservation.cpp
|
// Reservation.cpp
// CS201 Homework 1: MovieBookingSystem
// March 2021
// Can Avşar
// 21902111
#include <stdio.h>
#include "Reservation.h"
Reservation::Reservation()
{
_movieID = 0;
_row = 0;
_col = 0;
_resCode = 0;
}
Reservation::Reservation(long movieID, int row, char col)
{
_movieID = movieID;
_row = row;
_col = col;
_resCode = 0;
}
Reservation::~Reservation()
{
}
void Reservation::setResCode(int resCode)
{
_resCode = resCode;
}
int Reservation::getResCode()
{
return _resCode;
}
int Reservation::getRowNo()
{
return _row;
}
char Reservation::getColNo()
{
return _col;
}
long Reservation::getResMovieID()
{
return _movieID;
}
|
dbdcff4b5634d64aff9afb45cd634c11fced3a6e
|
5fb4db792adc11020a08a863c3a3423aaca13eff
|
/week-01/day-3/variable_mutation/main.cpp
|
4587460f06eab7d64f8dba03b4b8779c2b8ba9f9
|
[] |
no_license
|
green-fox-academy/tamasmarkovics
|
b65472222f44596fa2df0466d7a88f0d860b011f
|
4c70ac6fc8afc1bafa91847e9d9aab5633db4688
|
refs/heads/master
| 2020-07-23T13:56:23.406168
| 2019-12-06T11:45:17
| 2019-12-06T11:45:17
| 207,581,732
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,345
|
cpp
|
main.cpp
|
#include <iostream>
#include <string>
#include <math.h>
int main(int argc, char* args[]) {
int a = 3;
// make the "a" variable's value bigger by 10
a+=10;
std::cout << a << std::endl;
int b = 100;
// make b smaller by 7
b-=7;
std::cout << b << std::endl;
int c = 44;
// please double c's value
c*=2;
std::cout << c << std::endl;
int d = 125;
// please divide by 5 d's value
d/=5;
std::cout << d << std::endl;
int e = 8;
// please cube of e's value
e*e;
std::cout << e << std::endl;
int f1 = 123;
int f2 = 345;
bool big=f1>f2;
// tell if f1 is bigger than f2 (print as a boolean)
std::cout<< big << std::endl;
int g1 = 350;
int g2 = 200;
// tell if the double of g2 is bigger than g1 (print as a boolean)
big=(g2*2)>g1;
std::cout<< big << std::endl;
int h = 135798745;
// tell if it has 11 as a divisor (print as a boolean)
if (h/11.0==h/11){
std::cout<< 1<<std::endl;
}else
{
std::cout<<0<<std::endl;
}
int i1 = 10;
int i2 = 3;
// tell if i1 is higher than i2 squared and smaller than i2 cubed (print as a boolean)
if (i1>pow(i2, 0.5)&&i1<pow(i2, 2)){
std::cout<< 1<<std::endl;
}else
{
std::cout<<0<<std::endl;
}
int j = 1521;
// tell if j is dividable by 3 or 5 (print as a boolean)
if ((j/3==j/3.0)||(j/5==j/5.0)){
std::cout<< 1<<std::endl;
}else
{
std::cout<<0<<std::endl;
}
std::cout<<std::endl;
int currentHours = 14;
int currentMinutes = 34;
int currentSeconds = 42;
// Write a program that prints the remaining seconds (as an integer) from a
// day if the current time is represented by the variables
int DayInSec=24*60*60;
int rem=DayInSec-currentHours*60*60-currentMinutes*60-currentSeconds;
std::cout<<rem<<std::endl;
// Write a program that stores 3 sides of a cuboid as variables (doubles)
// The program should write the surface area and volume of the cuboid like:
//
// Surface Area: 600
// Volume: 1000
float hei=10;
float dep=20;
float wid=50;
std::cout<<std::endl<<"Surface Area: "<< (hei*dep+hei*wid+wid*dep)*2<<std::endl;
std::cout<<"Surface Area: "<< hei*dep*wid <<std::endl;
return 0;
}
|
e696acb19b22cbd31d8d0538c3819c6e1f7134c2
|
c423990916490a0006eeaaccfc60c186d1f802a7
|
/concurrent-cpp/1-intro.cpp
|
3789f3ed857319e90c831f02faf2dd09093fcd96
|
[] |
no_license
|
idontknoooo/my-code
|
297aa931455596dafd0e1f046ecf7d793bd1938d
|
647b8c77db35e545f2fce735c0d887c2b93aaf1c
|
refs/heads/master
| 2018-10-09T21:56:06.634340
| 2018-09-05T03:45:42
| 2018-09-05T03:45:42
| 33,699,122
| 0
| 1
| null | 2018-03-04T20:08:31
| 2015-04-10T00:09:50
|
Python
|
UTF-8
|
C++
| false
| false
| 379
|
cpp
|
1-intro.cpp
|
#include <iostream>
#include <string>
#include <thread>
using namespace std;
void function_1() {
cout << "Beauty is only skin-deep" << endl;
}
int main() {
thread t1(function_1); // t1 starts running
//t1.join(); // main thread waits for t1 to finish
//t1.detach(); // t1 will freely on its own -- daemon process
if(t1.joinable())
t1.join();
return 0;
}
|
43b299878679d08a7a9be664554538e5de84e304
|
13a81310f102e1d065ce405f1896035d7c006c0b
|
/src/particle_filter.cpp
|
a2a22cee51716783ec70dce45c6ce60a0e82fdb9
|
[
"MIT"
] |
permissive
|
RobotGameFoundation/CarND-Kidnapped-Vehicle-Project
|
64461de599f4a9c175db54b5944cc99c832c43eb
|
0f524b25ff74e761363a58c9af4177671a7e9f7b
|
refs/heads/master
| 2022-07-20T06:38:52.948444
| 2020-05-20T09:18:41
| 2020-05-20T09:18:41
| 265,512,890
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,881
|
cpp
|
particle_filter.cpp
|
/**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
using std::normal_distribution;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
std::default_random_engine gen;
num_particles = 100; // TODO: Set the number of particles
normal_distribution<double> dist_x(x, std[0]);
normal_distribution<double> dist_y(y, std[1]);
normal_distribution<double> dist_theta(theta, std[2]);
for (int i = 0; i < num_particles; i++) {
double sample_x = dist_x(gen);
double sample_y = dist_y(gen);
double sampel_theta = dist_theta(gen);
Particle particle;
particle.id = i;
particle.x = sample_x;
particle.y = sample_y;
particle.theta = sampel_theta;
particle.weight = 1;
weights.push_back(particle.weight);
particles.push_back(particle);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
std::default_random_engine gen;
// calculate particle x position will be inf if not limit yaw_rate num
if (fabs(yaw_rate)<0.0001) {
yaw_rate = 0.0001;
}
for (auto& particle : particles) {
double o_theta = particle.theta;
particle.x += velocity/yaw_rate*(sin(o_theta+ yaw_rate*delta_t)-sin(o_theta));
particle.y += velocity/yaw_rate*(cos(o_theta)-cos(o_theta+yaw_rate*delta_t));
particle.theta += yaw_rate*delta_t;
normal_distribution<double> dist_x(particle.x, std_pos[0]);
normal_distribution<double> dist_y(particle.y, std_pos[1]);
normal_distribution<double> dist_theta(particle.theta, std_pos[2]);
particle.x = dist_x(gen);
particle.y = dist_y(gen);
particle.theta = dist_theta(gen);
//std::cout << particle.x << std::endl;
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted,
std::vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
for (auto& obj : observations) {
double min_d = HUGE_VAL;
for(auto& predict: predicted) {
//double distance = sqrt(pow(predicted.x-obj.x,2) + pow(predicted.y -obj.y,2));
double distance = dist(obj.x, obj.y, predict.x, predict.y);
if (distance < min_d) {
min_d = distance;
obj.id = predict.id;
}
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
double sig_x = std_landmark[0];
double sig_y = std_landmark[1];
double weight_sum = 0;
for (auto& particle: particles) {
double x = particle.x;
double y = particle.y;
double theta = particle.theta;
vector<LandmarkObs> predicted;
for (auto& landmark: map_landmarks.landmark_list) {
int id = landmark.id_i;
double x_landmark = landmark.x_f;
double y_landmark = landmark.y_f;
if (dist(x,y,x_landmark,y_landmark) < sensor_range) {
LandmarkObs obs;
obs.x = x_landmark;
obs.y = y_landmark;
obs.id = id;
predicted.push_back(obs);
}
}
vector<LandmarkObs> trans_obs;
for (auto& obs: observations) {
double x_obs = obs.x;
double y_obs = obs.y;
// transform to map x coordinate
double x_map;
x_map = x + (cos(theta) * x_obs) - (sin(theta) * y_obs);
// transform to map y coordinate
double y_map;
y_map = y + (sin(theta) * x_obs) + (cos(theta) * y_obs);
LandmarkObs p;
p.x = x_map;
p.y = y_map;
trans_obs.push_back(p);
}
dataAssociation(predicted,trans_obs);
particle.weight = 1.0;
for (auto& obs: trans_obs) {
double x_obs = obs.x;
double y_obs = obs.y;
int id_obs = obs.id;
for (auto& pred: predicted) {
double x_pred = pred.x;
double y_pred = pred.y;
int id_pred = pred.id;
if (id_pred == id_obs) {
particle.weight *= multiv_prob(sig_x, sig_y, x_obs, y_obs, x_pred, y_pred);
}
}
}
weight_sum += particle.weight;
}
for (int j=0; j<num_particles; j++) {
Particle particle = particles[j];
double weight = particle.weight/weight_sum;
particle.weight = weight;
weights[j] = weight;
}
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
std::vector<Particle> p3;
double beta = 0.0;
int index = rand()% num_particles;
double max_weight = *max_element(weights.begin(), weights.end());
for (int i=0; i<num_particles; i++) {
double random = ((double) rand() / (RAND_MAX));
beta += random*2.0*max_weight;
while(beta > weights[index]) {
beta -= weights[index];
index = (index+1) % num_particles;
}
p3.push_back(particles[index]);
}
particles = p3;
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
|
ee780beffa78f40c6da1a58a437c5adc96817463
|
94eef8bc9fe9a39a1eacc5d197ecc5056c2f4cca
|
/21/06/frisky.cpp
|
ef1e2358362886f6163b32aa314b224999488a96
|
[] |
no_license
|
yurychu/cpp_coding
|
0f805fff172f1fa10488295f562ff667aea06d62
|
205ca786f6f129fccfd18f184582e29934b4d7de
|
refs/heads/master
| 2021-08-27T17:24:32.022949
| 2017-06-11T17:30:23
| 2017-06-11T17:30:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 609
|
cpp
|
frisky.cpp
|
#include <iostream>
using namespace std;
class Cat {
public:
// открытые методы доступа
unsigned int get_age();
void set_age(unsigned int age);
unsigned int get_weight();
void set_weight(unsigned int weight);
// открытые методы
void say_meow();
private:
// закрытые поля
unsigned int age;
unsigned int weight;
};
int main(){
Cat frisky;
frisky.set_age(4);
cout << "Frisky is a cat who is: " << frisky.get_age() << " year old " << endl;
return 0;
}
|
a170d67929944d5d148890ccea9892325b43bc91
|
0f8a1658e619914040590c63da251c6b32cf7f31
|
/src/client/videocap.cpp
|
d451fa1780fd0849a9620d10b66ffa58a0bf98bd
|
[] |
no_license
|
llyaiyyl/guard
|
e198c852810ed7ca9f141ade9588ffd51f88fcb7
|
f26ba114f9ae8968aa880b78be68f6bfdf226a5d
|
refs/heads/master
| 2020-03-28T01:20:16.065844
| 2018-09-28T09:46:05
| 2018-09-28T09:46:05
| 147,496,858
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,519
|
cpp
|
videocap.cpp
|
#include "videocap.h"
using namespace std;
videocap::videocap(AVFormatContext * ptr_format_ctx, AVCodecContext * ptr_codec_ctx, AVCodec * ptr_codec, int video_stream, int audio_stream,
int fps, int width, int height, int pix_fmt, int codec_id, url_type type)
{
int ret;
ptr_format_ctx_ = ptr_format_ctx;
ptr_codec_ctx_ = ptr_codec_ctx;
ptr_codec_ = ptr_codec;
sws_ctx_ = NULL;
frame_ = NULL;
dst_data_[0] = NULL;
video_stream_ = video_stream;
audio_stream_ = audio_stream;
fps_ = fps;
width_ = width;
height_ = height;
pix_fmt_ = pix_fmt;
codec_id_ = codec_id;
type_ = type;
sws_ctx_ = sws_getContext(ptr_codec_ctx_->width,
ptr_codec_ctx_->height,
ptr_codec_ctx_->pix_fmt,
ptr_codec_ctx_->width,
ptr_codec_ctx_->height,
AV_PIX_FMT_BGR24,
SWS_BILINEAR,
NULL,
NULL,
NULL);
if(NULL == sws_ctx_) {
cout << "sws_getContext error" << endl;
}
frame_ = av_frame_alloc();
if(NULL == frame_) {
cout << "av_frame_alloc error" << endl;
}
ret = av_image_alloc(dst_data_, dst_linesize_, width_, height_, AV_PIX_FMT_BGR24, 1);
if(ret < 0) {
cout << "av_image_alloc: " << ret << endl;
dst_data_[0] = NULL;
}
if(NULL == sws_ctx_ || NULL == frame_ || NULL == dst_data_[0]) {
if(dst_data_[0]) {
av_freep(&dst_data_[0]);
dst_data_[0] = NULL;
}
if(frame_) {
av_frame_free(&frame_);
frame_ = NULL;
}
if(sws_ctx_) {
sws_freeContext(sws_ctx_);
sws_ctx_ = NULL;
}
}
}
videocap::~videocap()
{
if(dst_data_[0]) {
av_freep(&dst_data_[0]);
dst_data_[0] = NULL;
}
if(frame_) {
av_frame_free(&frame_);
frame_ = NULL;
}
if(sws_ctx_) {
sws_freeContext(sws_ctx_);
}
if(ptr_codec_ctx_) {
avcodec_close(ptr_codec_ctx_);
avcodec_free_context(&ptr_codec_ctx_);
ptr_codec_ctx_ = NULL;
}
if(ptr_format_ctx_) {
avformat_close_input(&ptr_format_ctx_);
ptr_format_ctx_ = NULL;
}
}
videocap * videocap::create(const char *url, videocap::url_type type)
{
AVFormatContext * ptr_format_ctx = NULL;
AVCodecContext * ptr_codec_ctx = NULL;
AVCodec * ptr_codec = NULL;
AVDictionary * opts = NULL;
int video_stream, audio_stream, fps;
int ret;
if(videocap::url_type_rtsp == type) {
av_dict_set(&opts, "rtsp_transport", "tcp", 0);
} else if(videocap::url_type_v4l2 == type) {
avdevice_register_all();
} else if(videocap::url_type_unknow == type) {
cout << "url_type_unknow" << endl;
return NULL;
}
ret = avformat_open_input(&ptr_format_ctx, url, NULL, &opts);
if(ret) {
cout << "avformat_open_input: " << ret << endl;
return NULL;
}
ret = avformat_find_stream_info(ptr_format_ctx, NULL);
if(ret < 0) {
cout << "avformat_find_stream_info: " << ret << endl;
goto err0;
}
av_dump_format(ptr_format_ctx, 0, url, 0);
// find video stream
video_stream = -1;
for(uint32_t i = 0; i < ptr_format_ctx->nb_streams; i++) {
if(ptr_format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream = i;
break;
}
}
if(video_stream == -1) {
cout << "can't find video stream" << endl;
goto err0;
}
fps = (ptr_format_ctx->streams[video_stream]->avg_frame_rate.num) * 1.0 / ptr_format_ctx->streams[video_stream]->avg_frame_rate.den;
// find audio stream
audio_stream = -1;
for(uint32_t i = 0; i < ptr_format_ctx->nb_streams; i++) {
if(ptr_format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
audio_stream = i;
break;
}
}
if(audio_stream == -1) {
cout << "can't find audio stream" << endl;
}
ptr_codec = avcodec_find_decoder(ptr_format_ctx->streams[video_stream]->codecpar->codec_id);
if(NULL == ptr_codec) {
cout << "avcodec_find_decoder error" << endl;
goto err0;
}
ptr_codec_ctx = avcodec_alloc_context3(ptr_codec);
avcodec_parameters_to_context(ptr_codec_ctx, ptr_format_ctx->streams[video_stream]->codecpar);
ret = avcodec_open2(ptr_codec_ctx, ptr_codec, NULL);
if(ret < 0) {
cout << "avcodec_open2: " << ret << endl;
goto err1;
}
cout << ptr_codec_ctx->width << " x " << ptr_codec_ctx->height
<<" pix_fmt: " << ptr_codec_ctx->pix_fmt
<<" codec_id: " << ptr_format_ctx->streams[video_stream]->codecpar->codec_id
<<" fps: " << fps << endl;
return new videocap(ptr_format_ctx, ptr_codec_ctx, ptr_codec, video_stream, audio_stream,
fps, ptr_codec_ctx->width, ptr_codec_ctx->height, ptr_codec_ctx->pix_fmt, ptr_format_ctx->streams[video_stream]->codecpar->codec_id,
type);
err1:
avcodec_free_context(&ptr_codec_ctx);
err0:
avformat_close_input(&ptr_format_ctx);
return NULL;
}
int videocap::read_packet(AVPacket *packet)
{
return av_read_frame(ptr_format_ctx_, packet);
}
int videocap::read_rgbpic(const AVPacket * pkt, uint8_t ** ppdata, int * psize)
{
int ret;
if(NULL == sws_ctx_) {
cout << "uninit sws_ctx" << endl;
goto err;
}
ret = avcodec_send_packet(ptr_codec_ctx_, pkt);
if(ret < 0) {
cout << "avcodec_send_packet: " << ret << endl;
goto err;
}
ret = avcodec_receive_frame(ptr_codec_ctx_, frame_);
if(0 != ret) {
cout << "avcodec_receive_frame: " << ret << endl;
goto err;
}
ret = sws_scale(sws_ctx_,
(const uint8_t * const *)frame_->data,
frame_->linesize,
0,
frame_->height,
dst_data_,
dst_linesize_);
if(0 == ret) {
cout << "sws_scale error" << endl;
goto err;
}
av_frame_unref(frame_);
*ppdata = dst_data_[0];
*psize = dst_linesize_[0];
return ptr_codec_ctx_->frame_number;
err:
av_frame_unref(frame_);
*ppdata = NULL;
*psize = 0;
return -1;
}
|
2ded059236dd57a88157c1a7c931a110b0c1b6a9
|
580a178ed0db73bac2f6fd01270ebaa2312c9d1e
|
/HW12_E24084208/Source Code/Others/Game.cpp
|
ba128c313704ae68a3d52e5f2e3616730059df93
|
[] |
no_license
|
Learning-Jench2103/IC2_2020_Final-Project_RPG-Game
|
40e735d438696dd5d4a957b678fd22c2abbb73c7
|
e3f24852b67ed8c4478592e46900af9b85f9a848
|
refs/heads/master
| 2022-10-17T17:01:25.815473
| 2020-06-11T07:56:52
| 2020-06-11T07:56:52
| 254,785,080
| 0
| 0
| null | null | null | null |
BIG5
|
C++
| false
| false
| 34,649
|
cpp
|
Game.cpp
|
#include "Game.h"
#include <conio.h>
#include <ctime>
#include <set>
#include <fstream>
using namespace std;
void Game::generatePlayers()
{
Menu player_select_menu;
{
player_select_menu.question_name = "請選擇一個角色";
player_select_menu.instruction.push_back("您可以只擁有一個角色,並以他傲視群雄");
player_select_menu.instruction.push_back("您也可以擁有由數個成員組成的戰隊,並和他們一同稱霸天下");
player_select_menu.instruction.push_back("");
player_select_menu.instruction.push_back("以下是可選擇的角色清單及他們分別的屬性");
player_select_menu.instruction.push_back("請以↑↓鍵及 Enter 選擇最想要的職業");
player_select_menu.instruction.push_back("選擇完畢請按 Esc 退出選單");
player_select_menu.options.push_back(" NovicePlayer ");
player_select_menu.options.push_back(" OrcPlayer ");
player_select_menu.options.push_back(" KnightPlayer ");
player_select_menu.options.push_back("MagicianPlayer");
player_select_menu.option_descriptions.push_back("沒有過多特殊技能讓它無比單純;純真的特質讓對手往往對他掉以輕心,而受到較少的攻擊");
player_select_menu.option_descriptions.push_back("比 NovicePlayer 擁有更強攻擊能力,卻也讓對手們意識到他的厲害,下手漸漸不留情面");
player_select_menu.option_descriptions.push_back("擁有將魔力轉換為血量的特殊技能,讓它在千鈞一髮之際往往能有驚無險脫身");
player_select_menu.option_descriptions.push_back("使用特技可將血量轉為魔力,能在佔到上風時直接給對手更強力的致命一擊");
}
int response;
bool at_least_one = false;
do {
NovicePlayer* player_ptr;
system("cls");
response = player_select_menu.run();
switch (response) {
case 0:
player_ptr = new NovicePlayer;
break;
case 1:
player_ptr = new OrcPlayer;
break;
case 2:
player_ptr = new KnightPlayer;
break;
case 3:
player_ptr = new MagicianPlayer;
break;
default:
player_ptr = new NovicePlayer;
}
if (response != -1) {
cout << " 為他取個名字吧:";
string input;
getline(cin, input);
player_ptr->setName(input);
player_list.push_back(player_ptr);
at_least_one = true;
}
else if (!at_least_one) {
cout << " 您的隊伍至少需要一個職業哦哦哦";
Sleep(1000);
system("cls");
Sleep(500);
}
} while (response != -1 || !at_least_one);
all_player_level_sigma = player_list.size();
}
void Game::initializeFirstFloor()
{
if (First_floor != nullptr) {
delete First_floor;
}
First_floor = new Field("1F GP教室.csv", 14, 14);
First_floor->setGrid(111, "陷阱", "●", 253, "");
First_floor->setGrid(131, "紙條", "■", 250, "");
First_floor->setGrid(121, "蟲洞", "■", 250, "");
First_floor->setGrid(11, "商店", "■", 249, "");
First_floor->setGrid(101, "", "■", 206, "");
}
void Game::initializeSecondFloor()
{
if (Second_floor != nullptr) {
delete Second_floor;
}
Second_floor = new Field("2F LSD廣場.csv", 14, 14);
Second_floor->setGrid(11, "商店", "■", 249, "");
Second_floor->setGrid(201, "", "■", 206, "");
Second_floor->setGrid(221, "", "■", 242, "Q:最健忘的水果");
Second_floor->setGrid(222, "", "■", 242, "Q:視力最差的水果");
Second_floor->setGrid(223, "", "■", 242, "Q:長腳尖嘴郎 吹簫入洞房 只為貪吃硃砂酒 一聲霹靂見閻王");
Second_floor->setGrid(224, "", "■", 242, "Q:背板過海 滿腹文章");
Second_floor->setGrid(231, "", "榴", 165, "");
Second_floor->setGrid(232, "", "槤", 165, "");
Second_floor->setGrid(233, "", "梨", 165, "");
Second_floor->setGrid(234, "", "子", 165, "");
Second_floor->setGrid(235, "", "香", 165, "");
Second_floor->setGrid(236, "", "蕉", 165, "");
Second_floor->setGrid(237, "", "芒", 165, "");
Second_floor->setGrid(238, "", "果", 165, "");
Second_floor->setGrid(239, "", "西", 165, "");
Second_floor->setGrid(240, "", "瓜", 165, "");
Second_floor->setGrid(241, "", "蚊", 165, "");
Second_floor->setGrid(242, "", "子", 165, "");
Second_floor->setGrid(243, "", "水", 165, "");
Second_floor->setGrid(244, "", "蛭", 165, "");
Second_floor->setGrid(245, "", "烏", 165, "");
Second_floor->setGrid(246, "", "賊", 165, "");
Second_floor->setGrid(247, "", "蝸", 165, "");
Second_floor->setGrid(248, "", "牛", 165, "");
Second_floor->setGrid(261, "NotNot", "★", 156, "");
Second_floor->setGrid(262, "NotNot", "★", 156, "");
Second_floor->setGrid(271, "", "■", 250, "");
}
void Game::initializeThirdFloor()
{
if (Third_floor != nullptr) {
delete Third_floor;
}
Third_floor = new Field("3F ICCPP World.csv", 15, 11);
Third_floor->setGrid(11, "商店", "■", 249, "");
Third_floor->setGrid(301, "", "■", 206, "");
Third_floor->setGrid(311, "", "●", 165, "");
Third_floor->setGrid(312, "", "●", 165, "");
Third_floor->setGrid(313, "", "●", 165, "");
Third_floor->setGrid(314, "", "●", 165, "");
Third_floor->setGrid(315, "", "●", 165, "");
}
void Game::setCursor(int x, int y) const
{
HANDLE hin;
DWORD WriteWord;
COORD pos;
hin = GetStdHandle(STD_OUTPUT_HANDLE);
pos.X = x, pos.Y = y; // 將位置設在 (x,y) 之地方。
SetConsoleCursorPosition(hin, pos);
}
void Game::setColor(unsigned int color) const
{
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
}
bool Game::play()
{
int press;
bool game_end = false;
while (!game_end) {
system("cls");
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
// random gift begin
{
setColor(12);
if (step_count > 30 && rand() % 40 == 0) {
for (int i = 0; i < player_list.size(); i++) {
player_list.at(i)->addExp(10);
}
cout << " 恭喜踩到寶箱!你的每位成員都獲得了10點經驗值!\n\n ";
setColor();
step_count = 0;
}
else if (step_count > 30 && rand() % 30 == 0) {
for (int i = 0; i < player_list.size(); i++) {
player_list.at(i)->addHp(5);
}
cout << " 恭喜踩到寶箱!你的每位成員都獲得了5點血量!\n\n ";
setColor();
step_count = 0;
}
else if (step_count > 30 && rand() % 26 == 0) {
for (int i = 0; i < player_list.size(); i++) {
player_list.at(i)->addExp(5);
}
cout << " 恭喜踩到寶箱!你的每位成員都獲得了5點經驗值!\n\n ";
setColor();
step_count = 0;
}
else if (step_count > 30 && rand() % 22 == 0) {
for (int i = 0; i < player_list.size(); i++) {
money += 10;
}
cout << " 恭喜踩到寶箱!你獲得了10塊金幣!\n\n ";
setColor();
step_count = 0;
}
setColor();
}
// random gift end
// detect current_symbol before moving
set<int> choose_member;
int current_symbol = current_field->getSymbol();
{
// All map
switch (current_symbol) {
case 11:
{
system("cls");
store->run();
system("cls");
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
}
break;
case 21:
{
if (rand() % 100 == 0) {
system("cls");
cout << " 恭喜您在這個不起眼的角落\n"; Sleep(1000);
cout << " 遇上了千年一遇的\n"; Sleep(1000);
cout << " cpsoo先生走失的那隻\n"; Sleep(1000);
cout << " 每十多年才會現身一次的那隻\n"; Sleep(1000);
cout << " 名為薛丁葛格的貓\n\n"; Sleep(1000);
cout << " 為了感謝你讓牠再次被世人憶起\n"; Sleep(1000);
cout << " cpsoo先生決定破天荒\n"; Sleep(1000);
cout << " 替你所有的隊員祈禱\n"; Sleep(1000);
cout << " 立即晉升一個等級!!\n\n";
for (int i = 0; i < player_list.size(); i++) {
player_list.at(i)->setExp(player_list.at(i)->getLvupExp() + 10);
}
Sleep(4000);
system("cls");
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
}
}
break;
}
// 1F
switch (current_symbol) {
case 101:
if (!goblin_monster_killed) {
system("cls");
Sleep(1000);
cout << "\n Goblin:你還沒\n\n";
Sleep(2000);
cout << " Goblin:從我身上踩過去\n\n";
Sleep(2000);
cout << " Goblin:還想離開這裡啊啊啊\n\n";
Sleep(2000);
cout << " Goblin:先來我家打敗我再說!!\n\n";
Sleep(2500);
system("cls");
Sleep(1000);
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
}
else if (paper_amount < 5) {
system("cls");
Sleep(1000);
cout << "\n cpsoo先生:Wait wait wait!!\n\n";
Sleep(2000);
cout << " cpsoo先生:我的紙片\n\n";
Sleep(2000);
cout << " cpsoo先生:你還沒找完rrrrrrr\n\n";
Sleep(2000);
cout << " cpsoo先生:撿完前別想離開這裡!\n\n";
Sleep(2500);
system("cls");
Sleep(1000);
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
}
else {
system("cls");
Sleep(500);
setCursor(3, 3);
cout << "電梯上樓...";
Sleep(1000);
current_field = Second_floor;
system("cls");
if (!second_floor_entered) {
Welcome_2F welcome;
welcome.run();
system("cls");
Sleep(500);
second_floor_entered = true;
}
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
}
break;
case 111:
// Create a battle
player_screen = new Menu;
int player_list_response;
player_screen->question_name = "查看您的隊伍成員";
player_screen->instruction.push_back("請以↑↓鍵移動游標,並以Enter選擇參加戰鬥的隊員,選擇完畢請按下Esc;或直接按Esc鍵退出");
for (int i = 0; i < player_list.size(); i++) {
player_screen->options.push_back(player_list.at(i)->getName());
}
for (int i = 0; i < player_list.size(); i++) {
player_screen->option_descriptions.push_back(player_list.at(i)->showInfo());
}
//Sleep(3000);
system("cls");
Sleep(1000);
do {
player_list_response = player_screen->run();
if (player_list_response != -1) {
choose_member.insert(player_list_response);
}
} while (player_list_response != -1 && choose_member.size() != player_list.size());
if (choose_member.size() != 0) {
vector<NovicePlayer*> choose_player;
for (set<int>::iterator it = choose_member.begin(); it != choose_member.end(); it++) {
choose_player.push_back(player_list.at(*it));
}
int monster_num = (choose_player.size() * 0.7 >= 1) ? choose_player.size() * 0.7 : 1;
vector<BaseMonster*> monster_list;
for (int i = 0; i < monster_num; i++) {
BaseMonster* goblin = new GoblinMonster;
monster_list.push_back(goblin);
}
Battle* battle = new Battle(choose_player, monster_list, 0);
system("cls");
battle->run();
if (battle->playerWin()) {
goblin_monster_killed = true;
}
if (battle->monsterWin()) {
cout << " 遊戲即將結束";
Sleep(1500);
game_end = true;
}
for (int i = 0; i < player_list.size(); i++) {
if (player_list.at(i)->getHp() == 0) {
delete player_list.at(i);
player_list.erase(player_list.begin() + i);
i = -1;
}
}
for (int i = 0; i < monster_list.size(); i++) {
delete monster_list.at(i);
}
delete battle;
}
delete player_screen;
system("cls");
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
break;
case 121:
system("cls");
Sleep(1000);
setCursor(4, 2);
cout << "你已經進入了";
Sleep(2000);
setCursor(4, 4);
cout << "cpsoo先生畢生追尋的";
Sleep(2000);
setCursor(4, 6);
cout << "時空隧道";
Sleep(2000);
setCursor(4, 8);
cout << "請稍待他找尋你命中注定的地點將時空折疊";
Sleep(2000);
setCursor(4, 10);
cout << "把你送到未知的那個地方...";
Sleep(4000);
int x, y;
do {
x = rand() % current_field->getMapSize().width;
y = rand() % current_field->getMapSize().height;
} while (current_field->getSymbol(x, y) != 0);
current_field->setPosition(x, y);
system("cls");
Sleep(500);
continue;
break;
case 131:
if (!current_field->isStepped()) {
system("cls");
current_field->setGrid(current_field->getCurrentPosition(), "紙");
current_field->display();
++paper_amount;
setCursor(2, 22);
cout << "恭喜你撿到一張cpsoo先生失落已久的紙條!!";
current_field->step();
setCursor(2, 24);
cout << "已撿回 " << paper_amount << " 張紙條";
}
break;
}
// 2F
NotNotGame* notnotgame = nullptr;
switch (current_symbol) {
case 200:
//Sleep(1000);
system("cls");
Sleep(500);
setCursor(3, 3);
cout << "電梯下樓...";
Sleep(1000);
current_field = First_floor;
system("cls");
Sleep(500);
current_field->display();
if (current_field == First_floor) {
cout << " 已撿回 " << paper_amount << " 張紙條\n\n";
}
break;
case 201:
if (!second_floor_finish) {
system("cls");
End_2F End;
End.run();
system("cls");
player_screen = new Menu;
int player_list_response;
player_screen->question_name = "查看您的隊伍成員";
player_screen->instruction.push_back("請以↑↓鍵移動游標,並以Enter選擇參加戰鬥的隊員,選擇完畢請按下Esc;或直接按Esc鍵退出");
for (int i = 0; i < player_list.size(); i++) {
player_screen->options.push_back(player_list.at(i)->getName());
}
for (int i = 0; i < player_list.size(); i++) {
player_screen->option_descriptions.push_back(player_list.at(i)->showInfo());
}
system("cls");
do {
player_list_response = player_screen->run();
if (player_list_response != -1) {
choose_member.insert(player_list_response);
}
} while (player_list_response != -1 && choose_member.size() != player_list.size());
if (choose_member.size() != 0) {
vector<NovicePlayer*> choose_player;
for (set<int>::iterator it = choose_member.begin(); it != choose_member.end(); it++) {
choose_player.push_back(player_list.at(*it));
}
int monster_num = (choose_player.size() * 0.7 >= 1) ? choose_player.size() * 0.7 : 1;
vector<BaseMonster*> monster_list;
for (int i = 0; i < monster_num; i++) {
BaseMonster* zombie = new ZombieMonster;
monster_list.push_back(zombie);
}
Battle* battle = new Battle(choose_player, monster_list, 0);
system("cls");
battle->run();
if (battle->playerWin()) {
zombie_monster_killed = true;
second_floor_finish = true;
system("cls");
Sleep(500);
cout << "\n\n 電梯上樓...";
current_field = Third_floor;
Sleep(1000);
if (!third_floor_entered) {
system("cls");
Welcome_3F welcome;
welcome.run();
Sleep(500);
third_floor_entered = true;
}
system("cls");
current_field->display();
}
else if (battle->monsterWin()) {
cout << " 遊戲即將結束";
Sleep(1500);
game_end = true;
break;
}
else {
current_field->setPosition(28, 27);
current_field->display();
}
for (int i = 0; i < player_list.size(); i++) {
if (player_list.at(i)->getHp() == 0) {
delete player_list.at(i);
player_list.erase(player_list.begin() + i);
i = -1;
}
}
for (int i = 0; i < monster_list.size(); i++) {
delete monster_list.at(i);
}
delete battle;
}
delete player_screen;
}
else {
system("cls");
Sleep(500);
cout << "\n\n 電梯上樓...";
current_field = Third_floor;
Sleep(500);
system("cls");
current_field->display();
}
break;
case 233:
case 235:
case 239:
case 243:
case 247:
cout << " 你猜錯方向了啦啦啦啦啦 所有成員將被扣5點經驗值";
for (int i = 0; i < player_list.size(); i++) {
player_list.at(i)->minusExp(5);
}
break;
case 261:
if (!first_notnot) {
system("cls");
setCursor(2, 1);
cout << "歡迎!";
Sleep(2000);
setCursor(2, 3);
cout << "為了迎接風塵僕僕的你到來";
Sleep(2000);
setCursor(2, 5);
cout << "CAS先生早已精心為你設計了一場刺激的挑戰";
Sleep(2000);
setCursor(2, 7);
cout << "通過考驗後即可繼續旅程,但若不幸挑戰失利您將被送回原位,重新參加挑戰";
Sleep(2000);
setCursor(2, 9);
cout << "準備好了嗎!";
Sleep(2000);
setCursor(2, 11);
cout << "以下是一些和方向相關的問題,請在時限內按下符合題意的按鍵,";
Sleep(1500);
setCursor(2, 13);
cout << "您有一次答錯的機會,";
Sleep(1500);
setCursor(2, 15);
cout << "別緊張放輕鬆,挑戰即將開始!";
Sleep(2500);
notnotgame = new NotNotGame(15);
if (!notnotgame->run(player_list)) {
current_field->setPosition(7, 26);
delete notnotgame;
}
else {
current_field->setPosition(9, 26);
first_notnot = true;
delete notnotgame;
}
current_field->display();
}
break;
case 262:
if (!second_notnot) {
system("cls");
setCursor(2, 1);
cout << "遠道而來的你辛苦了!";
Sleep(2000);
setCursor(2, 3);
cout << "看到你先前優異的表現";
Sleep(2000);
setCursor(2, 5);
cout << "CAS先生決定再多給你一點考驗";
Sleep(2000);
setCursor(2, 7);
cout << "這次的題數比剛剛稍微多了點";
Sleep(2000);
setCursor(2, 9);
cout << "不過相信你必定可以跟剛剛一樣順利通過的!!";
Sleep(2500);
notnotgame = new NotNotGame(25);
if (!notnotgame->run(player_list)) {
current_field->setPosition(19, 26);
delete notnotgame;
continue;
}
else {
current_field->setPosition(18, 27);
second_notnot = true;
delete notnotgame;
continue;
}
}
break;
case 271:
system("cls");
Sleep(1000);
setCursor(4, 2);
cout << "樓下那位熱衷實(搞)驗(鬼)的cpsoo先生";
Sleep(2000);
setCursor(4, 4);
cout << "不小心玩過頭將你所處的空間折了起來";
Sleep(2000);
setCursor(4, 6);
cout << "將LSD廣場的另一端";
Sleep(2000);
setCursor(4, 8);
cout << "與你腳下建起了時空走廊";
Sleep(2000);
setCursor(4, 10);
cout << "稍待一會,空間即將切換...";
Sleep(4000);
int x, y;
do {
x = rand() % current_field->getMapSize().width;
y = rand() % current_field->getMapSize().height;
} while (current_field->getSymbol(x, y) != 0);
current_field->setPosition(x, y);
system("cls");
Sleep(500);
continue;
break;
}
// 3F
switch (current_symbol) {
case 300:
system("cls");
Sleep(500);
setCursor(3, 3);
cout << "電梯下樓...";
Sleep(1000);
current_field = Second_floor;
system("cls");
Sleep(500);
current_field->display();
break;
case 301:
player_screen = new Menu;
int player_list_response;
player_screen->question_name = "查看您的隊伍成員";
player_screen->instruction.push_back("請以↑↓鍵移動游標,並以Enter選擇參加戰鬥的隊員,選擇完畢請按下Esc;或直接按Esc鍵退出");
for (int i = 0; i < player_list.size(); i++) {
player_screen->options.push_back(player_list.at(i)->getName());
}
for (int i = 0; i < player_list.size(); i++) {
player_screen->option_descriptions.push_back(player_list.at(i)->showInfo());
}
system("cls");
do {
player_list_response = player_screen->run();
if (player_list_response != -1) {
choose_member.insert(player_list_response);
}
} while (player_list_response != -1 && choose_member.size() != player_list.size());
if (choose_member.size() != 0) {
vector<NovicePlayer*> choose_player;
for (set<int>::iterator it = choose_member.begin(); it != choose_member.end(); it++) {
choose_player.push_back(player_list.at(*it));
}
int monster_num = (choose_player.size() * 0.7 >= 1) ? choose_player.size() * 0.7 : 1;
vector<BaseMonster*> monster_list;
for (int i = 0; i < monster_num; i++) {
BaseMonster* jwmonster = new JWMonster;
monster_list.push_back(jwmonster);
}
Battle* battle = new Battle(choose_player, monster_list, 0);
system("cls");
battle->run();
if (battle->playerWin()) {
system("cls");
EndScreen end_screen;
game_end = true;
break;
}
else if (battle->monsterWin()) {
cout << " 遊戲即將結束";
Sleep(1500);
game_end = true;
break;
}
else {
current_field->display();
}
for (int i = 0; i < player_list.size(); i++) {
if (player_list.at(i)->getHp() == 0) {
delete player_list.at(i);
player_list.erase(player_list.begin() + i);
i = -1;
}
}
for (int i = 0; i < monster_list.size(); i++) {
delete monster_list.at(i);
}
delete battle;
}
delete player_screen;
break;
case 311:
system("cls");
current_field->setPosition(1, 3);
current_field->display();
current_field->setPosition(4, 2);
current_field->display();
current_field->setPosition(3, 8);
current_field->display();
current_field->setPosition(1, 6);
current_field->display();
current_field->setPosition(10, 7);
current_field->display();
break;
case 312:
system("cls");
Sleep(500);
setCursor(3, 1);
cout << "樓下廣場的整修工程";
Sleep(1500);
setCursor(3, 3);
cout << "不小心對天花板鑽破了個洞";
Sleep(1500);
setCursor(3, 5);
cout << "位置";
Sleep(1500);
setCursor(3, 7);
cout << "該好就在你的腳下";
Sleep(1500);
setCursor(3, 9);
cout << "小心!!!";
Sleep(1000);
system("cls");
current_field = Second_floor;
current_field->setPosition(15, 20);
current_field->display();
break;
case 313:
system("cls");
Sleep(500);
setCursor(3, 1);
cout << "台南連日的大雨";
Sleep(1500);
setCursor(3, 3);
cout << "又大又急";
Sleep(1500);
setCursor(3, 5);
cout << "淹了頂樓甚至";
Sleep(1500);
setCursor(3, 7);
cout << "衝破了你頭上的屋頂";
Sleep(1500);
setCursor(3, 9);
cout << "......";
Sleep(1500);
setCursor(3, 11);
cout << "大水把你往後沖了好一段路";
Sleep(1500);
setCursor(3, 13);
cout << "受了不少傷";
Sleep(3000);
setCursor(3, 16);
cout << "所有人血量少了20點";
Sleep(2500);
system("cls");
current_field->setPosition(2, 9);
current_field->display();
break;
case 314:
system("cls");
Sleep(500);
setCursor(3, 1);
cout << "終於踏進這一格的您辛苦了";
Sleep(1500);
setCursor(3, 3);
cout << "雖然這依然不是正確的密道";
Sleep(1500);
setCursor(3, 5);
cout << "如果已經找很久的話偷偷提示您";
Sleep(1500);
setCursor(3, 7);
cout << "別太早轉彎多走幾步路必是值得ㄉ";
Sleep(1500);
setCursor(3, 9);
cout << "雖然你腳下的地板";
Sleep(1500);
setCursor(3, 11);
cout << "早已裂開一個無法挽回的洞";
Sleep(1500);
setCursor(3, 13);
cout << "請小心,摔落即將開始...";
current_field = Second_floor;
Sleep(2500);
system("cls");
current_field->setPosition(27, 13);
current_field->display();
break;
case 315:
system("cls");
Sleep(500);
setCursor(3, 1);
cout << "今天的狀況異常的危急";
Sleep(1500);
setCursor(3, 3);
cout << "就跟我們的每一次期末一樣";
Sleep(1500);
setCursor(3, 5);
cout << "如果你還沒發現異狀請小心踏下未來每一步";
Sleep(1500);
setCursor(3, 7);
cout << "如果已經發現了";
Sleep(1500);
setCursor(3, 9);
cout << "恭喜你";
Sleep(1500);
setCursor(3, 11);
cout << "這裡是少數尚未危機四伏的巷子";
Sleep(1500);
setCursor(3, 13);
cout << "除了,風有點大,你要站不穩了...";
Sleep(2500);
system("cls");
current_field->setPosition(1, 8);
current_field->display();
break;
}
}
if (game_end) {
break;
}
// Let user press a key
{
do {
press = _getch();
if (press == 224) {
press = _getch();
}
switch (press) {
case 75:
case 'A':
press = 'a';
break;
case 77:
case 'D':
press = 'd';
break;
case 72:
case 'W':
press = 'w';
break;
case 80:
case 'S':
press = 's';
break;
case 'm':
serialize();
break;
case 'p':
player_screen = new Menu;
int player_list_response;
player_screen->question_name = "查看您的隊伍成員";
player_screen->instruction.push_back("請以↑↓鍵移動游標,並以Esc鍵退出");
for (int i = 0; i < player_list.size(); i++) {
player_screen->options.push_back(player_list.at(i)->getName());
}
for (int i = 0; i < player_list.size(); i++) {
player_screen->option_descriptions.push_back(player_list.at(i)->showInfo());
}
system("cls");
player_list_response = player_screen->run();
while (player_list_response != -1) {
player_list_response = player_screen->run();
}
delete player_screen;
system("cls");
current_field->display();
break;
case 'b':
system("cls");
backpack.display();
system("cls");
current_field->display();
break;
case 'v':
system("cls");
if (current_field == First_floor) {
legend_1F legend;
legend.display();
}
else if (current_field == Second_floor) {
legend_2F legend;
legend.display();
}
else if (current_field == Third_floor) {
legend_3F legend;
legend.display();
}
system("cls");
current_field->display();
break;
}
} while (!current_field->move(press) && press != 27);
}
if (press == 27) {
break;
}
// hot key in field screen end
// moving
++step_count;
// detect current_symbol after moving
current_symbol = current_field->getSymbol();
int temp_level_sigma = 0;
for (int i = 0; i < player_list.size(); i++) {
temp_level_sigma += player_list.at(i)->getLevel();
}
if (temp_level_sigma > all_player_level_sigma) {
for (int i = 0; i < temp_level_sigma - all_player_level_sigma; i++) {
backpack.addWeightLimit();
}
}
all_player_level_sigma = temp_level_sigma;
}
return game_end;
}
void Game::serialize()
{
fstream file("record.txt", ios::out);
// players
for (int i = 0; i < player_list.size(); i++) {
file << player_list.at(i)->serialize() << endl;
}
// backpack
file << backpack.serialize() << endl;
// current_field
if (current_field == First_floor) {
file << "@current_field$First_floor$#" << endl;
}
else if (current_field == Second_floor) {
file << "@current_field$Second_floor$#" << endl;
}
else if (current_field == Third_floor) {
file << "@current_field$Third_floor$#" << endl;
}
// positions in each field
stringstream s1, s2;
s1 << First_floor->getCurrentPosition().x;
s2 << First_floor->getCurrentPosition().y;
file << ("@First_floor$" + s1.str() + '$' + s2.str() + '$' + '#') << endl;
s1.str(""); s1.clear(); s2.str(""); s2.clear();
s1 << Second_floor->getCurrentPosition().x;
s2 << Second_floor->getCurrentPosition().y;
file << ("@Second_floor$" + s1.str() + '$' + s2.str() + '$' + '#') << endl;
s1.str(""); s1.clear(); s2.str(""); s2.clear();
s1 << Third_floor->getCurrentPosition().x;
s2 << Third_floor->getCurrentPosition().y;
file << ("@Third_floor$" + s1.str() + '$' + s2.str() + '$' + '#') << endl;
s1.str(""); s1.clear(); s2.str(""); s2.clear();
file << "@Game$ " << endl;
file << paper_amount << ' ' << all_player_level_sigma << ' ' << second_floor_entered << ' ' << third_floor_entered << ' '
<< second_floor_finish << ' ' << first_notnot << ' ' << second_notnot << ' '
<< goblin_monster_killed << ' ' << zombie_monster_killed << endl;
file << "#end#";
file.close();
}
void Game::unserialize()
{
// destructor
fstream file("record.txt", ios::in);
string input;
string label;
stringstream ss;
while (1) {
getline(file, input);
if (input.length() == 0) {
break;
}
int begin, end;
begin = input.find('@');
end = input.find('$');
if (begin == -1 || end == -1) {
break;
}
label = string(input, begin + 1, end - begin - 1);
if (label == "Game") {
break;
}
if (label == "NovicePlayer") {
player_list.push_back(NovicePlayer::unserialize(input));
}
else if (label == "OrcPlayer") {
player_list.push_back(OrcPlayer::unserialize(input));
}
else if (label == "KnightPlayer") {
player_list.push_back(KnightPlayer::unserialize(input));
}
else if (label == "MagicianPlayer") {
player_list.push_back(MagicianPlayer::unserialize(input));
}
else if (label == "Backpack") {
backpack.unserialize(input);
}
else if (input == "@current_field$First_floor$#") {
current_field = First_floor;
}
else if (input == "@current_field$Second_floor$#") {
current_field = Second_floor;
}
else if (input == "@current_field$Third_floor$#") {
current_field = Third_floor;
}
else if (label == "First_floor") {
int x, y;
int begin_posi, end_posi;
begin_posi = input.find('$');
end_posi = input.find('$', begin_posi + 1);
ss << string(input, begin_posi + 1, end_posi - begin_posi - 1);
ss >> x; ss.str(""); ss.clear();
begin_posi = end_posi;
end_posi = input.find('$', begin_posi + 1);
ss << string(input, begin_posi + 1, end_posi - begin_posi - 1);
ss >> y; ss.str(""); ss.clear();
First_floor->setPosition(x, y);
}
else if (label == "Second_floor") {
int x, y;
int begin_posi, end_posi;
begin_posi = input.find('$');
end_posi = input.find('$', begin_posi + 1);
ss << string(input, begin_posi + 1, end_posi - begin_posi - 1);
ss >> x; ss.str(""); ss.clear();
begin_posi = end_posi;
end_posi = input.find('$', begin_posi + 1);
ss << string(input, begin_posi + 1, end_posi - begin_posi - 1);
ss >> y; ss.str(""); ss.clear();
Second_floor->setPosition(x, y);
}
else if (label == "Third_floor") {
int x, y;
int begin_posi, end_posi;
begin_posi = input.find('$');
end_posi = input.find('$', begin_posi + 1);
ss << string(input, begin_posi + 1, end_posi - begin_posi - 1);
ss >> x; ss.str(""); ss.clear();
begin_posi = end_posi;
end_posi = input.find('$', begin_posi + 1);
ss << string(input, begin_posi + 1, end_posi - begin_posi - 1);
ss >> y; ss.str(""); ss.clear();
Third_floor->setPosition(x, y);
}
}
file >> paper_amount >> all_player_level_sigma >> second_floor_entered >> third_floor_entered
>> second_floor_finish >> first_notnot >> second_notnot
>> goblin_monster_killed >> zombie_monster_killed;
}
Game::Game()
{
srand(time(NULL));
backpack.setPlayerList(&player_list);
// Main_Menu //
{
Main_Menu.question_name = "遊戲主選單";
Main_Menu.instruction.push_back("歡迎進入我的RPG!");
Main_Menu.instruction.push_back("這是一款精心製作的遊戲");
Main_Menu.instruction.push_back("帶您體驗小大一苦中作樂的新鮮大學生活");
Main_Menu.instruction.push_back("");
Main_Menu.instruction.push_back("請以鍵盤↑↓鍵移動綠色游標,並以 Enter 選擇功能");
Main_Menu.instruction.push_back("");
Main_Menu.instruction.push_back("準備好了嗎?那就讓我們開始吧~~");
Main_Menu.options.push_back("進入遊戲");
Main_Menu.options.push_back("載入存檔");
Main_Menu.options.push_back("退 出");
Main_Menu.option_descriptions.push_back("讓我們邁步踏入未知的世界迎接挑戰吧");
Main_Menu.option_descriptions.push_back("從過去的紀錄再次出發");
Main_Menu.option_descriptions.push_back("該繼續準備期末囉:D");
}
store = new Store(&backpack, &money);
}
Game::~Game()
{
// delete player series objects //
for (int i = 0; i < player_list.size(); i++) {
delete player_list.at(i);
}
delete store;
delete First_floor;
delete Second_floor;
delete Third_floor;
}
void Game::run()
{
int main_menu_chosen;
bool close = false;
while (!close) { // main menu begin
system("cls");
main_menu_chosen = Main_Menu.run();
// options of main menu //
switch (main_menu_chosen) {
case 0: // main_menu_chosen == 0 begin
system("cls");
if (reset) {
if (player_list.size() > 0) {
for (int i = 0; i < player_list.size(); i++) {
delete player_list.at(i);
}
player_list.clear();
}
generatePlayers();
initializeFirstFloor();
initializeSecondFloor();
initializeThirdFloor();
current_field = First_floor;
backpack.clear();
money = 0;
paper_amount = 0;
all_player_level_sigma = 0;
second_floor_entered = false;
third_floor_entered = false;
second_floor_finish = false;
first_notnot = false;
second_notnot = false;
goblin_monster_killed = false;
zombie_monster_killed = false;
Welcome_1F welcome;
system("cls");
welcome.run();
system("cls");
}
reset = play();
break; // main_menu_chosen == 0 end
case 1:
initializeFirstFloor();
initializeSecondFloor();
initializeThirdFloor();
unserialize();
reset = play();
break;
case 2:
close = true;
}
} // main menu end
}
|
6c609dbdd730c4abb0d98c2ad695f3cbd6b3da41
|
9da315d428a71be07111a470c70938d0bf0183d6
|
/painter.h
|
a1f9519475f24c747832d35e8ed73f32912f86d4
|
[] |
no_license
|
chrisyeshi/Painter
|
df3a2ab84a1cf5c092d0de2b8952452c609ddeb3
|
962b6645608f6a99d07186c6a6672362793a6ad2
|
refs/heads/master
| 2020-05-17T18:42:49.721588
| 2016-02-24T00:43:44
| 2016-02-24T00:43:44
| 34,410,654
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,231
|
h
|
painter.h
|
#ifndef PAINTER_H
#define PAINTER_H
#include <iostream>
#include <QOpenGLShaderProgram>
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer>
#include "shape.h"
namespace yy {
// TODO: make painter to handle binding textures
class Painter
{
public:
Painter();
~Painter();
void initializeGL(const Shape& shape, const std::string& vert, const std::string& frag);
void initializeGL(const std::string& vert, const std::string& frag);
void initializeProgram(const std::string &vert, const std::string &frag);
void initializeVAO(const Shape& shape);
// god damn OpenGL doesn't share VAO among contexts, yet it fucking requires us to use VAO!
void recreateVAO();
void updateAttributes(const std::vector<Shape::Attribute>& attributes);
template <typename... Args>
void paint(Args... args);
template <typename Loc, typename Val, typename... Args>
void setUniforms(Loc location, Val value, Args... args);
template <typename Loc, typename Val>
void setUniform(Loc location, Val value);
private:
int nIndex;
Shape shape;
QOpenGLVertexArrayObject vao;
QOpenGLBuffer vbo, ibo;
QOpenGLShaderProgram* program;
template <typename Loc, typename Val, typename... Args>
void setUniformsInternal(Loc location, Val value, Args... args);
void setUniformsInternal() {}
};
// the variadic templated paint function
template <typename... Args>
void Painter::paint(Args... args)
{
auto f = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_3_3_Core>();
f->initializeOpenGLFunctions();
GLint oProg, oVao;
f->glGetIntegerv(GL_CURRENT_PROGRAM, &oProg);
program->bind();
setUniformsInternal(args...);
f->glGetIntegerv(GL_VERTEX_ARRAY_BUFFER_BINDING, &oVao);
vao.bind();
f->glDrawElements(GL_TRIANGLES, nIndex, GL_UNSIGNED_INT, 0);
vao.release();
f->glBindBuffer(GL_ARRAY_BUFFER, oVao);
program->release();
f->glUseProgram(oProg);
}
template <typename Loc, typename Val, typename... Args>
void Painter::setUniforms(Loc location, Val value, Args... args)
{
auto f = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_3_3_Core>();
f->initializeOpenGLFunctions();
GLint oProg;
f->glGetIntegerv(GL_CURRENT_PROGRAM, &oProg);
program->bind();
setUniformsInternal(location, value, args...);
program->release();
f->glUseProgram(oProg);
}
template <typename Loc, typename Val>
void Painter::setUniform(Loc location, Val value)
{
auto f = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_3_3_Core>();
f->initializeOpenGLFunctions();
GLint oProg;
f->glGetIntegerv(GL_CURRENT_PROGRAM, &oProg);
program->bind();
program->setUniformValue(location, value);
program->release();
f->glUseProgram(oProg);
}
template <typename Loc, typename Val, typename... Args>
void Painter::setUniformsInternal(Loc location, Val value, Args... args)
{
program->setUniformValue(location, value);
setUniformsInternal(args...);
}
} // namespace yy
#endif // PAINTER_H
|
0c76074c131230f28fc41c67a90986d291c0baec
|
43bb80335728466e8f2b0fe045b58c911ca8d9a0
|
/Software/Bus Test Card/bus-monitor/bus-monitor.ino
|
b7616cba9a0410c34831279334976ad88fa465d1
|
[] |
no_license
|
ksr/YACC1-2020
|
4a362f03fd6bd07d0b00769f7052997fcbc5994f
|
3bcacf3c574e82cbff498e6ba4a5b06939080487
|
refs/heads/master
| 2023-07-20T04:51:08.426852
| 2021-09-02T15:10:01
| 2021-09-02T15:10:01
| 289,729,240
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,915
|
ino
|
bus-monitor.ino
|
/*
BUS Monitor
Loops watching bus for changes.
Works well when combined with single step mode on sequencer
Usgae notes:
Monitor via Arduino IDE Monitor program
SET ARDUINO MONITOR TO "No Line Ending"
0 is off
1 is on
***** add logic to only monitor bus lines June 26/20
this program adjusts for active low vs active high
*/
#include <Wire.h>
#include "Adafruit_MCP23017.h"
#include <avr/pgmspace.h>
#include "YACC_Common_header.h"
//#define DEBUG
Adafruit_MCP23017 mcp[NUMBER_OF_CONTROLLERS];
// Hold previous state of bus signal lines (16 bits)
unsigned int previous[NUMBER_OF_CONTROLLERS];
// Hold cuurent state of bus signal lines (16 bits)
unsigned int current[NUMBER_OF_CONTROLLERS];
boolean first=true;
void flashLed(int led) {
char tmp[20];
#ifdef DEBUG
sprintf(tmp, "Flash %d\n", led);
Serial.print(tmp);
#endif
digitalWrite(led, HIGH);
delay(100);
digitalWrite(led, LOW);
}
void blinkLed(int led) {
char tmp[20];
#ifdef DEBUG
sprintf(tmp, "Flash %d\n", led);
Serial.print(tmp);
#endif
digitalWrite(led, HIGH);
delay(100);
digitalWrite(led, LOW);
delay(100);
}
/*
Given a chip and a pin number return the appropriate signal name string
*/
String strOpcode(int chip, int pinab) {
int i;
int port;
int pin;
char tmp[100];
/* Need to convert a 15 bit port bit pin number (pinab) in range 0-15 to port 0 or 1 and a a 8 bit pin
Pins 0-7 are on port 0, pint 8-15 are on port 1
*/
if (pinab >= PINS_PER_PORT) {
port = 1;
pin = pinab - PINS_PER_PORT;
} else {
port = 0;
pin = pinab;
}
i = 0;
#ifdef DEBUG
sprintf(tmp, "looking for %d %d %d %d\n", chip, port, pin);
Serial.print(tmp);
#endif
while (strlen(opcodes[i].code) != 0 ) {
if ((opcodes[i].chip == chip) &&
(opcodes[i].port == port) &&
(opcodes[i].pin == pin))
return (opcodes[i].code);
i++;
}
return ("YIKES NO OPCODE FOUND");
}
void setup() {
int i, j, chip, pin;
Serial.begin(19200);
Serial.println("Setup Start");
/* Set all controllers to input, turn on internal pullups */
for (i = 0; i < NUMBER_OF_CONTROLLERS; i++) {
mcp[i].begin(i);
previous[i] = 0;
for (j = 0; j < BITS_PER_CONTROLLER; j++) {
mcp[i].pinMode(j, INPUT);
mcp[i].pullUp(j, HIGH); // turn on a 100K pullup internally
}
}
for (i = 0; i < NUMBER_OF_CONTROLLERS; i++) {
previous[i] = mcp[i].readGPIOAB();
}
/* Flash all leds
??? Looks like 9,10,11,12,13 are Arduino ports
*/
for (i = 9; i <= 13; i++) {
pinMode(i, OUTPUT); /*??? Should 13 actually be i ??*/
flashLed(i);
}
Serial.println("Setup Done");
}
void loop() {
bool changed;
int i, j;
char tmp[100];
unsigned int mask;
changed = false;
for (i = 0; i < NUMBER_OF_CONTROLLERS; i++) {
current[i] = mcp[i].readGPIOAB();
if (current[i] != previous[i]) {
changed = true;
}
}
if (changed || first) {
/* print value on address & data bus*/
sprintf(tmp, "Address=%04x Data Hi=%02x Lo=%02x ",
current[ADDRESS_CHIP], (current[DATA_CHIP] & 0xff00) >> 8 , current[DATA_CHIP] & 0x00ff);
Serial.print(tmp);
/* find changed bus signal within soecific controller */
for (i = FIRST_BUS_SIGNAL_CONTROLLER; i < NUMBER_OF_CONTROLLERS; i++) {
mask = 0x0001;
for (j = 0; j < BITS_PER_CONTROLLER; j++) {
if (((current[i] & mask) != (previous[i] & mask)) || first) {
if (current[i] & mask) {
sprintf(tmp, "(1)");
Serial.print(tmp);
}
else {
sprintf(tmp, "(0)");
Serial.print(tmp);
}
Serial.print(strOpcode(i, j)); Serial.print(" ");
}
mask = mask << 1;
}
}
first = false;
Serial.println();
for (i = 0; i < NUMBER_OF_CONTROLLERS; i++) {
previous[i] = current[i];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.