hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
d39062a644a635edf25fc08cabc4c96a93117c22
922
cpp
C++
Pratice/repeatedString/main.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
Pratice/repeatedString/main.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
Pratice/repeatedString/main.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { cout << "Enter words "; string words; vector <string> stringHolder; int size = 0; while (size != 5) { size++; cin >> words; stringHolder.push_back(words); } sort(stringHolder.begin(), stringHolder.end()); int vSize = stringHolder.size(); if(vSize == 0) { cout << "No words "; return 1; } int wordCount = 1; words = stringHolder[0]; for(int i = 1; i < vSize; i++) { if(words != stringHolder[i]) { cout << words << " appeared " << wordCount << " amount of time\n"; wordCount = 0; words = stringHolder[i]; } wordCount++; } cout << words << " appeared " << wordCount << " amount of times \n"; return 0; }
18.44
78
0.4859
JasenRatnam
d39139f5437d8357fb6ff70daededd6f8024a64f
500
cpp
C++
ue5/Blink_game/Blink_game/PiDigitalOutput.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
ue5/Blink_game/Blink_game/PiDigitalOutput.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
ue5/Blink_game/Blink_game/PiDigitalOutput.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
#include "PiDigitalOutput.h" #include "PiIoManager.h" namespace pi_io { Pi_digital_output::Pi_digital_output(Pin pin) : pin_{ Pi_io_manager::instance().register_output(pin) } { } void Pi_digital_output::set_state(State state) { Pi_io_manager::instance().digital_write(pin_, state); } State Pi_digital_output::get_state() { return Pi_io_manager::instance().digital_read(pin_); } Pi_digital_output& Pi_digital_output::operator=(State rhs) { set_state(rhs); return *this; } }
18.518519
103
0.736
michivo
d39e2ce9546228306e6525f4563d98c23c74011a
3,217
cpp
C++
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Runtime.InteropServices // Name: UCOMIStream // C++ Typed Name: mscorlib::System::Runtime::InteropServices::UCOMIStream #include <gtest/gtest.h> #include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream.h> #include <mscorlib/System/mscorlib_System_Byte.h> #include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_STATSTG.h> namespace mscorlib { namespace System { namespace Runtime { namespace InteropServices { //Public Methods Tests // Method Read // Signature: std::vector<mscorlib::System::Byte*> pv, mscorlib::System::Int32 cb, mscorlib::System::IntPtr pcbRead TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Read_Test) { } // Method Write // Signature: std::vector<mscorlib::System::Byte*> pv, mscorlib::System::Int32 cb, mscorlib::System::IntPtr pcbWritten TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Write_Test) { } // Method Seek // Signature: mscorlib::System::Int64 dlibMove, mscorlib::System::Int32 dwOrigin, mscorlib::System::IntPtr plibNewPosition TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Seek_Test) { } // Method SetSize // Signature: mscorlib::System::Int64 libNewSize TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,SetSize_Test) { } // Method CopyTo // Signature: mscorlib::System::Runtime::InteropServices::UCOMIStream pstm, mscorlib::System::Int64 cb, mscorlib::System::IntPtr pcbRead, mscorlib::System::IntPtr pcbWritten TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,CopyTo_Test) { } // Method Commit // Signature: mscorlib::System::Int32 grfCommitFlags TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Commit_Test) { } // Method Revert // Signature: TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Revert_Test) { } // Method LockRegion // Signature: mscorlib::System::Int64 libOffset, mscorlib::System::Int64 cb, mscorlib::System::Int32 dwLockType TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,LockRegion_Test) { } // Method UnlockRegion // Signature: mscorlib::System::Int64 libOffset, mscorlib::System::Int64 cb, mscorlib::System::Int32 dwLockType TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,UnlockRegion_Test) { } // Method Stat // Signature: mscorlib::System::Runtime::InteropServices::STATSTG pstatstg, mscorlib::System::Int32 grfStatFlag TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Stat_Test) { } // Method Clone // Signature: mscorlib::System::Runtime::InteropServices::UCOMIStream ppstm TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Clone_Test) { } } } } }
27.033613
178
0.71806
brunolauze
d3a15126bd4f8b80e79078193f3df6e00b0f4e7b
763
cpp
C++
src/lib/reorder.cpp
xuzijian629/pace2020
ec39d0dd193daf9fa1306ee8508a6f80fbab3c79
[ "MIT" ]
3
2020-06-12T09:17:33.000Z
2020-09-02T19:05:50.000Z
src/lib/reorder.cpp
xuzijian629/pace2020
ec39d0dd193daf9fa1306ee8508a6f80fbab3c79
[ "MIT" ]
null
null
null
src/lib/reorder.cpp
xuzijian629/pace2020
ec39d0dd193daf9fa1306ee8508a6f80fbab3c79
[ "MIT" ]
null
null
null
#include "graph.cpp" Graph reorder(const Graph& g, const vector<int>& to) { Graph ret; int n = g.n(); for (int i = 0; i < n; i++) { assert(g.nodes.test(i)); ret.add_node(to[i]); FOR_EACH(j, at(g.adj, i)) { ret.add_edge(to[i], to[j]); } } if (g.root != -1) ret.root = to[g.root]; return ret; } pair<vector<int>, vector<int>> find_good_order(const Graph& g) { int n = g.n(); vector<pair<int, int>> deg; for (int i = 0; i < n; i++) { deg.emplace_back(at(g.adj, i).count(), i); } sort(deg.rbegin(), deg.rend()); vector<int> to(n), back(n); for (int i = 0; i < n; i++) { int v = deg[i].second; to[v] = i; back[i] = v; } return make_pair(to, back); }
25.433333
65
0.496723
xuzijian629
d3a2dcad7e91633690595747c0214b6d830471a3
9,266
cpp
C++
src/external/thread_mpi/src/p2p_send_recv.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
384
2015-01-02T19:44:15.000Z
2022-03-27T15:13:15.000Z
src/external/thread_mpi/src/p2p_send_recv.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
168
2017-05-27T14:43:32.000Z
2021-04-12T08:07:11.000Z
src/external/thread_mpi/src/p2p_send_recv.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
258
2015-01-19T11:19:57.000Z
2022-03-18T08:59:52.000Z
/* This source code file is part of thread_mpi. Written by Sander Pronk, Erik Lindahl, and possibly others. Copyright (c) 2009,2016, Sander Pronk, Erik Lindahl. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3) Neither the name of the copyright holders 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 US ''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 WE 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. If you want to redistribute modifications, please consider that scientific software is very special. Version control is crucial - bugs must be traceable. We will be happy to consider code for inclusion in the official distribution, but derived work should not be called official thread_mpi. Details are found in the README & COPYING files. */ #ifdef HAVE_TMPI_CONFIG_H #include "tmpi_config.h" #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include "impl.h" #include "p2p.h" /* point-to-point communication exported functions */ int tMPI_Send(const void* buf, int count, tMPI_Datatype datatype, int dest, int tag, tMPI_Comm comm) { struct envelope *sev; struct tmpi_thread *send_dst; struct tmpi_thread *cur = tMPI_Get_current(); struct tmpi_req_ req; #ifdef TMPI_PROFILE tMPI_Profile_count_start(cur); #endif #ifdef TMPI_TRACE tMPI_Trace_print("tMPI_Send(%p, %d, %p, %d, %d, %p)", buf, count, datatype, dest, tag, comm); #endif if (!comm) { return tMPI_Error(TMPI_COMM_WORLD, TMPI_ERR_COMM); } send_dst = tMPI_Get_thread(comm, dest); if (!send_dst) { return tMPI_Error(comm, TMPI_ERR_SEND_DEST); } sev = tMPI_Post_send(cur, comm, send_dst, (void*)buf, count, datatype, tag, FALSE); if (sev == NULL) { return TMPI_ERR_ENVELOPES; } tMPI_Req_init(&req, sev); tMPI_Wait_single(cur, &req); #ifdef TMPI_PROFILE tMPI_Profile_count_stop(cur, TMPIFN_Send); #endif return req.error; } int tMPI_Recv(void* buf, int count, tMPI_Datatype datatype, int source, int tag, tMPI_Comm comm, tMPI_Status *status) { struct envelope *rev; struct tmpi_thread *recv_src = 0; struct tmpi_thread *cur = tMPI_Get_current(); struct tmpi_req_ req; #ifdef TMPI_PROFILE tMPI_Profile_count_start(cur); #endif #ifdef TMPI_TRACE tMPI_Trace_print("tMPI_Recv(%p, %d, %p, %d, %d, %p, %p)", buf, count, datatype, source, tag, comm, status); #endif if (!comm) { return tMPI_Error(TMPI_COMM_WORLD, TMPI_ERR_COMM); } if (source != TMPI_ANY_SOURCE) { recv_src = tMPI_Get_thread(comm, source); if (!recv_src) { return tMPI_Error(comm, TMPI_ERR_RECV_SRC); } } rev = tMPI_Post_match_recv(cur, comm, recv_src, buf, count, datatype, tag, FALSE); if (rev == NULL) { return TMPI_ERR_ENVELOPES; } tMPI_Req_init(&req, rev); tMPI_Wait_single(cur, &req); tMPI_Set_status(&req, status); #ifdef TMPI_PROFILE tMPI_Profile_count_stop(cur, TMPIFN_Recv); #endif return req.error; } int tMPI_Sendrecv(const void *sendbuf, int sendcount, tMPI_Datatype sendtype, int dest, int sendtag, void *recvbuf, int recvcount, tMPI_Datatype recvtype, int source, int recvtag, tMPI_Comm comm, tMPI_Status *status) { struct envelope *rev, *sev; struct tmpi_thread *cur = tMPI_Get_current(); struct tmpi_thread *recv_src = 0; struct tmpi_thread *send_dst; struct tmpi_req_ sreq, rreq; int ret = TMPI_SUCCESS; #ifdef TMPI_PROFILE tMPI_Profile_count_start(cur); #endif #ifdef TMPI_TRACE tMPI_Trace_print("tMPI_Sendrecv(%p, %d, %p, %d, %d, %p, %d, %p, %d, %d, %p, %p)", sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status); #endif if (!comm) { return tMPI_Error(TMPI_COMM_WORLD, TMPI_ERR_COMM); } send_dst = tMPI_Get_thread(comm, dest); if (!send_dst) { return tMPI_Error(comm, TMPI_ERR_SEND_DEST); } if (source != TMPI_ANY_SOURCE) { recv_src = tMPI_Get_thread(comm, source); if (!recv_src) { return tMPI_Error(comm, TMPI_ERR_RECV_SRC); } } /* we first prepare to send */ sev = tMPI_Post_send(cur, comm, send_dst, (void*)sendbuf, sendcount, sendtype, sendtag, FALSE); if (sev == NULL) { return TMPI_ERR_ENVELOPES; } tMPI_Req_init(&sreq, sev); /* the we prepare to receive */ rev = tMPI_Post_match_recv(cur, comm, recv_src, recvbuf, recvcount, recvtype, recvtag, FALSE); if (rev == NULL) { return TMPI_ERR_ENVELOPES; } tMPI_Req_init(&rreq, rev); /* fix the pointers */ sreq.next = &rreq; sreq.prev = NULL; rreq.prev = &sreq; rreq.next = NULL; /* and wait for our requests */ do { if (tMPI_Test_multi(cur, &sreq, NULL)) { break; } tMPI_Wait_process_incoming(cur); } while (TRUE); #ifdef TMPI_PROFILE tMPI_Profile_count_stop(cur, TMPIFN_Sendrecv); #endif tMPI_Set_status(&rreq, status); ret = sreq.error; if (rreq.error != TMPI_SUCCESS) { ret = rreq.error; } return ret; } /* async */ int tMPI_Isend(const void* buf, int count, tMPI_Datatype datatype, int dest, int tag, tMPI_Comm comm, tMPI_Request *request) { struct tmpi_thread *cur = tMPI_Get_current(); struct req_list *rql = &(cur->rql); struct tmpi_req_ *rq = tMPI_Get_req(rql); struct tmpi_thread *send_dst; struct envelope *ev; #ifdef TMPI_PROFILE tMPI_Profile_count_start(cur); #endif #ifdef TMPI_TRACE tMPI_Trace_print("tMPI_Isend(%p, %d, %p, %d, %d, %p, %p)", buf, count, datatype, dest, tag, comm, request); #endif if (!comm) { tMPI_Return_req(rql, rq); return tMPI_Error(TMPI_COMM_WORLD, TMPI_ERR_COMM); } send_dst = tMPI_Get_thread(comm, dest); if (!send_dst) { tMPI_Return_req(rql, rq); return tMPI_Error(comm, TMPI_ERR_SEND_DEST); } ev = tMPI_Post_send(cur, comm, send_dst, (void*)buf, count, datatype, tag, TRUE); if (ev == NULL) { return TMPI_ERR_ENVELOPES; } tMPI_Req_init(rq, ev); *request = rq; #ifdef TMPI_PROFILE tMPI_Profile_count_stop(cur, TMPIFN_Isend); #endif return ev->error; } int tMPI_Irecv(void* buf, int count, tMPI_Datatype datatype, int source, int tag, tMPI_Comm comm, tMPI_Request *request) { struct tmpi_thread *cur = tMPI_Get_current(); struct req_list *rql = &(cur->rql); struct tmpi_req_ *rq = tMPI_Get_req(rql); struct tmpi_thread *recv_src = 0; struct envelope *ev; #ifdef TMPI_PROFILE tMPI_Profile_count_start(cur); #endif #ifdef TMPI_TRACE tMPI_Trace_print("tMPI_Irecv(%p, %d, %p, %d, %d, %p, %p)", buf, count, datatype, source, tag, comm, request); #endif if (!comm) { tMPI_Return_req(rql, rq); return tMPI_Error(TMPI_COMM_WORLD, TMPI_ERR_COMM); } if (source != TMPI_ANY_SOURCE) { recv_src = tMPI_Get_thread(comm, source); if (!recv_src) { tMPI_Return_req(rql, rq); return tMPI_Error(comm, TMPI_ERR_RECV_SRC); } } ev = tMPI_Post_match_recv(cur, comm, recv_src, buf, count, datatype, tag, TRUE); if (ev == NULL) { return TMPI_ERR_ENVELOPES; } tMPI_Req_init(rq, ev); *request = rq; #ifdef TMPI_PROFILE tMPI_Profile_count_stop(cur, TMPIFN_Irecv); #endif return ev->error; }
27.825826
87
0.642456
hejamu
d3a4b2fedbf139f9f34bc02019ee210dbf3eb967
5,781
cpp
C++
src/test/cases/multi_session.cpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
src/test/cases/multi_session.cpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
src/test/cases/multi_session.cpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <boost/uuid/uuid_io.hpp> #include "../test.hpp" #include "../../util/io.hpp" #include "../../util/util.hpp" #include "../../util/exception.hpp" #include "gen/isolevel_impls.hpp" namespace associative { namespace test { class Concurrent : public Test {}; TEST_F(Concurrent, IsolationUnsafe1) { auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); std::istringstream iss("content"); storeFile(file->getBlob("default")->getPath(true), iss); auto uuid = toString(file->uuid); env.commitSession(IsolationLevels::Full); auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.getFile(uuid); file1->removeBlob("default"); auto file2 = env2.getFile(uuid); iss.seekg(std::ios_base::beg); storeFile(file2->getBlob("default")->getPath(true), iss); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::BlobExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::BlobExclusive), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::Unsafe); ASSERT_THROW(env2.commitSession(IsolationLevels::Unsafe), CommitException) << "Expected exception"; env2.rollbackSession(); } TEST_F(Concurrent, IsolationUnsafe2) { auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); auto uuid = toString(file->uuid); env.commitSession(IsolationLevels::Full); auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.getFile(uuid); auto file2 = env2.getFile(uuid); auto blob = file2->getBlob("default"); file1->removeBlob("default"); env1.commitSession(IsolationLevels::Unsafe); std::istringstream iss("content"); storeFile(blob->getPath(true), iss); ASSERT_THROW(env2.commitSession(IsolationLevels::Unsafe), CommitException) << "Expected exception"; env2.rollbackSession(); } TEST_F(Concurrent, IsolationBlobExclusive) { auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); std::istringstream iss("content"); storeFile(file->getBlob("default")->getPath(true), iss); auto uuid = toString(file->uuid); env.commitSession(IsolationLevels::Full); auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.getFile(uuid); file1->addBlob("second", "text/plain"); auto file2 = env2.getFile(uuid); iss.seekg(std::ios_base::beg); storeFile(file2->getBlob("default")->getPath(true), iss); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::BlobExclusive); env2.commitSession(IsolationLevels::Full); } TEST_F(Concurrent, IsolationFileExclusive) { auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.createFile(); file1->addBlob("default", "text/plain"); auto file2 = env2.createFile(); file2->addBlob("default", "text/plain"); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::FileExclusive); env2.commitSession(IsolationLevels::Full); } TEST_F(Concurrent, IsolationAlmostFull) { auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.createFile(); file1->addBlob("default", "text/plain"); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::AlmostFull); env2.commitSession(IsolationLevels::Full); } TEST_F(Concurrent, IsolationFull) { // This test case is trivial (as already tested in single_session.cpp), // but is included here for completeness auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); env.commitSession(IsolationLevels::Full); } }}
34.207101
107
0.749524
larsrh
d3a597ad501e2d555aba9b07db0a2aaea043bfa0
1,601
cpp
C++
MeanMedianMode.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
41
2021-10-03T16:03:52.000Z
2021-11-14T18:15:33.000Z
MeanMedianMode.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
175
2021-10-03T10:47:31.000Z
2021-10-20T11:55:32.000Z
MeanMedianMode.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
208
2021-10-03T11:24:04.000Z
2021-10-31T17:27:59.000Z
#include<iostream> using namespace std; int main() { int invalue[]={2,4,5,2,6}; int num_value=5; float tot=0; float mean=0; for(int i=0; i<num_value; i++) { tot = tot+invalue[i]; } mean = tot/num_value; cout<<"The mean value is: "<<mean; //Median calculation float median = 0; float mid=0; if(num_value%2 == 0) { int temp=(num_value/2)-1; for(int i=0;i<num_value;i++) { if(temp==i || (temp+1)==i) { mid=mid+invalue[i]; } } mid=mid/2; cout<<"Median value is: "<<mid; } else { int temp=(num_value/2); for(int i=0;i<num_value;i++) { if(temp==i) { int mid=invalue[i]; cout<<" Median value: "<<mid; } } } //Mode calculation int i, j,z, tmp, maxCount, modeValue; int tally[num_value]; for(i=0;i<num_value;i++) { for(j=0;j<num_value-i;j++) { if(invalue[j]>invalue[j+1]) { tmp=invalue[j]; invalue[j]=invalue[j+1]; invalue[j+1]=tmp; } } } for (i = 0; i < num_value; i++) { for(z=i+1;z<num_value;z++) { if(invalue[i]==invalue[z]) { tally[i]++; } } } maxCount = 0; modeValue = 0; for (i = 0; i < num_value; i++) { if (tally[i] > maxCount) { maxCount = tally[i]; modeValue = invalue[i]; } } cout<<"\nMode value is : "<< modeValue; return 0; }
18.835294
43
0.436602
rj011
d3a676ab524adbc844d2f332ab9f5ea0a3f57335
68,589
cpp
C++
tests/utils/numeric_utils_test.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
tests/utils/numeric_utils_test.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
tests/utils/numeric_utils_test.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, All Rights Reserved /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is EMC Corporation /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "tests_shared.hpp" #include "utils/bit_utils.hpp" #include "utils/numeric_utils.hpp" #include <vector> #include <algorithm> namespace { template<typename T> iresearch::bstring encode(T value, size_t offset = 0) { typedef iresearch::numeric_utils::numeric_traits<T> traits_t; iresearch::bstring data; data.resize(traits_t::size()); traits_t::encode(traits_t::integral(value), &(data[0]), offset); return data; } } TEST(numeric_utils_test, encode32) { const irs::byte_type TYPE_MAGIC = 0; // 0 { const uint32_t value = 0; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 43 { const size_t shift = 43; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 1 byte { const uint32_t value = 0x7D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 1132 { const size_t shift = 1132; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 2 bytes { const uint32_t value = 0x3037; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0x30); expected.append(1, 0x37); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0x30); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // invalid shift = 54 { const size_t shift = 54; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 3 bytes { const uint32_t value = 0x44007D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]))); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0x44); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0x44); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0x44); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // invalid shift = 33 { const size_t shift = 33; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 4 bytes { const uint32_t value = 0x7FFFFEAF; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); expected.append(1, 0xFF); expected.append(1, 0xFE); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // invalid shift = 33 { const size_t shift = 33; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } } TEST(numeric_utils_test, i32_lexicographical_sort) { std::vector<int32_t> data = { -350, -761, -609, -343, 681, -915, -166, -727, 144, -464, 486, -527, 161, -616, -823, -283, -345, -988, 208, -550, 856, -235, 582, -357, 417, 565, -393, 658, 147, 266, 242, 990, -604, 686, 982, 287, 950, -566, 767, -25, 503, -214, 70, 351, 473, -531, -654, -795, 938, 634, -188, 437, 57, -808, -129, -793, 202, -671, -859, -808, 245, 71, -968, 533, -179, 771, -954, 839, -49, 776, -875, 761, -327, -947, 979, -129, -291, 835, 358, -796, -338, -168, -669, -181, -550, -368, 747, 321, -181, -243, -540, -974, -838, 266, -495, 77, 660, -911, -957, -418 }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); // sort values as a strings { irs::bstring lhsb, rhsb; lhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); rhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (int32_t lhs, int32_t rhs) { lhsb.resize(iresearch::numeric_utils::encode32(lhs, &(lhsb[0]))); rhsb.resize(iresearch::numeric_utils::encode32(rhs, &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, float_lexicographical_sort) { std::vector<float_t> data = { 651986.24597f, 0.f, 789897.54621f, 334163.97801f, 503825.00775f, 145063.42199f, 860891.64170f, 70621.40595f, 652100.77900f, 197530.50436f, 515243.79748f, 430713.86816f, 920883.39861f, 33127.12690f, 669809.53751f, 742514.67643f, 541261.20072f, 424864.54813f, -84206.11661f, 37734.94341f, 399434.40440f, 583076.69427f, 921670.79766f, 370855.67353f, 539653.46945f, 888530.51518f, 955485.29949f, 728637.62999f, 604241.69549f, 199548.03446f, 987841.11798f, 187679.83587f, 860653.96767f, 704908.54946f, 270492.27179f, 981837.20772f, 89069.58880f, 976493.74761f, 177264.69379f, 580679.70200f, 269226.75505f, -7565.20355f, 580326.52632f, 820924.88651f, 999188.46427f, 208690.17207f, -65341.05952f, 415085.10025f, 249832.76681f, 761120.91782f, 221577.50140f, 883788.22463f, 487001.46581f, 231184.95100f, 313349.23483f, 58377.55974f, -24389.93795f, -85784.41119f, 230454.79233f, 40357.24455f, 775261.89865f, 802026.18120f, 748156.61351f, 565290.75590f, std::numeric_limits<float_t>::max(), 59125.49834f, 81581.64508f, -77242.32905f, 358950.49929f, 927754.07961f, 816446.24556f, 491053.68666f, 25909.79241f, 319106.64948f, std::numeric_limits<float_t>::min(), 798202.10184f, 318100.23017f, 183748.53501f, 891857.49166f, 638973.58074f, -53220.76564f, 23770.88234f, 223292.54636f, 59219.16834f, -1*std::numeric_limits<float_t>::infinity(), 556780.22390f, 625542.69411f, 943141.14072f, 299615.24480f, -49206.87529f, 292463.48822f, 786073.54881f, 27863.51332f, 473998.82589f, std::numeric_limits<float_t>::infinity(), 391216.34299f, 945374.63819f, 958320.88699f, 826033.74749f, 439145.14628f, 132385.51939f, 420388.33719f, 878636.29916f, 164969.74829f, 763102.14175f }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); std::sort(data.begin(), data.end()); // sort values as a strings { iresearch::bstring lhsb, rhsb; lhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); rhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (float_t lhs, float_t rhs) { lhsb.resize(iresearch::numeric_utils::encode32(iresearch::numeric_utils::ftoi32(lhs), &(lhsb[0]))); rhsb.resize(iresearch::numeric_utils::encode32(iresearch::numeric_utils::ftoi32(rhs), &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, i64_lexicographical_sort) { std::vector<int64_t> data = { 75916234875, 52789213189, -351958887,95319743962, 79430098384, -93388245157, -49766133093, -14684623510, 81939936346, -88743499960, 20121855753, 83100432533, 51334979222, -73041310283, 61053586489, -27283259777, 66875916011, 64196723717, -63245085177, 49356623092, 4831901977, -94997824110, 558743111, 86064753122, -20505155546, 97553550685, 4184837506, -87917522122, -18266405289, 72779316345, 78725060901, -37948627940, -48856097607, 53160149963, -71272992316, -20828322249, 9522187027, -84578726831, 12441908766, 17798626822, -20379673205, -18890364139, 2691328827, -26486115883, 68027701743, 91157000176, 67489735701, -65819861863, 32420845326, 35357628656, -352937797, 3730286026, -48575671214, -57132400233, -57931671060, 79274974121, 9443962937, 51250545543, -53668161995, 63749872762, -10243160821, 69057817471, -32302480156, 55309984087, 26821242343, -47858619974, -43658945958, 13882630371, -54803336237, -42915650818, 30843782668, 81271509976, -62481641673, 58881660576, -18924990310, -67739865224, 62103715004, 86468068247, 97226357283, 79135831106, 32583755567, -51070913529, 84103329088, 55669172603, -80203080540, 76458883725, 89479791488, 71316492715, 77391498575, -40379985779, 40912438277, -74300496300, 87642158905, -64141659318, 49343408029, 53715985320, -79770447588, -74497633642, -61100778565, 20399307283 }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); // sort values as a strings { irs::bstring lhsb, rhsb; lhsb.resize(iresearch::numeric_utils::numeric_traits<int64_t>::size()); rhsb.resize(iresearch::numeric_utils::numeric_traits<int64_t>::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (int64_t lhs, int64_t rhs) { lhsb.resize(iresearch::numeric_utils::encode64(lhs, &(lhsb[0]))); rhsb.resize(iresearch::numeric_utils::encode64(rhs, &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, double_lexicographical_sort) { std::vector<double_t> data = { 0., 317957780006.32197596427145, 533992104946.63198708865418, -444498986678.43033870609027, 993156979788.63351968519088, 609230681140.54886677327979, 171177411065.98517441469486, -940116899991.46242625613810, 72774954639.73607618349422, -217026020966.94801979090461, -925157835672.21734471256721, 767751105952.89203615528161, 598978092707.21771414727797, -655278929348.69924995521980, -557099107446.66080337327942, -727673216596.09359530550129, 155929101237.99420019518314, -798911902959.88316785538717, 584117345318.25284721248450, -181281342721.20955526885090, -884976572303.55617231854991, -737155568663.56896639967755, -259257466187.35485998324811, 724842924496.55147478755167, 992409605529.35004491794391, -427341238328.88027575280530, 957748176510.32850915115723, -927854884382.26975704648986, -295874505907.23869665862932, -298929529869.43047953277383, 107495609255.27271314303983, 102434974677.13196514040789, -526793124865.17854261453196, -986666726873.56673501132370, -105069548406.20492976447797, -810126205817.85505908441500, 502725540428.76024750469264, -86871683172.35618977451520, 734071867416.64626980975562, -777490837395.88541788788765, -488500977628.16631124735172, 463763000193.87295478669598, -226003491890.61834099265670, 761498090700.01267394982869, 798989307041.74065359017842, -905445250638.50230101426239, -602929648758.34512000826426, -196635976059.65844172037134, -68902930742.55014338649350, 863617225486.60693014348248, 297576823876.04230264017466, 997953300363.36244100861365, 30857690158.69949486046075, -443412200288.57337324347970, 219426915617.39282478456983, 104728098541.83723150838038, -475445743405.93337239973870, 772038568636.42044767570703, -340372866643.76634482469705, -84314886985.49330559814968, -413809077541.25496258086290, 125388728047.43644224826081, 999016783199.74652640509723, -689317751531.17149673922523, 438800651318.76647999452729, -458810955965.33778867001542, -86436450987.32619126668488, -331705479571.45864124012116, -183427201203.73517330909854, -519768203385.06633573447649, 517973236515.17426432816976, 502506143181.82046673345401, -789732965542.81048734803241, -919346901550.58489253306058, 10824521542.91072932207525, -745318840139.22831050084360, -32521082569.15634617635810, 705549213898.15826616164216, 980234109787.37944261514556, 941403018283.37973835104133, 361903082282.23728122293823, 559399746153.22414140832803, 64887538116.83856794463404, 531879426693.48764544980956, -767469304505.48851141030365, 454718537374.73419745207494, 26781561331.25608848932017, -802390430961.91735517322894, -323002730180.97632107370362, -849713418562.76309982070844, -439276315942.06966270789023, -222411432872.71793599832707, 125254418293.59830277673821, 62915394577.62399435864016, -250289681949.78762508825754, -818758496930.24461014673328, -168764751948.77234843968057, -418952390280.99569970788234, 6143003239.36296777770061, -683268292659.55290415303451, 448388662863.70375327007088, std::numeric_limits<double_t>::infinity(), -1*std::numeric_limits<double_t>::infinity(), std::numeric_limits<double_t>::max(), std::numeric_limits<double_t>::min() }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); std::sort(data.begin(), data.end()); // sort values as a strings { typedef iresearch::numeric_utils::numeric_traits<double_t> traits_t; irs::bstring lhsb, rhsb; lhsb.resize(traits_t::size()); rhsb.resize(traits_t::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (double_t lhs, double_t rhs) { lhsb.resize(traits_t::encode(traits_t::integral(lhs), &(lhsb[0]))); rhsb.resize(traits_t::encode(traits_t::integral(rhs), &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, encode64) { const irs::byte_type TYPE_MAGIC = 0x60; // 0 { const uint64_t value = 0; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 1 byte { const uint64_t value = 0x7D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 2 bytes { const uint64_t value = 0x3037; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x30); expected.append(1, 0x37); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 3 bytes { const uint64_t value = 0x44007D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x44); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x44); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 4 bytes { const uint64_t value = 0x7FFFFEAF; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 5 bytes { const uint64_t value = uint64_t(0xCE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 6 bytes { const uint64_t value = uint64_t(0xFACE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0xFA); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 7 bytes { const uint64_t value = uint64_t(0xEFFACE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 8 bytes { const uint64_t value = uint64_t(0x2AEFFACE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } } TEST(numeric_utils_test, int_traits) { typedef irs::numeric_utils::numeric_traits<int32_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(5, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT32_C(0)); ASSERT_EQ( INT32_C(0), traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, uint_traits) { typedef irs::numeric_utils::numeric_traits<uint32_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(5, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT32_C(0)); ASSERT_EQ( INT32_C(0), traits_t::decode(encoded.c_str()) ); } { traits_t::integral_t value(0x12345678); if constexpr (irs::is_big_endian()) { ASSERT_EQ(value, traits_t::hton(value)); ASSERT_EQ(value, traits_t::ntoh(value)); } else { ASSERT_NE(value, traits_t::hton(value)); ASSERT_NE(value, traits_t::ntoh(value)); ASSERT_EQ(value, traits_t::hton(traits_t::ntoh(value))); ASSERT_EQ(value, traits_t::ntoh(traits_t::hton(value))); } } } TEST(numeric_utils_test, long_traits) { typedef irs::numeric_utils::numeric_traits<int64_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(9, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT64_C(0)); ASSERT_EQ( INT64_C(0), traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, ulong_traits) { typedef irs::numeric_utils::numeric_traits<uint64_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(9, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT64_C(0)); ASSERT_EQ( INT64_C(0), traits_t::decode(encoded.c_str()) ); } { traits_t::integral_t value(0x1234567890ABCDEF); if constexpr (irs::is_big_endian()) { ASSERT_EQ(value, traits_t::hton(value)); ASSERT_EQ(value, traits_t::ntoh(value)); } else { ASSERT_NE(value, traits_t::hton(value)); ASSERT_NE(value, traits_t::ntoh(value)); ASSERT_EQ(value, traits_t::hton(traits_t::ntoh(value))); ASSERT_EQ(value, traits_t::ntoh(traits_t::hton(value))); } } } TEST(numeric_utils_test, float_t_traits) { typedef float_t type; typedef irs::numeric_utils::numeric_traits<type> traits_t; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::inf().c_str()) ); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::ninf().c_str()) ); ASSERT_EQ(5, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::infinity()); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(-1*std::numeric_limits<type>::infinity()); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode((float_t)0.f); ASSERT_EQ( 0.f, traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, double_t_traits) { typedef double_t type; typedef irs::numeric_utils::numeric_traits<type> traits_t; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::inf().c_str()) ); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::ninf().c_str()) ); ASSERT_EQ(9, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::infinity()); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(-1*std::numeric_limits<type>::infinity()); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode((double_t)0.); ASSERT_EQ( 0., traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, float_traits) { typedef float type; typedef irs::numeric_utils::numeric_traits<type> traits_t; } TEST(numeric_utils_test, double_traits) { typedef double type; typedef irs::numeric_utils::numeric_traits<type> traits_t; } TEST(numeric_utils_test, long_double_traits) { typedef long double type; typedef irs::numeric_utils::numeric_traits<type> traits_t; }
35.030133
183
0.641488
geenen124
d3affc575e085caa497c7f39f735e3358a5de4a9
528
cpp
C++
leetcode/algorithm/16.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
leetcode/algorithm/16.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
leetcode/algorithm/16.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int min_val = 1e9+7, ans = 1e9+7; sort(nums.begin(), nums.end()); for (int m=0; m<nums.size(); ++m) { int l = 0, r = nums.size()-1; while (l < m && m < r) { int sum = nums[l] + nums[m] + nums[r]; if (abs(target - sum) < min_val) { min_val = abs(target - sum); ans = sum; } else if (target == sum) { return sum; } if (sum < target) { l++; } else { r--; } } } return ans; } };
19.555556
53
0.49053
juseongkr
d3b3c82fc2ff57d1185046fa929d554d98864cae
8,855
cpp
C++
gameEngine/gameEngine/SceneDirector.cpp
ComputerScienceTrolls/simpleGameGL
81e25f690f5825bf633685e9d7d2771a3d61f4c7
[ "MIT" ]
null
null
null
gameEngine/gameEngine/SceneDirector.cpp
ComputerScienceTrolls/simpleGameGL
81e25f690f5825bf633685e9d7d2771a3d61f4c7
[ "MIT" ]
5
2017-10-06T21:39:20.000Z
2018-01-29T13:23:19.000Z
gameEngine/gameEngine/SceneDirector.cpp
ComputerScienceTrolls/simpleGameGL
81e25f690f5825bf633685e9d7d2771a3d61f4c7
[ "MIT" ]
null
null
null
#include "SceneDirector.h" #include <iostream> std::auto_ptr<SceneDirector> SceneDirector::instance; //default width and height int WIDTH = 800; int HEIGHT = 600; double lastTime = glfwGetTime(); int nbFrames = 0; //void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); SceneDirector::SceneDirector() { glfwInit(); //initiate openAl component alutInit(NULL, 0); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow(WIDTH, HEIGHT, "HelloWorld", nullptr, nullptr); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; glewInit(); glGetError(); // Call it once to catch glewInit() bug, all other errors are now from our application. ResourceManager::LoadShader("shaders/sprite.vs", "shaders/sprite.frag", nullptr, "sprite"); Shader temp1 = ResourceManager::GetShader("sprite"); Renderer = new SpriteRenderer(temp1); //Renderer = temp; glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(800), static_cast<GLfloat>(600), 0.0f, -1.0f, 1.0f); ResourceManager::GetShader("sprite").Use().SetInteger("sprite", 0); ResourceManager::GetShader("sprite").SetMatrix4("projection", projection); } /* void SceneDirector::Update(float delta) { currentScene->Update(delta); //check sensors for (int i = 0; i < sensors.size(); i++) { sensors.at(i)->sense(); } // Measure speed double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0) { // If last prinf() was more than 1 sec ago // printf and reset timer printf("%f ms/frame\n", 1000.0 / double(nbFrames)); nbFrames = 0; lastTime += 1.0; } } */ void SceneDirector::checkSensors() { for (int i = 0; i < sensors.size(); i++) { sensors.at(i)->sense(); } } void SceneDirector::pauseScene(AbstractScene * s) { //find scene given bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s == scenes.at(i)) { found = true; scenes[i]->setActive(false); } } if (!found) { std::cout << "pauseSence: no scene found"; } } void SceneDirector::unpauseScene(AbstractScene * s) { //find scene given bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s == scenes.at(i)) { found = true; scenes[i]->setActive(true); } } if (!found) { std::cout << "pauseSence: no scene found"; } } SceneDirector* SceneDirector::getInstance() { if (instance.get() == nullptr) { instance.reset(new SceneDirector()); } return instance.get(); } void SceneDirector::addScene(AbstractScene *s) { scenes.push_back(s); //if scenes is empy, make new scene the currentScene if (scenes.size() < 2) { currentScene = s; currentScene->setWindow(window); currentScene->setRenderer(Renderer); } } AbstractScene* SceneDirector::getScene(std::string) { return nullptr; } AbstractScene* SceneDirector::getScene(int i) { return scenes.at(i); } void SceneDirector::setSceneBackground(std::string n) { currentScene->setBackground(n.c_str()); } void SceneDirector::removeScene(std::string n) { //get index of collider int index = -1; for (int i = 0; i < this->scenes.size(); i++) { if (this->scenes[i]->getName() == n) { index = i; } } //if found remove it from the vector if (index != -1) { std::cout << "deleting " << scenes.at(index)->getName(); this->scenes.erase(scenes.begin() + index); } else { std::cout << "scene with the name of " << n << " not found"; } } void SceneDirector::removeScene(int index) { if (index > -1 && index <= sensors.size() - 1) { this->sensors.erase(sensors.begin() + index); } else { std::cout << "index is not in range"; } } //sets the given scene, if it's not already in scene list, add it void SceneDirector::setScene(AbstractScene *s) { currentScene->Stop(); currentScene = s; currentScene->setWindow(window); currentScene->setRenderer(Renderer); currentScene->Init(); currentScene->reset(); currentScene->Start(); bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s = scenes.at(i)) { found = true; } } if (!found) { scenes.push_back(s); } } //sets to scene, but only pauses old scene, if scene doens't exist in scenes, add it. void SceneDirector::setScenePause(AbstractScene * s) { //if scene is already the currentScene, do nothing if (currentScene != s) { currentScene->setActive(false); currentScene = s; currentScene->setWindow(window); currentScene->setRenderer(Renderer); currentScene->Start(); bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s = scenes.at(i)) { found = true; } } if (!found) { scenes.push_back(s); } } } void SceneDirector::nextScene() { int currentIndex = -1; for (int i = 0; i < scenes.size(); i++) { if (currentScene == scenes.at(i)) { currentIndex = i; } } //make sure currentIndex and currentIndex+1 is in range if (currentIndex != -1 && (currentIndex) < scenes.size()-1) { //stop currentScene currentScene->Stop(); //assign new currentScene currentScene = scenes.at(currentIndex + 1); //init new currentScene currentScene->setWindow(window); currentScene->setRenderer(Renderer); //currentScene->Init(); currentScene->reset(); currentScene->Start(); } else { std::cout << "Next: there is no Scene to jump to"; std::cout << "\ncurrentIndex: " << currentIndex; std::cout << "\nsize: " << scenes.size(); } } void SceneDirector::previousScene() { int currentIndex = -1; for (int i = 0; i < scenes.size(); i++) { if (currentScene == scenes.at(i)) { currentIndex = i; } } //make sure currentIndex and currentIndex-1 is in range if (currentIndex != -1 && currentIndex - 1 > -1) { //stop currentScene currentScene->Stop(); //assign new currentScene currentScene = scenes.at(currentIndex - 1); //init new currentScene currentScene->setWindow(window); currentScene->setRenderer(Renderer); currentScene->Init(); currentScene->reset(); currentScene->Start(); } else { std::cout << "Previous: there is no Scene to jump to"; std::cout << "\ncurrentIndex: " << currentIndex; std::cout << "\nsize: " << scenes.size(); } } void SceneDirector::Start() { // OpenGL configuration glViewport(0, 0, 800, 600); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // DeltaTime variables GLfloat deltaTime = 0.0f; GLfloat lastFrame = 0.0f; //tell currentScene to set to active currentScene->Start(); while (!glfwWindowShouldClose(window)) { // Calculate delta time double currentFrame = glfwGetTime(); deltaTime = float(currentFrame) - lastFrame; lastFrame = float(currentFrame); glfwPollEvents(); // Update Game state this->Update(deltaTime); // Render glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); this->Render(); glfwSwapBuffers(window); } } void SceneDirector::Render() { currentScene->Render(); } void SceneDirector::addSensor(AbstractSensor * s) { sensors.push_back(s); } void SceneDirector::addObserver(AbstractObserver * o) { observers.push_back(o); } void SceneDirector::removeSensor(std::string name) { int index = -1; for (int i = 0; i < this->sensors.size(); i++) { if (this->sensors[i]->getName() == name) { index = i; } } //if found remove it from the vector if (index != -1) { std::cout << "deleting " << this->sensors.at(index)->getName(); this->sensors.erase(sensors.begin() + index); } else { std::cout << "Sensor with the name of " << name << " not found"; } } void SceneDirector::removeSensor(int index) { if (index > -1 && index <= sensors.size() - 1) { sensors.erase(sensors.begin() + index); } else { std::cout << "index is not in range"; } } void SceneDirector::removeObserver(std::string name) { //get index of collider int index = -1; for (int i = 0; i < observers.size(); i++) { if (observers[i]->getName() == name) { index = i; } } //if found remove it from the vector if (index != -1) { std::cout << "deleting " << observers.at(index)->getName(); observers.erase(observers.begin() + index); } else { std::cout << "observer with the name of " << name << " not found"; } } void SceneDirector::removeObserver(int index) { if (index > -1 && index <= sensors.size() - 1) { observers.erase(observers.begin() + index); } else { std::cout << "index is not in range"; } } size_t SceneDirector::getNumberOfScenes() { return scenes.size(); } AbstractScene* SceneDirector::getCurrentScene() { return this->currentScene; } SceneDirector::~SceneDirector() { glfwTerminate(); ResourceManager::Clear(); //delete items that are on heap that is used by openal alutExit(); }
19.809843
114
0.658724
ComputerScienceTrolls
d3b7e84eb305cec0b6ae45cfd9546f1a1dc425b1
3,515
hpp
C++
src/Base/Policies/DataStreamBuffer.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2017-02-17T13:01:13.000Z
2017-02-17T13:01:13.000Z
src/Base/Policies/DataStreamBuffer.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
null
null
null
src/Base/Policies/DataStreamBuffer.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2018-07-23T00:05:58.000Z
2018-07-23T00:05:58.000Z
/*! * \file DataStreamBuffer.hpp * \brief DataStream buffering policies * * \author mstefanc * \date 06-07-2010 */ #ifndef DATASTREAMBUFFER_HPP_ #define DATASTREAMBUFFER_HPP_ #include <queue> #include <stdexcept> namespace Base { /*! * Buffering policies for DataStream. * * Every buffering policy should have form: * \code * template <class T> * class PolicyName { * protected: * // store data in some internal container * void store(const T & t); * * // retrieve data from internal container * T retrieve(); * }; * \endcode * * There are some predefined simple policies (like FIFO queue, keeping only newest or oldest data). */ namespace DataStreamBuffer { /*! * \brief Buffering policy - FIFO queue. * * All items are stored in queue, so that none of them is missed during processing. */ template <class T> class Queue { public: bool empty() const { return buffer.empty(); } protected: /*! * Push data on the end of queue * \param t data to be stored */ void store(const T & t) { buffer.push(t); } /*! * Get first element from queue * \return First element from queue * \throw exception queue is empty */ T retrieve() { if (buffer.size() > 0) { T t = buffer.front(); buffer.pop(); return t; } else { /// \todo Throw correct exception throw std::runtime_error("Queue: Empty buffer!"); // throwing disabled until scopeLock will be implemented in DataStream } } private: //// FIFO queue std::queue<T> buffer; }; /*! * \brief Buffering policy - keep only the newest data. * * Only the newest data is remembered, when data comes before reading previous one, * older item is lost. */ template <class T> class Newest { public: /*! * Clears internal flags state */ Newest() { fresh = false; } bool empty() const { return !fresh; } protected: /*! * Remember new data. * \param t data to be remembered */ void store(const T & t) { item = t; fresh = true; } /*! * Return remembered data (if it's fresh). * * If there is no new data since last read, exception is thrown. * * \return remembered data * \throw exception there is no fresh data since last read */ T retrieve() { if (fresh) { fresh = false; return item; } else { /// \todo Throw correct exception throw std::runtime_error("Newest: Fresh data not available!"); } } private: /// newest data T item; /// data freshness flag bool fresh; }; /*! * \brief Buffering policy - keep only the oldest data * * Only the oldest data is remembered, when data comes before reading previous one, * newer item is lost. */ template <class T> class Oldest { public: /*! * Clears internal flags state */ Oldest() { fresh = false; } protected: /*! * Remember new data * * If there is older, unread data then new one is lost. * * \param t data to be remembered */ void store(const T & t) { if (!fresh) { item = t; fresh = true; } } /*! * Return remembered data (if it's fresh). * * If there is no data since last read, exception is thrown. * * \return remembered data * \throw exception there is no fresh data since last read */ T retrieve() { if (fresh) { fresh = false; return item; } else { /// \todo Throw correct exception throw std::runtime_error("Oldest: No data available!"); } } private: /// oldest data T item; /// data freshness flag bool fresh; }; } //: DataStreamBuffer } //: Base #endif /* DATASTREAMBUFFER_HPP_ */
17.84264
99
0.64239
mlaszko
d3b86882d6d10f4438be7e15f1ab5bc01bf2d4da
4,636
cpp
C++
Source/HardTime2/Private/Missions.cpp
ThomasWilliamWallace/PrisonGame
243ffd5d587086775c094d3dc72ff29987aa9bce
[ "MIT" ]
1
2018-12-30T15:35:50.000Z
2018-12-30T15:35:50.000Z
Source/HardTime2/Private/Missions.cpp
ThomasWilliamWallace/PrisonGame
243ffd5d587086775c094d3dc72ff29987aa9bce
[ "MIT" ]
null
null
null
Source/HardTime2/Private/Missions.cpp
ThomasWilliamWallace/PrisonGame
243ffd5d587086775c094d3dc72ff29987aa9bce
[ "MIT" ]
null
null
null
#include "Missions.h" #include "PlayerData.h" #include "SimWorld.h" #include "Constants.h" #include "ActorItem.h" MissionClass::MissionClass(RandomMission r, UPlayerData* playerPtr): MissionClass(playerPtr) {} MissionClass::MissionClass(UPlayerData* owner): m_mission(GetRandomMission()), m_owner(owner) { m_mission = EMissions::bringItemToRoom; m_itemType = EItemType::ball; m_locationClass = LocationClass(ELocations::gym); return; assert(m_owner != nullptr); switch (m_mission) { case EMissions::noMission: return; case EMissions::increaseAgility: m_objective = owner->pStats->getAgility(); break; case EMissions::increaseStrength: m_objective = owner->pStats->getStrength(); break; case EMissions::increaseIntelligence: m_objective = owner->pStats->getIntelligence(); break; case EMissions::bringItemToRoom: m_itemType = GetRandomItemType(); m_locationClass = GetRandomLocation(); return; default: ThrowException("Selected an invalid mission type."); } m_objective += 3; //todo ensure that the mission is achievable, ie 100 or below } MissionClass::MissionClass(EMissions mission, UPlayerData* owner, double objective): m_mission(mission), m_owner(owner), m_objective(objective) { assert(m_owner!=nullptr); } MissionClass::MissionClass(EMissions mission, UPlayerData* owner, EItemType itemType, ELocations location): m_mission(mission), m_owner(owner), m_itemType(itemType), m_locationClass(location) { assert(m_owner!=nullptr); } MissionClass::MissionClass(const MissionClass& missionClass): m_mission(missionClass.m_mission), m_owner(missionClass.m_owner), m_objective(missionClass.m_objective), m_itemType(missionClass.m_itemType), m_locationClass(missionClass.m_locationClass) { assert(m_owner!=nullptr); } bool MissionClass::IsMissionComplete(USimWorld &world) { switch (m_mission) { case EMissions::increaseAgility: return (m_objective <= m_owner->pStats->getAgility()); case EMissions::increaseStrength: return (m_objective <= m_owner->pStats->getStrength()); case EMissions::increaseIntelligence: return (m_objective <= m_owner->pStats->getIntelligence()); case EMissions::bringItemToRoom: for (auto &item : world.items) { if ((item->m_itemType == m_itemType) && (item->m_locationClass.location == m_locationClass.location) && (item->m_carryingPlayer == nullptr)) { return true; } } return false; case EMissions::noMission: return false; } return false; } std::string MissionClass::MissionNarrative() { switch (m_mission) { case EMissions::noMission: return "No Mission\n"; case EMissions::increaseAgility: return "Mission: " + m_owner->CharacterName() + " must " + MissionName() + " to " + FormatDouble(m_objective) + ". (current=" + FormatDouble(m_owner->pStats->getAgility()) + ")"; case EMissions::increaseStrength: return "Mission: " + m_owner->CharacterName() + " must " + MissionName() + " to " + FormatDouble(m_objective) + ". (current=" + FormatDouble(m_owner->pStats->getStrength()) + ")"; case EMissions::increaseIntelligence: return "Mission: " + m_owner->CharacterName() + " must " + MissionName() + " to " + FormatDouble(m_objective) + ". (current=" + FormatDouble(m_owner->pStats->getIntelligence()) + ")"; case EMissions::bringItemToRoom: return "Mission: " + m_owner->CharacterName() + " must bring a " + ItemTypeToString(m_itemType) + " to the " + m_locationClass.ToString() + "."; } ThrowException("ERROR: MISSION TYPE NOT RECOGNISED"); } std::string MissionClass::MissionName() { switch(m_mission) { case (EMissions::increaseAgility): return "increase agility"; case (EMissions::increaseStrength): return "increase strength"; case (EMissions::increaseIntelligence): return "increase intelligence"; case (EMissions::bringItemToRoom): return "bring item to room"; case (EMissions::noMission): return "no mission"; } ThrowException("UnrecognisedMission"); } EMissions GetRandomMission() { int random = rand() % 100; if (random<25) return EMissions::increaseStrength; else if (random<50) return EMissions::increaseAgility; else if (random<75) return EMissions::increaseIntelligence; else return EMissions::bringItemToRoom; }
31.972414
195
0.668464
ThomasWilliamWallace
d3bae8e4df2382db44e5a5bbbd5a4f982daf7872
789
cpp
C++
src/MulticopterPlugin/FFCalc_CutoffCoef.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
91
2015-01-29T11:03:42.000Z
2022-02-13T07:34:04.000Z
src/MulticopterPlugin/FFCalc_CutoffCoef.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
213
2015-01-26T06:21:15.000Z
2020-07-23T05:51:30.000Z
src/MulticopterPlugin/FFCalc_CutoffCoef.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
71
2015-01-06T02:32:05.000Z
2020-12-01T03:42:25.000Z
/** @author Japan Atomic Energy Agency */ #include "MulticopterPluginHeader.h" namespace Multicopter { namespace FFCalc { CutoffCoef::CutoffCoef ( const double cutoffDistance, const double normMiddleValue) : _impl (CutoffCoefImpl::createInstance (cutoffDistance, normMiddleValue)) { } CutoffCoef::CutoffCoef (CutoffCoef&& rhs) : _impl (std::move(rhs._impl)) { } CutoffCoef::~CutoffCoef() { delete _impl; } void CutoffCoef::initialize ( const double cutoffDistance, const double normMiddleValue) { delete _impl; _impl = CutoffCoefImpl::createInstance (cutoffDistance, normMiddleValue); return; } double CutoffCoef::get ( const Vector3& point, const Vector3& normalDir, const GaussTriangle3d& tri) const { return _impl->get (point, normalDir, tri); } }}
18.785714
77
0.737643
roto5296
d3c0eaa6d16dbbf92473213172a880fafb0628d8
742
hh
C++
restore_ios.hh
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
restore_ios.hh
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
restore_ios.hh
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
/* git-junction * Copyright (c) 2016-2017 by Pauli Saksa * * Licensed under The MIT License, see file LICENSE.txt in this source tree. */ #ifndef GIT_JUNCTION_RESTORE_IOS_HEADER #define GIT_JUNCTION_RESTORE_IOS_HEADER #include <ios> class restore_ios { std::ios &io; std::ios::fmtflags flags; std::ios::char_type fill; std::streamsize width; std::streamsize precision; public: restore_ios(std::ios &_io) : io{_io}, flags{io.flags()}, fill{io.fill()}, width{io.width()}, precision{io.precision()} { } ~restore_ios(void) { io.flags(flags); io.fill(fill); io.width(width); io.precision(precision); } }; #endif
18.55
76
0.59973
psaksa
d3c2cdd1cd9682a3a579a1692e817e5631ea6c7f
642
hpp
C++
lib/hargui/include/part.hpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
2
2020-09-11T18:11:10.000Z
2020-10-20T17:25:38.000Z
lib/hargui/include/part.hpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
null
null
null
lib/hargui/include/part.hpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
null
null
null
// // Created by Johannes on 17.07.2020. // #ifndef HAR_GUI_PART_HPP #define HAR_GUI_PART_HPP #include <gtkmm/box.h> #include <gtkmm/button.h> #include <gtkmm/image.h> #include <gtkmm/label.h> namespace har::gui_ { class part : public Gtk::Button { private: Gtk::Box _box; Gtk::Image _image; Gtk::Label _label; Cairo::RefPtr<Cairo::Surface> _surface; public: part(); void set_image(Glib::RefPtr<Gdk::Pixbuf> & pixbuf); void set_label(const std::string & label); ~part() noexcept override; }; } #endif //HAR_GUI_PART_HPP
18.882353
60
0.590343
Ocead
d3c3047d5e550d91d427e58f93e746b5edf461a0
12,468
cpp
C++
LibCarla/source/carla/sumonetwork/SumoNetwork.cpp
AdaCompNUS/summ
a91f0c06202fb6a4100249882eec69ddf5bc7656
[ "MIT" ]
103
2020-03-10T04:21:50.000Z
2022-03-29T13:26:57.000Z
LibCarla/source/carla/sumonetwork/SumoNetwork.cpp
AdaCompNUS/summ
a91f0c06202fb6a4100249882eec69ddf5bc7656
[ "MIT" ]
12
2020-04-11T11:36:01.000Z
2021-12-09T11:35:56.000Z
LibCarla/source/carla/sumonetwork/SumoNetwork.cpp
AdaCompNUS/summ
a91f0c06202fb6a4100249882eec69ddf5bc7656
[ "MIT" ]
8
2020-11-21T07:47:12.000Z
2022-03-25T13:41:05.000Z
#include "SumoNetwork.h" #include "carla/geom/Math.h" #include "carla/geom/Triangulation.h" #include <boost/algorithm/string.hpp> #include <pugixml/pugixml.hpp> #include <string> #include <sstream> #include <fstream> namespace carla { namespace sumonetwork { static std::vector<geom::Vector2D> parse_shape_list(const std::string& s) { if (s.empty()) return {}; std::vector<std::string> split_list; boost::split( split_list, s, boost::is_any_of(", "), boost::token_compress_on); std::vector<geom::Vector2D> position_list; for (size_t i = 0; i < split_list.size(); i += 2) { position_list.emplace_back( std::stof(split_list[i + 1]), // Swap for SUMO -> CARLA. std::stof(split_list[i])); // Swap for SUMO -> CARLA. } return position_list; } static geom::Vector2D parse_coordinates(const std::string& s) { if (s.empty()) return geom::Vector2D(0, 0); std::vector<std::string> split_list; boost::split( split_list, s, boost::is_any_of(","), boost::token_compress_on); // Swap x, y for SUMO -> CARLA. return geom::Vector2D(std::stof(split_list[1]), std::stof(split_list[0])); } static std::pair<geom::Vector2D, geom::Vector2D> parse_bounds(const std::string& s) { std::vector<std::string> split_list; boost::split( split_list, s, boost::is_any_of(","), boost::token_compress_on); // Swap x, y for SUMO -> CARLA. return std::make_pair( geom::Vector2D(std::stof(split_list[1]), std::stof(split_list[0])), geom::Vector2D(std::stof(split_list[3]), std::stof(split_list[2]))); } static std::vector<std::string> parse_string_list(const std::string& s) { if (s.empty()) return {}; std::vector<std::string> split_list; boost::split( split_list, s, boost::is_any_of(" "), boost::token_compress_on); return split_list; } SumoNetwork SumoNetwork::Load(const std::string& file) { std::ifstream ifs; ifs.open(file, std::ios::in); std::ostringstream ss; ss << ifs.rdbuf(); ifs.close(); pugi::xml_document xml; xml.load_string(ss.str().c_str()); SumoNetwork sumo_network; pugi::xml_node net_node = xml.child("net"); pugi::xml_node location_node = net_node.child("location"); sumo_network._offset = parse_coordinates(location_node.attribute("netOffset").value()); std::pair<geom::Vector2D, geom::Vector2D> bounds = parse_bounds(location_node.attribute("convBoundary").value()); sumo_network._bounds_min = bounds.first; sumo_network._bounds_max = bounds.second; // origBoundary: LonLat -> (parse_bounds swaps) -> LatLon std::pair<geom::Vector2D, geom::Vector2D> originalBounds = parse_bounds(location_node.attribute("origBoundary").value()); sumo_network._original_bounds_min = originalBounds.first; sumo_network._original_bounds_max = originalBounds.second; for (pugi::xml_node edge_node : net_node.children("edge")) { Edge edge; edge.id = edge_node.attribute("id").value(); edge.from = edge_node.attribute("from").value(); edge.to = edge_node.attribute("to").value(); edge.priority = edge_node.attribute("priority").as_int(); std::string function = edge_node.attribute("function").value(); if (function == "internal") edge.function = Function::Internal; else if (function == "connector") edge.function = Function::Connector; else if (function == "crossing") edge.function = Function::Crossing; else if (function == "walkingarea") edge.function = Function::WalkingArea; else edge.function = Function::Normal; // Temp vector required because order of lanes read do not necessarily match // order of their indexes. std::vector<Lane> lanes_temp; for (pugi::xml_node lane_node : edge_node.children("lane")) { Lane lane; lane.id = lane_node.attribute("id").value(); lane.index = lane_node.attribute("index").as_uint(); lane.speed = lane_node.attribute("speed").as_float(); lane.length = lane_node.attribute("length").as_float(); lane.shape = parse_shape_list(lane_node.attribute("shape").value()); lanes_temp.emplace_back(std::move(lane)); } edge.lanes.resize(lanes_temp.size()); // TODO: Check if sorting passes or there are invalid instances, e.g. indexes // that exceed the bounds of the number of lanes. for (size_t i = 0; i < lanes_temp.size(); i++) { edge.lanes[lanes_temp[i].index] = std::move(lanes_temp[i]); } sumo_network._edges.emplace(edge.id, std::move(edge)); } for (pugi::xml_node junction_node : net_node.children("junction")) { Junction junction; junction.id = junction_node.attribute("id").value(); junction.x = junction_node.attribute("y").as_float(); // Swap for SUMO -> CARLA. junction.y = junction_node.attribute("x").as_float(); // Swap for SUMO -> CARLA. junction.inc_lanes = parse_string_list(junction_node.attribute("incLanes").value()); junction.int_lanes = parse_string_list(junction_node.attribute("intLanes").value()); junction.shape = parse_shape_list(junction_node.attribute("shape").value()); sumo_network._junctions.emplace(junction.id, std::move(junction)); } for (pugi::xml_node connection_node : net_node.children("connection")) { Connection connection; connection.from = connection_node.attribute("from").value(); connection.to = connection_node.attribute("to").value(); connection.from_lane = connection_node.attribute("fromLane").as_uint(); connection.to_lane = connection_node.attribute("toLane").as_uint(); connection.via = connection_node.attribute("via").value(); sumo_network._connections.emplace_back(std::move(connection)); } sumo_network.Build(); return sumo_network; } void SumoNetwork::Build() { std::vector<rt_value_t> index_entries; for (const auto& edge_entry : _edges) { const Edge& edge = edge_entry.second; for (const Lane& lane : edge.lanes) { for (size_t i = 0; i < lane.shape.size() - 1; i++) { index_entries.emplace_back( rt_segment_t( rt_point_t(lane.shape[i].x, lane.shape[i].y), rt_point_t(lane.shape[i + 1].x, lane.shape[i + 1].y)), std::make_tuple(edge.id, lane.index, i)); } _lane_to_parent_edge_map[lane.id] = std::make_pair(edge.id, lane.index); _outgoing_connections_map.emplace(lane.id, std::vector<size_t>()); } } _segments_index = rt_tree_t(index_entries); for (size_t i = 0; i < _connections.size(); i++) { const Connection& connection = _connections[i]; if (!connection.via.empty()){ _internal_edge_to_connection_map[connection.via] = i; } _outgoing_connections_map.at(_edges[connection.from].lanes[connection.from_lane].id).emplace_back(i); } } geom::Vector2D SumoNetwork::GetRoutePointPosition(const RoutePoint& route_point) const { const geom::Vector2D& start = _edges.at(route_point.edge).lanes[route_point.lane].shape[route_point.segment]; const geom::Vector2D& end = _edges.at(route_point.edge).lanes[route_point.lane].shape[route_point.segment + 1]; return start + route_point.offset * (end - start).MakeUnitVector(); } RoutePoint SumoNetwork::GetNearestRoutePoint(const geom::Vector2D& position) const { std::vector<rt_value_t> results; _segments_index.query(boost::geometry::index::nearest(rt_point_t(position.x, position.y), 1), std::back_inserter(results)); rt_value_t& result = results[0]; geom::Vector2D segment_start( boost::geometry::get<0, 0>(result.first), boost::geometry::get<0, 1>(result.first)); geom::Vector2D segment_end( boost::geometry::get<1, 0>(result.first), boost::geometry::get<1, 1>(result.first)); geom::Vector2D direction = (segment_end - segment_start).MakeUnitVector(); float t = geom::Vector2D::DotProduct( position - segment_start, direction); t = std::max(0.0f, std::min((segment_end - segment_start).Length(), t)); return RoutePoint{ std::get<0>(result.second), std::get<1>(result.second), std::get<2>(result.second), t}; } std::vector<RoutePoint> SumoNetwork::GetNextRoutePoints(const RoutePoint& route_point, float distance) const { const Edge& edge = _edges.at(route_point.edge); const Lane& lane = edge.lanes[route_point.lane]; const geom::Vector2D& segment_start = lane.shape[route_point.segment]; const geom::Vector2D& segment_end = lane.shape[route_point.segment + 1]; float segment_length = (segment_end - segment_start).Length(); if (route_point.offset + distance <= segment_length) { return { {route_point.edge, route_point.lane, route_point.segment, route_point.offset + distance} }; } else if (route_point.segment < lane.shape.size() - 2) { return GetNextRoutePoints( RoutePoint{route_point.edge, route_point.lane, route_point.segment + 1, 0}, distance - (segment_length - route_point.offset)); } else { std::vector<RoutePoint> next_route_points; for (size_t connection_index : _outgoing_connections_map.at(lane.id)) { const Connection& connection = _connections[connection_index]; if (connection.via == "") { std::vector<RoutePoint> results = GetNextRoutePoints( RoutePoint{connection.to, connection.to_lane, 0, 0}, distance - (segment_length - route_point.offset)); next_route_points.insert(next_route_points.end(), results.begin(), results.end()); } else { const std::pair<std::string, uint32_t>& lane_parent = _lane_to_parent_edge_map.at(connection.via); std::vector<RoutePoint> results = GetNextRoutePoints( RoutePoint{lane_parent.first, lane_parent.second, 0, 0}, distance - (segment_length - route_point.offset)); next_route_points.insert(next_route_points.end(), results.begin(), results.end()); } } return next_route_points; } } std::vector<std::vector<RoutePoint>> SumoNetwork::GetNextRoutePaths(const RoutePoint& route_point, size_t num_points, float interval) const { if (num_points == 0) return {{route_point}}; std::vector<std::vector<RoutePoint>> result; for (const RoutePoint& next_route_point : GetNextRoutePoints(route_point, interval)) { std::vector<std::vector<RoutePoint>> next_route_paths = GetNextRoutePaths(next_route_point, num_points - 1, interval); result.reserve(next_route_paths.size()); for (const std::vector<RoutePoint>& next_route_path : next_route_paths) { result.emplace_back(); result.back().reserve(1 + next_route_path.size()); result.back().emplace_back(route_point); result.back().insert(result.back().end(), next_route_path.begin(), next_route_path.end()); } } return result; } occupancy::OccupancyMap SumoNetwork::CreateOccupancyMap() const { occupancy::OccupancyMap occupancy_map; for (const auto& edge_entry : _edges) { const Edge& edge = edge_entry.second; for (const Lane& lane : edge.lanes) { // Extra 0.10m to close any gap between lanes. occupancy_map = occupancy_map.Union(occupancy::OccupancyMap(lane.shape, 4.10f)); } } for (const auto& junction_entry : _junctions) { const Junction& junction = junction_entry.second; occupancy_map = occupancy_map.Union(occupancy::OccupancyMap(junction.shape)); } return occupancy_map; } occupancy::OccupancyMap SumoNetwork::CreateRoadmarkOccupancyMap() const { occupancy::OccupancyMap roadmark_occupancy_map; for (const auto& edge_entry : _edges) { const Edge& edge = edge_entry.second; for (const Lane& lane : edge.lanes) { roadmark_occupancy_map = roadmark_occupancy_map.Union(occupancy::OccupancyMap(lane.shape, 4.00f, 0.10f)); } } occupancy::OccupancyMap junction_occupancy_map; for (const auto& junction_entry : _junctions) { const Junction& junction = junction_entry.second; junction_occupancy_map = junction_occupancy_map.Union(occupancy::OccupancyMap(junction.shape)); } return roadmark_occupancy_map.Difference(junction_occupancy_map); } segments::SegmentMap SumoNetwork::CreateSegmentMap() const { std::vector<geom::Segment2D> segments; for (const auto& edge_entry : _edges) { const Edge& edge = edge_entry.second; for (const Lane& lane : edge.lanes) { for (size_t i = 0; i < lane.shape.size() - 1; i++) { segments.emplace_back(lane.shape[i], lane.shape[i + 1]); } } } return segments::SegmentMap(std::move(segments)); } } }
38.245399
141
0.691129
AdaCompNUS
d3c33632c61a5a6cb488342dcdca615fd04ae0e1
548
cpp
C++
AcWing/LeetCode究极班/56.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
7
2019-02-25T13:15:00.000Z
2021-12-21T22:08:39.000Z
AcWing/LeetCode究极班/56.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
null
null
null
AcWing/LeetCode究极班/56.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
1
2019-04-03T06:12:46.000Z
2019-04-03T06:12:46.000Z
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& a) { vector<vector<int>> res; if (a.empty()) return res; // 按照区间左端点排序 sort(a.begin(), a.end()); int l = a[0][0], r = a[0][1]; for (int i = 1; i < a.size(); i ++) { if (a[i][0] > r) { res.push_back({l, r}); l = a[i][0], r = a[i][1]; } else r = max(r, a[i][1]); } res.push_back({l, r}); return res; } };
23.826087
55
0.368613
LauZyHou
d3c5b86661dd4c680d6cf7a5db14c620dd28813b
2,783
cc
C++
src/multio/action/Aggregation.cc
dvuckovic/multio
36d2e4e4aa9f874f255efbde74642e5a514e8d76
[ "Apache-2.0" ]
null
null
null
src/multio/action/Aggregation.cc
dvuckovic/multio
36d2e4e4aa9f874f255efbde74642e5a514e8d76
[ "Apache-2.0" ]
null
null
null
src/multio/action/Aggregation.cc
dvuckovic/multio
36d2e4e4aa9f874f255efbde74642e5a514e8d76
[ "Apache-2.0" ]
1
2021-09-06T13:39:10.000Z
2021-09-06T13:39:10.000Z
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include "Aggregation.h" #include <algorithm> #include "eckit/config/Configuration.h" #include "eckit/exception/Exceptions.h" #include "multio/LibMultio.h" #include "multio/domain/Mappings.h" #include "multio/util/ScopedTimer.h" namespace multio { namespace action { Aggregation::Aggregation(const eckit::Configuration& config) : Action(config) {} void Aggregation::execute(Message msg) const { util::ScopedTimer timer{timing_}; if ((msg.tag() == Message::Tag::Field) && handleField(msg)) { executeNext(createGlobalField(msg)); } if ((msg.tag() == Message::Tag::StepComplete) && handleFlush(msg)) { executeNext(msg); } } bool Aggregation::handleField(const Message& msg) const { messages_[msg.fieldId()].push_back(msg); return allPartsArrived(msg); } bool Aggregation::handleFlush(const Message& msg) const { // Initialise if need be if (flushes_.find(msg.domain()) == end(flushes_)) { flushes_[msg.domain()] = 0; } return ++flushes_.at(msg.domain()) == msg.domainCount(); } bool Aggregation::allPartsArrived(const Message& msg) const { LOG_DEBUG_LIB(LibMultio) << " *** Number of messages for field " << msg.fieldId() << " are " << messages_.at(msg.fieldId()).size() << std::endl; return (msg.domainCount() == messages_.at(msg.fieldId()).size()) && (msg.domainCount() == domain::Mappings::instance().get(msg.domain()).size()); } Message Aggregation::createGlobalField(const Message& msg) const { const auto& fid = msg.fieldId(); LOG_DEBUG_LIB(LibMultio) << " *** Creating global field for " << fid << std::endl; auto levelCount = msg.metadata().getLong("levelCount", 1); Message msgOut{Message::Header{msg.header()}, eckit::Buffer{msg.globalSize() * levelCount * sizeof(double)}}; for (const auto& msg : messages_.at(fid)) { domain::Mappings::instance().get(msg.domain()).at(msg.source())->to_global(msg, msgOut); } messages_.erase(fid); return msgOut; } void Aggregation::print(std::ostream& os) const { os << "Aggregation(for " << messages_.size() << " fields = ["; for (const auto& msg : messages_) { os << '\n' << " ---> " << msg.first; } os << "])"; } static ActionBuilder<Aggregation> AggregationBuilder("Aggregation"); } // namespace action } // namespace multio
29.924731
96
0.655049
dvuckovic
d3c66153c89e68a9c95dd00225f22134379f1f1a
9,146
cc
C++
contrib/fluxbox/src/FbTk/Layer.cc
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
null
null
null
contrib/fluxbox/src/FbTk/Layer.cc
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
2
2017-05-30T05:21:59.000Z
2018-03-14T07:21:33.000Z
src/FbTk/Layer.cc
antix-skidoo/fluxbox
b83ee923f4ab2ab51f3b8c14343bda0579e538c6
[ "MIT" ]
null
null
null
// Layer.cc for FbTk - fluxbox toolkit // Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // and Simon Bowden (rathnor at users.sourceforge.net) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "Layer.hh" #include "LayerItem.hh" #include "App.hh" #include "FbWindow.hh" #include "MultLayers.hh" #include <iostream> #include <algorithm> #include <numeric> using namespace FbTk; #ifdef DEBUG using std::cerr; using std::endl; #endif // DEBUG namespace { int sum_windows(int nr, LayerItem* item) { return nr + item->numWindows(); } int count_windows(const FbTk::Layer::ItemList& items) { return std::accumulate(items.begin(), items.end(), 0, sum_windows); } void extract_windows_to_stack(const LayerItem::Windows& windows, std::vector<Window>& stack) { LayerItem::Windows::const_iterator i = windows.begin(); LayerItem::Windows::const_iterator end = windows.end(); for (; i != end; ++i) { Window w = (*i)->window(); if (w) stack.push_back(w); } } void extract_windows_to_stack(const FbTk::Layer::ItemList& items, LayerItem* temp_raised, std::vector<Window>& stack) { if (temp_raised) { // add windows that go on top extract_windows_to_stack(temp_raised->getWindows(), stack); } FbTk::Layer::ItemList::const_iterator it = items.begin(); FbTk::Layer::ItemList::const_iterator it_end = items.end(); for (; it != it_end; ++it) { // add all the windows from each other item if (*it == temp_raised) { continue; } extract_windows_to_stack((*it)->getWindows(), stack); } } void restack(const FbTk::Layer::ItemList& items, LayerItem* temp_raised) { std::vector<Window> stack; extract_windows_to_stack(items, temp_raised, stack); if (!stack.empty()) XRestackWindows(FbTk::App::instance()->display(), &stack[0], stack.size()); } } // end of anonymous namespace void Layer::restack(const std::vector<Layer*>& layers) { std::vector<Window> stack; std::vector<Layer*>::const_iterator l; for (l = layers.begin(); l != layers.end(); ++l) { extract_windows_to_stack((*l)->itemList(), 0, stack); } if (!stack.empty()) XRestackWindows(FbTk::App::instance()->display(), &stack[0], stack.size()); } Layer::Layer(MultLayers &manager, int layernum): m_manager(manager), m_layernum(layernum), m_needs_restack(false) { } Layer::~Layer() { } void Layer::restack() { if (m_manager.isUpdatable()) { ::restack(itemList(), 0); m_needs_restack = false; } } void Layer::restackAndTempRaise(LayerItem &item) { ::restack(itemList(), &item); } int Layer::countWindows() { return ::count_windows(itemList()); } // Stack all windows associated with 'item' below the 'above' item void Layer::stackBelowItem(LayerItem &item, LayerItem *above) { if (!m_manager.isUpdatable()) return; // if there are no windows provided for above us, // then we must restack the entire layer // we can't do XRaiseWindow because a restack then causes OverrideRedirect // windows to get pushed to the bottom if (!above || m_needs_restack) { // must need to go right to top restack(); return; } std::vector<Window> stack; // We do have a window to stack below // so we put it on top, and fill the rest of the array with the ones to go below it. // assume that above's window exists stack.push_back(above->getWindows().back()->window()); // fill the rest of the array extract_windows_to_stack(item.getWindows(), stack); XRestackWindows(FbTk::App::instance()->display(), &stack[0], stack.size()); } // We can't just use Restack here, because it won't do anything if they're // already in the same relative order excluding other windows void Layer::alignItem(LayerItem &item) { if (itemList().front() == &item) { stackBelowItem(item, m_manager.getLowestItemAboveLayer(m_layernum)); return; } // Note: some other things effectively assume that the window list is // sorted from highest to lowest // get our item iterator myit = std::find(itemList().begin(), itemList().end(), &item); iterator it = myit; // go to the one above it in our layer (top is front, so we decrement) --it; // keep going until we find one that is currently visible to the user while (it != itemList().begin() && !(*it)->visible()) --it; if (it == itemList().begin() && !(*it)->visible()) // reached front item, but it wasn't visible, therefore it was already raised stackBelowItem(item, m_manager.getLowestItemAboveLayer(m_layernum)); else stackBelowItem(item, *it); } Layer::iterator Layer::insert(LayerItem &item, unsigned int pos) { #ifdef DEBUG // at this point we don't support insertions into a layer other than at the top if (pos != 0) cerr<<__FILE__<<"("<<__LINE__<<"): Insert using non-zero position not valid in Layer"<<endl; #endif // DEBUG itemList().push_front(&item); // restack below next window up stackBelowItem(item, m_manager.getLowestItemAboveLayer(m_layernum)); return itemList().begin(); } void Layer::remove(LayerItem &item) { iterator it = itemList().begin(); iterator it_end = itemList().end(); for (; it != it_end; ++it) { if (*it == &item) { itemList().erase(it); break; } } } void Layer::raise(LayerItem &item) { // assume it is already in this layer if (&item == itemList().front()) { if (m_needs_restack) restack(); return; // nothing to do } iterator it = std::find(itemList().begin(), itemList().end(), &item); if (it != itemList().end()) itemList().erase(it); else { #ifdef DEBUG cerr<<__FILE__<<"("<<__LINE__<<"): WARNING: raise on item not in layer["<<m_layernum<<"]"<<endl; #endif // DEBUG return; } itemList().push_front(&item); stackBelowItem(item, m_manager.getLowestItemAboveLayer(m_layernum)); } void Layer::tempRaise(LayerItem &item) { // assume it is already in this layer if (!m_needs_restack && &item == itemList().front()) return; // nothing to do iterator it = std::find(itemList().begin(), itemList().end(), &item); if (it == itemList().end()) { #ifdef DEBUG cerr<<__FILE__<<"("<<__LINE__<<"): WARNING: raise on item not in layer["<<m_layernum<<"]"<<endl; #endif // DEBUG return; } if (m_needs_restack) restackAndTempRaise(item); else stackBelowItem(item, m_manager.getLowestItemAboveLayer(m_layernum)); m_needs_restack = true; } void Layer::lower(LayerItem &item) { // assume already in this layer // is it already the lowest? if (&item == itemList().back()) { if (m_needs_restack) restack(); return; // nothing to do } iterator it = std::find(itemList().begin(), itemList().end(), &item); if (it != itemList().end()) // remove this item itemList().erase(it); #ifdef DEBUG else { cerr<<__FILE__<<"("<<__LINE__<<"): WARNING: lower on item not in layer"<<endl; return; } #endif // DEBUG // add it to the bottom itemList().push_back(&item); // find the item we need to stack below // start at the end it = itemList().end(); // go up one so we have an object (which must exist, since at least this item is in the layer) it--; // go down another one // must exist, otherwise our item must == itemList().back() it--; // and restack our window below that one. stackBelowItem(item, *it); } void Layer::raiseLayer(LayerItem &item) { m_manager.raiseLayer(item); } void Layer::lowerLayer(LayerItem &item) { m_manager.lowerLayer(item); } void Layer::moveToLayer(LayerItem &item, int layernum) { m_manager.moveToLayer(item, layernum); } LayerItem *Layer::getLowestItem() { if (itemList().empty()) return 0; else return itemList().back(); }
29.40836
119
0.64684
xk2600
d3ca16f46de4c5008ef55d0175fe5df4c64b834a
699
hpp
C++
CPPMetal/Headers/CPPMetal.hpp
chromy/cppmetal
7acebf0519f119745e25a2b9eaac81889fb3a774
[ "MIT" ]
null
null
null
CPPMetal/Headers/CPPMetal.hpp
chromy/cppmetal
7acebf0519f119745e25a2b9eaac81889fb3a774
[ "MIT" ]
null
null
null
CPPMetal/Headers/CPPMetal.hpp
chromy/cppmetal
7acebf0519f119745e25a2b9eaac81889fb3a774
[ "MIT" ]
null
null
null
/* See LICENSE folder for this sample’s licensing information. Abstract: Header for C++ Metal wrapper */ #ifndef CPPMetal_hpp #define CPPMetal_hpp #include "CPPMetalBuffer.hpp" #include "CPPMetalCommandBuffer.hpp" #include "CPPMetalCommandQueue.hpp" #include "CPPMetalDevice.hpp" #include "CPPMetalDepthStencil.hpp" #include "CPPMetalDrawable.hpp" #include "CPPMetalLibrary.hpp" #include "CPPMetalPixelFormat.hpp" #include "CPPMetalRenderPass.hpp" #include "CPPMetalRenderCommandEncoder.hpp" #include "CPPMetalRenderPipeline.hpp" #include "CPPMetalTexture.hpp" #include "CPPMetalVertexDescriptor.hpp" #include "CPPMetalKitView.hpp" #include "CPPMetalKitTextureLoader.hpp" #endif // CPPMetal_hpp
24.964286
59
0.812589
chromy
d3cb0ed9b1fdaf3539605f327f266cb31f3ac6a8
1,704
inl
C++
dds/DCPS/transport/framework/TransportReceiveStrategy_T.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
dds/DCPS/transport/framework/TransportReceiveStrategy_T.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
dds/DCPS/transport/framework/TransportReceiveStrategy_T.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
/* * $Id: TransportReceiveStrategy_T.inl 5266 2012-01-21 04:36:48Z mitza $ * * * Distributed under the OpenDDS License. * See: http://www.opendds.org/license.html */ #include "EntryExit.h" #include "TransportReassembly.h" template<typename TH, typename DSH> ACE_INLINE int OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::start() { DBG_ENTRY_LVL("TransportReceiveStrategy","start",6); return this->start_i(); } template<typename TH, typename DSH> ACE_INLINE void OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::stop() { DBG_ENTRY_LVL("TransportReceiveStrategy","stop",6); this->stop_i(); } template<typename TH, typename DSH> ACE_INLINE const TH& OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::received_header() const { return this->receive_transport_header_; } template<typename TH, typename DSH> ACE_INLINE TH& OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::received_header() { return this->receive_transport_header_; } template<typename TH, typename DSH> ACE_INLINE const DSH& OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::received_sample_header() const { return this->data_sample_header_; } template<typename TH, typename DSH> ACE_INLINE DSH& OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::received_sample_header() { return this->data_sample_header_; } template<typename TH, typename DSH> ACE_INLINE size_t OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::successor_index(size_t index) const { return ++index % RECEIVE_BUFFERS; } template<typename TH, typename DSH> ACE_INLINE void OpenDDS::DCPS::TransportReceiveStrategy<TH, DSH>::relink(bool) { // The subclass needs implement this function for re-establishing // the link upon recv failure. }
24.342857
85
0.767606
binary42
d3cce85f53a3bc6b83698a5117e58ad16ea37919
3,776
hpp
C++
src/libraries/core/primitives/ranges/scalarRange/scalarRange.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/primitives/ranges/scalarRange/scalarRange.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/primitives/ranges/scalarRange/scalarRange.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::scalarRange Description A scalar range specifier. The range selector can be specified as an "LOWER:UPPER" range, as a "LOWER:" bound, as an ":UPPER" bound or simply as an "EXACT" value. The read constructor uses a colon (:) as a range marker and a comma (,) to delimit the next possible range selector. SourceFiles scalarRange.cpp \*---------------------------------------------------------------------------*/ #ifndef scalarRange_H #define scalarRange_H #include "scalar.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of classes class Istream; class Ostream; // Forward declaration of friend functions and operators class scalarRange; Istream& operator>>(Istream&, scalarRange&); Ostream& operator<<(Ostream&, const scalarRange&); /*---------------------------------------------------------------------------*\ Class scalarRange Declaration \*---------------------------------------------------------------------------*/ class scalarRange { //- Enumeration defining the types of token enum rangeType { EMPTY = 0, EXACT, LOWER, UPPER, RANGE }; // Private data enum rangeType type_; scalar value_; scalar value2_; public: static int debug; // Constructors //- Construct an empty range scalarRange(); //- Construct a range from lower to upper scalarRange(const scalar lower, const scalar upper); //- Construct from Istream. // Since commas can be used as list delimiters, // leading and trailing commas are ignored. scalarRange(Istream&); // Member Functions //- Is the range empty? bool empty() const; //- Is the range non-empty? bool valid() const; //- Is the range 'EXACT'? bool isExact() const; //- The value constituting an 'EXACT' match // or the values for 'UPPER' or 'LOWER' limits scalar value() const; //- The lower limit scalar lower() const; //- The upper limit scalar upper() const; //- Return true if the value is within the range bool selected(const scalar) const; // Member Operators bool operator==(const scalarRange&) const; bool operator!=(const scalarRange&) const; // IOstream Operators friend Istream& operator>>(Istream&, scalarRange&); friend Ostream& operator<<(Ostream&, const scalarRange&); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
26.041379
79
0.521981
MrAwesomeRocks
d3ce4e217b620855f1d8e47c48be4f6c8dc802bc
355
cpp
C++
ex204042016.cpp
jcvasconcelos/praticando-exercicios-simples-git-c
24e7328ff6c6cb452acf2fad1e7a1789e2daaf42
[ "MIT" ]
null
null
null
ex204042016.cpp
jcvasconcelos/praticando-exercicios-simples-git-c
24e7328ff6c6cb452acf2fad1e7a1789e2daaf42
[ "MIT" ]
null
null
null
ex204042016.cpp
jcvasconcelos/praticando-exercicios-simples-git-c
24e7328ff6c6cb452acf2fad1e7a1789e2daaf42
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> int main() { int soma=10; float money=2.21; char letra='A'; double valor=2.01E6; printf("Valor da soma = %d\n", soma); //Mosta na tela o conteudo da variavel printf("Valor de Money = %f\n", money); printf("Valor de Letra = %c\n", letra); printf("Valor de valor = %e\n", valor); system("pause"); return 0; }
20.882353
77
0.642254
jcvasconcelos
d3cfe449233ce983335d89e7aa4518989c8198ea
3,504
cpp
C++
misc/data_parallel/research/openmp/src/demo.cpp
mchapman87501/DMCWingWorks
973979d515d054a835f78ff0fe86fd909e1138c7
[ "MIT" ]
null
null
null
misc/data_parallel/research/openmp/src/demo.cpp
mchapman87501/DMCWingWorks
973979d515d054a835f78ff0fe86fd909e1138c7
[ "MIT" ]
null
null
null
misc/data_parallel/research/openmp/src/demo.cpp
mchapman87501/DMCWingWorks
973979d515d054a835f78ff0fe86fd909e1138c7
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <sstream> #include <fstream> #include <chrono> #include <vector> #include <cmath> #include <cstring> #include <algorithm> #include <stdexcept> #include <random> #include "point.h" #include "particle.h" #include "airfoil.h" #include "world.h" using namespace std; using namespace wingworks; using namespace std::chrono; namespace { void write_airfoil_shape(std::ostream& outs, const Airfoil& airfoil) { outs << "X,Y" << std::endl; auto vertices = airfoil.shape().vertices(); for (const auto& p : vertices) { outs << p.x() << "," << p.y() << std::endl; } } void write_airfoil(const Airfoil& airfoil) { ofstream outf("airfoil.csv"); write_airfoil_shape(outf, airfoil); outf.close(); } string foil_force_file_name(const size_t step_num) { ostringstream outs; outs << "net_force_" << setfill('0') << setw(4) << step_num << ".csv"; return outs.str(); } void write_foil_forces(const size_t step_num, const World& world) { ofstream outf(foil_force_file_name(step_num)); world.write_force_on_foil(outf); outf.close(); } string pos_file_name(const size_t step_num) { ostringstream outs; outs << "positions_" << setfill('0') << setw(4) << step_num << ".csv"; return outs.str(); } void write_positions(const size_t step_num, const World& world) { ofstream outf(pos_file_name(step_num)); world.write_particle_positions(outf); outf.close(); } } int main(int argc, char **argv) { const double world_width = 128.0; const double world_height = 72.0; const double aoa_rad = 10.0 * M_PI / 180.0; const Airfoil airfoil( world_width / 8.0, world_height / 2.0, world_width / 4.0, aoa_rad ); write_airfoil(airfoil); const double max_particle_speed = 0.0005; const Point wind_vel = Point(0.11, 0.0); World world( airfoil, world_width, world_height, max_particle_speed, wind_vel); Vector total_foil_force; const size_t movie_seconds = 20; const size_t fps = 30; const size_t steps_per_frame = 10; size_t index = 0; double mv_prev = 0.0; steady_clock::time_point t0 = steady_clock::now(); for (size_t sec = 1; sec <= movie_seconds; ++sec) { for (size_t iframe = 1; iframe <= fps; iframe++) { for (size_t istep = 1; istep <= steps_per_frame; ++istep) { world.step(); } index += 1; write_positions(index, world); write_foil_forces(index, world); total_foil_force.add(world.force_on_foil()); world.reset_force_on_foil(); steady_clock::time_point tf = steady_clock::now(); duration<double> dt = duration_cast<duration<double>>(tf - t0); t0 = tf; const double mv = world.momentum(); const double dmv = mv - mv_prev; mv_prev = mv; cout << sec << "." << iframe << "/" << movie_seconds << ": net mv = " << mv << ", Δmv = " << dmv << "; dt = " << dt.count() << " seconds" << endl; } } // The direction of the force is backwards, hence the scale: cout << "Summed force on foil: " << total_foil_force.scaled(-1.0).to_str() << endl; return 0; }
27.375
78
0.575628
mchapman87501
d3d125509a12bbca83c880be071fa262ad056735
1,873
inl
C++
dev/Code/Tools/SphericalHarmonics/PRT/DefaultTransferConfigurator.inl
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Tools/SphericalHarmonics/PRT/DefaultTransferConfigurator.inl
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Tools/SphericalHarmonics/PRT/DefaultTransferConfigurator.inl
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #if defined(OFFLINE_COMPUTATION) #include <PRT/SHFrameworkBasis.h> #include <PRT/ISHMaterial.h> inline NSH::NTransfer::CDefaultTransferConfigurator::CDefaultTransferConfigurator(const STransferParameters& crParameters) : m_TransferParameters(crParameters) {} inline const bool NSH::NTransfer::CDefaultTransferConfigurator::ProcessOnlyUpperHemisphere(const NMaterial::EMaterialType cMatType) const { switch (cMatType) { case NSH::NMaterial::MATERIAL_TYPE_DEFAULT: return true; break; case NSH::NMaterial::MATERIAL_TYPE_BASETEXTURE: return true; break; case NSH::NMaterial::MATERIAL_TYPE_ALPHATEXTURE: case NSH::NMaterial::MATERIAL_TYPE_ALPHA_DEFAULT: return false; break; case NSH::NMaterial::MATERIAL_TYPE_BACKLIGHTING: case NSH::NMaterial::MATERIAL_TYPE_BACKLIGHTING_DEFAULT: return false; break; default: return true; } } inline NSH::ITransferConfiguratorPtr NSH::NTransfer::CDefaultTransferConfigurator::Clone() const { return ITransferConfiguratorPtr(new CDefaultTransferConfigurator(m_TransferParameters)); } inline const bool NSH::NTransfer::CDefaultTransferConfigurator::UseCoefficientLookupMode() const { return false; } #endif
32.859649
137
0.753871
jeikabu
d3d20adae2446f8d8b45f2833ac954436a55d9ea
11,970
cc
C++
tests/ticker.cc
hedzr/hicc
c2a33afec2ff1f79c42ed9f888ad091710e7ae60
[ "MIT" ]
null
null
null
tests/ticker.cc
hedzr/hicc
c2a33afec2ff1f79c42ed9f888ad091710e7ae60
[ "MIT" ]
null
null
null
tests/ticker.cc
hedzr/hicc
c2a33afec2ff1f79c42ed9f888ad091710e7ae60
[ "MIT" ]
null
null
null
// // Created by Hedzr Yeh on 2021/7/13. // // #define HICC_TEST_THREAD_POOL_DBGOUT 1 // #define HICC_ENABLE_THREAD_POOL_READY_SIGNAL 1 #include "hicc/hz-ticker.hh" #include "hicc/hz-x-class.hh" #include "hicc/hz-x-test.hh" #include <chrono> #include <iostream> #include <thread> hicc::debug::X x_global_var; namespace test { template<typename T> constexpr auto ZFN() { constexpr auto function = std::string_view{__FUNCTION_NAME__}; constexpr auto prefix = std::string_view{"auto ZFN() [T = "}; constexpr auto suffix = std::string_view{"]"}; constexpr auto start = function.find(prefix) + prefix.size(); constexpr auto end = function.rfind(suffix); std::string_view name = function.substr(start, (end - start)); return name.substr(0, (end - start)); // return function; } template<typename T> constexpr auto ZFS() { constexpr auto function = std::string_view{__FUNCTION_NAME__}; constexpr auto prefix = std::string_view{"auto ZFT() [T = "}; // constexpr auto suffix = std::string_view{"]"}; constexpr auto start = function.find(prefix) + prefix.size(); // constexpr auto end = function.rfind(suffix); return (unsigned long long) start; // function.substr(start, (end - start)); // return function; } template<typename T> constexpr auto ZFT() { constexpr auto function = std::string_view{__FUNCTION_NAME__}; // constexpr auto prefix = std::string_view{"auto ZFT() [T = "}; constexpr auto suffix = std::string_view{"]"}; // constexpr auto start = function.find(prefix) + prefix.size(); constexpr auto end = function.rfind(suffix); return (unsigned long long) end; // function.substr(start, (end - start)); // return function; } template<typename T> constexpr auto ZFZ() { // auto ZFZ() [T = std::__1::basic_string<char>] constexpr auto function = std::string_view{__FUNCTION_NAME__}; return function; } } // namespace test void test_type_name() { printf(">>Z '%s'\n", test::ZFZ<std::string>().data()); printf(">>Z '%s'\n", test::ZFN<std::string>().data()); printf(">>Z %llu, %llu\n", test::ZFS<std::string>(), test::ZFT<std::string>()); #ifndef _WIN32 printf(">>2 '%s'\n", hicc::debug::type_name_holder<std::string>::value.data()); printf(">>1 '%s'\n", hicc::debug::type_name_1<hicc::pool::conditional_wait_for_int>().data()); printf(">>> '%s'\n", hicc::debug::type_name<hicc::pool::conditional_wait_for_int>().data()); #endif auto fn = hicc::debug::type_name<std::string>(); std::string str{fn}; printf(">>> '%s'\n", str.c_str()); std::cout << hicc::debug::type_name<std::string>() << '\n'; std::cout << std::string(hicc::debug::type_name<std::string>()) << '\n'; printf(">>> %s\n", std::string(hicc::debug::type_name<std::string>()).c_str()); } void foo() { std::cout << x_global_var.c_str() << '\n'; std::this_thread::sleep_for(std::chrono::seconds(1)); } void test_thread_basics() { printf("> %s\n", __FUNCTION_NAME__); { std::thread t; std::cout << "- before starting, joinable: " << std::boolalpha << t.joinable() << '\n'; t = std::thread(foo); std::cout << "- after starting, joinable: " << t.joinable() << '\n'; t.join(); std::cout << "- after joining, joinable: " << t.joinable() << '\n'; } { unsigned int n = std::thread::hardware_concurrency(); std::cout << "- " << n << " concurrent _threads are supported.\n"; } } void foo1() { hicc_print("foo1 hit."); } void test_periodical_job() { namespace chr = hicc::chrono; namespace dtl = hicc::chrono::detail; using clock = std::chrono::system_clock; using time_point = clock::time_point; using namespace std::literals::chrono_literals; struct testcase { const char *desc; chr::anchors anchor; int offset; int ordinal; int times; time_point now, expected; }; #define CASE(desc, anchor, ofs) \ testcase { desc, anchor, ofs, 1, -1, time_point(), time_point() } #define CASE1(desc, anchor, ofs, ord) \ testcase { desc, anchor, ofs, ord, -1, time_point(), time_point() } #define CASE2(desc, anchor, ofs, ord, times) \ testcase { desc, anchor, ofs, ord, times, time_point(), time_point() } #define NOW_CASE(now_str, expected_str, desc, anchor, ofs) \ testcase { desc, anchor, ofs, 1, -1, hicc::chrono::parse_datetime(now_str), hicc::chrono::parse_datetime(expected_str) } for (auto const &t : { // Month NOW_CASE("2021-08-05", "2021-09-03", "day 3 every month", chr::anchors::Month, 3), NOW_CASE("2021-08-05", "2021-08-23", "day 23 every month", chr::anchors::Month, 23), NOW_CASE("2021-08-05", "2021-08-29", "day -3 every month", chr::anchors::Month, -3), NOW_CASE("2021-08-05", "2021-08-17", "day -15 every month", chr::anchors::Month, -15), NOW_CASE("2021-08-17", "2021-09-17", "day -15 every month", chr::anchors::Month, -15), // Year NOW_CASE("2021-08-05", "2022-08-03", "day 3 (this month) every year", chr::anchors::Year, 3), NOW_CASE("2021-08-05", "2021-08-23", "day 23 (this month) every year", chr::anchors::Year, 23), NOW_CASE("2021-08-05", "2021-12-29", "day -3 (this month) every year", chr::anchors::Year, -3), NOW_CASE("2021-08-05", "2021-12-17", "day -15 (this month) every year", chr::anchors::Year, -15), NOW_CASE("2021-08-18", "2021-12-17", "day -15 (this month) every year", chr::anchors::Year, -15), // FirstThirdOfMonth ... NOW_CASE("2021-08-05", "2021-09-03", "day 3 every first third of month", chr::anchors::FirstThirdOfMonth, 3), NOW_CASE("2021-08-05", "2021-08-08", "day 8 every first third of month", chr::anchors::FirstThirdOfMonth, 8), NOW_CASE("2021-08-05", "2021-08-08", "day -3 every first third of month", chr::anchors::FirstThirdOfMonth, -3), NOW_CASE("2021-08-05", "2021-09-04", "day -7 every first third of month", chr::anchors::FirstThirdOfMonth, -7), // MiddleThirdOfMonth ... NOW_CASE("2021-08-15", "2021-09-13", "day 3 every mid third of month", chr::anchors::MiddleThirdOfMonth, 3), NOW_CASE("2021-08-15", "2021-08-18", "day 8 every mid third of month", chr::anchors::MiddleThirdOfMonth, 8), NOW_CASE("2021-08-15", "2021-08-18", "day -3 every mid third of month", chr::anchors::MiddleThirdOfMonth, -3), NOW_CASE("2021-08-15", "2021-09-14", "day -7 every mid third of month", chr::anchors::MiddleThirdOfMonth, -7), // LastThirdOfMonth ... NOW_CASE("2021-08-25", "2021-09-23", "day 3 every last third of month", chr::anchors::LastThirdOfMonth, 3), NOW_CASE("2021-08-25", "2021-08-28", "day 8 every last third of month", chr::anchors::LastThirdOfMonth, 8), NOW_CASE("2021-08-25", "2021-08-29", "day -3 every last third of month", chr::anchors::LastThirdOfMonth, -3), NOW_CASE("2021-08-25", "2021-09-23", "day -9 every last third of month", chr::anchors::LastThirdOfMonth, -9), NOW_CASE("2021-08-22", "2021-08-23", "day -9 every last third of month", chr::anchors::LastThirdOfMonth, -9), }) { dtl::periodical_job pj(t.anchor, t.ordinal, t.offset, t.times, foo1); auto now = t.now; if (chr::duration_is_zero(now)) now = hicc::chrono::now(); else pj.last_pt = now; auto pt = pj.next_time_point(now); hicc_print("%40s: %s -> %s", t.desc, hicc::chrono::format_time_point_to_local(now).c_str(), hicc::chrono::format_time_point_to_local(pt).c_str()); auto tmp = t.expected; if (!chr::duration_is_zero(tmp)) { if (hicc::chrono::compare_date_part(pt, tmp) != 0) { hicc_print("%40s: ERROR: expecting %s but got %s", " ", hicc::chrono::format_time_point_to_local(tmp).c_str(), hicc::chrono::format_time_point_to_local(pt).c_str()); exit(-1); } } } #undef NOW_CASE } void test_timer() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count{1}; auto t = hicc::chrono::timer<>::get(); #if !HICC_ENABLE_THREAD_POOL_READY_SIGNAL std::this_thread::sleep_for(300ms); #endif hicc_print(" - start at: %s", hicc::chrono::format_time_point().c_str()); t->after(1us) .on([&count] { auto now = hicc::chrono::now(); hicc::pool::cw_setter cws(count); // std::time_t ct = std::time(0); // char *cc = ctime(&ct); printf(" - after [%02d]: %s\n", count.val(), hicc::chrono::format_time_point(now).c_str()); }) .build(); printf("count.wait()\n"); count.wait_for(); // t.clear(); printf("end of %s\n", __FUNCTION_NAME__); } void test_ticker() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count{16}; auto t = hicc::chrono::ticker<>::get(); #if !HICC_ENABLE_THREAD_POOL_READY_SIGNAL std::this_thread::sleep_for(300ms); #endif hicc_print(" - start at: %s", hicc::chrono::format_time_point().c_str()); t->every(1us) .on([&count]() { // auto now = hicc::chrono::now(); hicc::pool::cw_setter cws(count); printf(" - every [%02d]: %s\n", count.val(), hicc::chrono::format_time_point().c_str()); }) .build(); count.wait(); // t.clear(); printf("end of %s\n", __FUNCTION_NAME__); } void test_ticker_interval() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count2{4}; auto t = hicc::chrono::ticker<>::get([] { hicc_print(" - start at: %s", hicc::chrono::format_time_point().c_str()); }); t->interval(200ms) .on([&count2] { hicc::pool::cw_setter cws(count2); printf(" - interval [%02d]: %s\n", count2.val(), hicc::chrono::format_time_point().c_str()); }) .build(); count2.wait(); printf("end of %s\n", __FUNCTION_NAME__); } void test_alarmer() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count2{4}; hicc::chrono::alarmer<>::super::get() ->every_month(3) .on([&count2] { auto now = hicc::chrono::now(); hicc::pool::cw_setter cws(count2); printf(" - alarmer [%02d]: %s\n", count2.val(), hicc::chrono::format_time_point(now).c_str()); }) .build(); printf("end of %s\n", __FUNCTION_NAME__); } int main() { // test_thread(); HICC_TEST_FOR(test_periodical_job); #if 1 HICC_TEST_FOR(test_type_name); HICC_TEST_FOR(test_thread_basics); HICC_TEST_FOR(test_timer); HICC_TEST_FOR(test_ticker); HICC_TEST_FOR(test_ticker_interval); HICC_TEST_FOR(test_alarmer); // using namespace std::literals::chrono_literals; // std::this_thread::sleep_for(200ns); // // { // std::time_t ct = std::time(0); // char *cc = ctime(&ct); // printf(". now: %s\n", cc); // } // { // auto t = std::time(nullptr); // auto tm = *std::localtime(&t); // std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << '\n'; // } #endif return 0; }
38.488746
181
0.578279
hedzr
d3d2a90e687b53ad00a51878e5c1bc5525580db2
2,913
hpp
C++
DefeatMonsterAICreateBaseProject/Skill.hpp
AinoMegumi/DefeatMonsterAICreateBaseProject
6666f55bec2ec42fc81a0a39fcd98d93af091676
[ "MIT" ]
null
null
null
DefeatMonsterAICreateBaseProject/Skill.hpp
AinoMegumi/DefeatMonsterAICreateBaseProject
6666f55bec2ec42fc81a0a39fcd98d93af091676
[ "MIT" ]
null
null
null
DefeatMonsterAICreateBaseProject/Skill.hpp
AinoMegumi/DefeatMonsterAICreateBaseProject
6666f55bec2ec42fc81a0a39fcd98d93af091676
[ "MIT" ]
null
null
null
#pragma once #include "Element.hpp" struct SkillA { SkillA() = default; SkillA(const std::string Name, const std::string Tag, int UseMP, const int BasePower, const std::string Description, const ElementInfo SkillElement, const std::string EffectGraphPath, const std::string EffectSoundPath, const bool Range, const bool ResurrectionEffect, const int SkillType, const int LessMP, const int AddBlendLevel) : Name(Name), Tag(Tag), UseMP(UseMP), BasePower(BasePower), Description(Description), SkillElement(SkillElement), EffectGraphPath(EffectGraphPath), EffectSoundPath(EffectSoundPath), Range(Range), ResurrectionEffect(ResurrectionEffect), SkillType(SkillType), LessMP(LessMP), AddBlendLevel(AddBlendLevel) {} std::string Name; // 名前 std::string Tag; // 識別タグ int UseMP; // 消費MP int BasePower; // 基本攻撃力 std::string Description; // 説明 ElementInfo SkillElement; // 属性(enum class値) std::string EffectGraphPath;// エフェクト画像のパス std::string EffectSoundPath;// エフェクトのサウンドパス bool Range; // 範囲効果フラグ bool ResurrectionEffect; // 復活効果の有無 int SkillType; // スキル種別(0:攻撃 1:回復 2:範囲回復) int LessMP; // 最低限必要なMP int AddBlendLevel; // 加算ブレンドのレベル bool operator == (const SkillA s) const { return this->Name == s.Name && this->UseMP == s.UseMP && this->BasePower == s.BasePower && this->Description == s.Description && this->SkillElement == s.SkillElement; } bool operator != (const SkillA s) const { return !this->operator==(s); } }; struct SkillW { SkillW() = default; SkillW(const std::wstring Name, const std::wstring Tag, int UseMP, const int BasePower, const std::wstring Description, const ElementInfo SkillElement, const std::wstring EffectGraphPath, const std::wstring EffectSoundPath, const bool Range, const bool ResurrectionEffect, const int SkillType, const int LessMP, const int AddBlendLevel) : Name(Name), Tag(Tag), UseMP(UseMP), BasePower(BasePower), Description(Description), SkillElement(SkillElement), EffectGraphPath(EffectGraphPath), EffectSoundPath(EffectSoundPath), Range(Range), ResurrectionEffect(ResurrectionEffect), SkillType(SkillType), LessMP(LessMP), AddBlendLevel(AddBlendLevel) {} std::wstring Name; // 名前 std::wstring Tag; // 識別タグ int UseMP; // 消費MP int BasePower; // 基本攻撃力 std::wstring Description; // 説明 ElementInfo SkillElement; // 属性(enum class値) std::wstring EffectGraphPath;// エフェクト画像のパス std::wstring EffectSoundPath;// エフェクトのサウンドパス bool Range; // 範囲効果フラグ bool ResurrectionEffect; // 復活効果の有無 int SkillType; // スキル種別(0:攻撃 1:回復 2:範囲回復) int LessMP; // 最低限必要なMP int AddBlendLevel; // 加算ブレンドのレベル bool operator == (const SkillW s) const { return this->Name == s.Name && this->UseMP == s.UseMP && this->BasePower == s.BasePower && this->Description == s.Description && this->SkillElement == s.SkillElement; } }; #if defined(UNICODE) typedef SkillW Skill; #else typedef SkillA Skill; #endif
50.224138
186
0.729832
AinoMegumi
d3d33631652acfc324a5eef9e1cb776de3d55a76
4,093
hpp
C++
include/xtomic/impl/hash_map_node_integral_key.hpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
include/xtomic/impl/hash_map_node_integral_key.hpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
include/xtomic/impl/hash_map_node_integral_key.hpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
/* * hash_node_integral_key.hpp * * Created on: Feb 7, 2015 * Author: masha */ #ifndef INCLUDE_HASH_MAP_NODE_INTEGRAL_KEY_HPP_ #define INCLUDE_HASH_MAP_NODE_INTEGRAL_KEY_HPP_ #include <xtomic/quantum.hpp> #include "meta_utils.hpp" namespace xtomic { // Eclipse Luna does not recognize alignas keyword regardless of any settings // It seems Eclipse's developers do not admit the bug so the only way // to avoid annoying error marks these macro are used template<typename Key> struct align_by(2*sizeof(Key)) key_item { typedef key_item<Key> this_type; typedef typename get_int_by_size<sizeof(Key)>::type state_type; // states of the item (m_state field) enum { unused, // initial state pending,// key is valid, value is being constructed/deleted touched,// key is valid allocated,// key & value are valid }; // normal life cycle of an item in the hash table is: // // <after initialization> // 1. unused - initial state. Fields key and value have not been initialized // // <insert is in progress> // 2. pending - insert operation is in progress. // key is initialized // value is being constructed // // <first insert finished> // 3. allocated - ready to use, all fields are valid // // <first erase is in progress> // 4. pending - erase operation is in progress. // key is valid // value is being destroyed // // <first erase finished> // 5. touched - erase operation finished. // key is valid // value is destroyed // // <subsequent insert is in progress> // 6. pending - insert operation is in progress. // key is valid // value is being constructed // // <insert finished> // 7. allocated - exactly same as 3. key_item() : m_key(), m_state() { } key_item(const Key key, const state_type state) : m_key(key), m_state(state) { } key_item(const this_type & other) : m_key(other.m_key), m_state(other.m_state) { } key_item(const volatile this_type & other) : m_key(other.m_key), m_state(other.m_state) { } Key m_key; state_type m_state; }; template<typename Key, typename Value> class hash_node_integral_key { public: typedef Key key_type; typedef Value mapped_type; typedef hash_node_integral_key<key_type, mapped_type> this_class; typedef key_item<Key> key_item_type; typedef typename key_item_type::state_type state_type; private: hash_node_integral_key(const this_class&); // = delete; this_class& operator=(const this_class&); // = delete; public: hash_node_integral_key() : m_key(), m_refCount(0) { } const key_item_type getKey() const { return m_key; } void setKey(const key_type keyValue, const state_type stateValue) { m_key.m_key = keyValue; m_key.m_state = stateValue; } state_type getState() const { return m_key.m_state; } void setState(const state_type val) { thread_fence(barriers::release); m_key.m_state = val; } mapped_type* getValue() { return reinterpret_cast<mapped_type*>(m_value); } const mapped_type* getValue() const { return reinterpret_cast<const mapped_type*>(m_value); } bool atomic_cas(const key_item_type & expected, const key_item_type & newkey) { return xtomic::atomic_cas(m_key, expected, newkey); } void addRef() const { ++m_refCount; } void release() const { --m_refCount; } void waitForRelease() const { while (m_refCount.load(barriers::relaxed)) ; } private: volatile key_item_type m_key;char m_value[sizeof(mapped_type)] align_as(mapped_type); mutable xtomic::quantum<int> m_refCount; }; } #endif /* INCLUDE_HASH_MAP_NODE_INTEGRAL_KEY_HPP_ */
25.110429
89
0.623015
mashavorob
d3d3de9f03ca55bc936f029cc45fae822effae88
1,352
cpp
C++
src/Broadcaster.cpp
fairinternal/cuberite
a8c63a757c73279b854e5ef9622287d1c7d68b85
[ "Apache-2.0" ]
null
null
null
src/Broadcaster.cpp
fairinternal/cuberite
a8c63a757c73279b854e5ef9622287d1c7d68b85
[ "Apache-2.0" ]
null
null
null
src/Broadcaster.cpp
fairinternal/cuberite
a8c63a757c73279b854e5ef9622287d1c7d68b85
[ "Apache-2.0" ]
null
null
null
// Broadcaster.cpp // Implements the broadcasting interface for cWorld #include "Globals.h" #include "Broadcaster.h" #include "World.h" #include "Chunk.h" #include "ClientHandle.h" cBroadcaster::cBroadcaster(cWorld * a_World) : m_World(a_World) { } void cBroadcaster::BroadcastParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude) { m_World->DoWithChunkAt(a_Src, [=](cChunk & a_Chunk) -> bool { for (auto && client : a_Chunk.GetAllClients()) { if (client == a_Exclude) { continue; } client->SendParticleEffect(a_ParticleName, a_Src.x, a_Src.y, a_Src.z, a_Offset.x, a_Offset.y, a_Offset.z, a_ParticleData, a_ParticleAmount); }; return true; }); } void cBroadcaster::BroadcastParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, std::array<int, 2> a_Data, cClientHandle * a_Exclude) { m_World->DoWithChunkAt(a_Src, [=](cChunk & a_Chunk) -> bool { for (auto && client : a_Chunk.GetAllClients()) { if (client == a_Exclude) { continue; } client->SendParticleEffect(a_ParticleName, a_Src, a_Offset, a_ParticleData, a_ParticleAmount, a_Data); }; return true; }); }
22.163934
219
0.705621
fairinternal
d3d576e1958a7c3ed1f9ead8e6193cec77f383b4
6,911
cpp
C++
exodus/libexodus/exodus/mvos2.cpp
exodusdb/exodus
b99dd39e826d5a56b6a807c14994ee8fc8970ff8
[ "MIT" ]
null
null
null
exodus/libexodus/exodus/mvos2.cpp
exodusdb/exodus
b99dd39e826d5a56b6a807c14994ee8fc8970ff8
[ "MIT" ]
null
null
null
exodus/libexodus/exodus/mvos2.cpp
exodusdb/exodus
b99dd39e826d5a56b6a807c14994ee8fc8970ff8
[ "MIT" ]
null
null
null
/* Copyright (c) 2009 steve.bush@neosys.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // for sleep #include <thread> #include <chrono> #include <random> #include <unistd.h> //for getpid #include <exodus/mv.h> // to get whole environment extern char** environ; namespace exodus { void var::ossleep(const int milliseconds) const { THISIS("void var::ossleep(const int milliseconds) const") assertDefined(function_sig); // not needed if *this not used std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } // BOOST RANDOM // http://www.boost.org/doc/libs/1_38_0/libs/random/random_demo.cpp //// set the generator type to ... //// using RNG_typ = boost::minstd_rand; //using RNG_typ = boost::mt19937; //boost::thread_specific_ptr<RNG_typ> tss_random_base_generators; // //RNG_typ* get_random_base_generator() { // // get/init the base generator // RNG_typ* threads_random_base_generator = // tss_random_base_generators.get(); // if (!threads_random_base_generator) { // tss_random_base_generators.reset(new RNG_typ); // threads_random_base_generator = tss_random_base_generators.get(); // if (!threads_random_base_generator) // throw MVError("Could not create random number generator"); // // // seed to the os clock (secs since unix epoch) // // Caveat: std::time(0) is not a very good truly-random seed. // // logputl("Seeding random number generator to system clock"); // // decimal constants is unsigned only in C99" ie this number exceed max SIGNED // // integer // // (*threads_random_base_generator).seed(static_cast<unsigned // // int>(std::time(0)+2375472354)); // (*threads_random_base_generator) // .seed(static_cast<unsigned int>(std::time(0) + 2075472354)); // //(*thread_base_generator).seed(static_cast<unsigned int>(var().ostime().toInt())); // } // return threads_random_base_generator; //} using RNG_typ = std::mt19937; thread_local std::unique_ptr<RNG_typ> thread_RNG; // PickOS returns pseudo random integers in the range of 0-4 for rnd(5) var var::rnd() const { THISIS("var var::rnd() const") assertNumeric(function_sig); // Create a base generator per thread on the heap. Will be destroyed on thread termination. if (not thread_RNG.get()) var().initrnd(); int max = (*this).toInt() - 1; if (max < 0) return var(*this); // Define a integer range (0 to n-1) std::uniform_int_distribution<int> uniform_dist(0, max); // Generate a pseudo random number from the distribution using the seeded RNG return uniform_dist(*thread_RNG); //return x; } void var::initrnd() const { THISIS("void var::initrnd() const") assertDefined(function_sig); // Get a seed for the RNG uint64_t seed; if (this->unassigned()) { } else if (this->isnum()) { // Seed from number //seed = this->toLong(); seed = this->toInt(); } else if (var_typ & VARTYP_STR) { // Seed from string seed = 1; for (size_t ii = 0; ii < var_str.size(); ii++) seed *= var_str[ii]; // seed=MurmurHash64((char*)var_str.data(),int(var_str.size()*sizeof(char)),0); } else { // Seed from low resolution clock per second //seed.var_int = static_cast<unsigned int>(std::time(0) + 2'075'472'354); // Seed from high resolution clock seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); } // Set the new seed thread_RNG = std::make_unique<RNG_typ>(seed); } bool var::osgetenv(const char* envvarname) { THISIS("bool var::osgetenv(const char* envvarname)") assertDefined(function_sig); //assertStringMutator(function_sig); //ISSTRING(envvarname) // return whole environment if blank envvarname //if (envvarname.var_str.empty()) { if (*envvarname == 0) { var_str.clear(); //var_typ = VARTYP_STR; int i = 1; char* s = *environ; for (; s; i++) { // printf("%s\n", s); // var_str.append(boost::locale::conv::utf_to_utf<wchar_t>(s)); var_str.append(s); var_str.append("\n"); s = *(environ + i); } return true; } //TIP if you cant seem to osgetenv vars set in bash, then ensure you set them in bash with "export" //const char* cvalue = std::getenv(envvarname.var_str.c_str()); const char* cvalue = std::getenv(envvarname); if (cvalue == 0) { var_str.clear(); var_typ = VARTYP_STR; return false; } // *this = var(cvalue); var_str = cvalue; var_typ = VARTYP_STR; return true; } bool var::ossetenv(const char* envvarname) const { THISIS("bool var::ossetenv(const char* envvarname) const") assertString(function_sig); //ISSTRING(envvarname) //#ifdef _MSC_VER #ifndef setenv /* on windows this should be used BOOL WINAPI SetEnvironmentVariable(LPCTSTR lpName, LPCTSTR lpValue); */ // var("USING PUTENV").outputl(); // is this safe on windows?? // https://www.securecoding.cert.org/confluence/display/seccode/POS34-C.+Do+not+call+putenv()+with+a+pointer+to+an+automatic+variable+as+the+argument //std::string tempstr = envvarname.toString(); //tempstr += "="; //tempstr += toString(); // var(tempstr).outputl("temp std:string"); // std::cout<<tempstr<<" "<<tempstr.length()<<std::endl; // this will NOT work reliably since putenv will NOT COPY the local (i.e. temporary) // variable string //var("putenv " ^ var(tempstr) ).outputl(); //#pragma warning (disable : 4996) //const int result = putenv((char*)(tempstr.c_str())); //putenv("EXO_DATA=C:\\"); //std::cout<<getenv("EXO_DATA"); //char winenv[1024]; char* env = (char*)malloc(1024); //snprintf(env, 1024, "%s=%s", envvarname.var_str.c_str(), var_str.c_str()); snprintf(env, 1024, "%s=%s", envvarname, var_str.c_str()); //std::cout << winenv; int result = putenv(env); if (result == 0) return true; else return false; #else var("setenv " ^ envvarname ^ "=" ^ (*this)).outputl(); return setenv((char*)(envvarname.toString().c_str()), (char*)(toString().c_str()), 1); #endif } var var::ospid() const { //THISIS("var var::ospid() const") return getpid(); } } // namespace exodus
28.916318
150
0.70178
exodusdb
d3d74341214e42a6c90a87797b8fbaa336f66315
2,951
cpp
C++
exampleCreate/src/ofApp.cpp
armadillu/ofxTextureAtlas
b00b510acedc1211778b0f94b5a1c0753ea780d7
[ "MIT" ]
14
2015-03-31T03:33:34.000Z
2021-06-04T08:45:45.000Z
exampleCreate/src/ofApp.cpp
armadillu/ofxTextureAtlas
b00b510acedc1211778b0f94b5a1c0753ea780d7
[ "MIT" ]
1
2020-08-27T16:19:30.000Z
2020-08-27T16:53:43.000Z
exampleCreate/src/ofApp.cpp
armadillu/ofxTextureAtlas
b00b510acedc1211778b0f94b5a1c0753ea780d7
[ "MIT" ]
6
2015-08-05T20:45:19.000Z
2020-07-09T10:55:05.000Z
#include "ofApp.h" void ofApp::setup(){ ofSetFrameRate(60); ofSetVerticalSync(true); ofEnableAlphaBlending(); ofBackground(22); scale = 1.0; // LISTENERS ofAddListener(atlasCreator.eventAtlasCreationFinished, this, &ofApp::onAtlasCreationFinished); vector<string> fileList; ofDirectory d; d.allowExt("jpg"); d.listDir("images/cats"); //you are expected to put a ton of images in there. d.sort(); for(int i = 0; i < d.numFiles(); i++){ fileList.push_back(d.getPath(i)); } fileList.resize(MIN(500, fileList.size())); //lets limit the file list to 500 // CREATE ATLAS (+ callback to save) ////////////////////////// //create as many atlases as required to fit all those images in atlases of 4096 x 4096 //each image being 256 at the most. atlasCreator.createAtlases( fileList, 4096, //fbo/atlas size GL_RGB, //internal format ofVec2f(400,400), //maxItemSideSize 2.0, //padding true, //mipmaps -0.9 //mipmap bias ); } void ofApp::onAtlasCreationFinished(bool & arg){ //once atlases are created, save them to disk, so that we can load them next time //without having to recreate them atlasCreator.saveToDisk("textureCache", "png"); //save in a folder named "textureCache", in png format } void ofApp::update(){ float dt = 1./60.; } void ofApp::draw(){ ofDrawBitmapString("Progress: " + ofToString(atlasCreator.getPercentDone() * 100,1), 30, 50); if(atlasCreator.isCreating()){ //atlass construction process ofTexture * atlas = atlasCreator.getCurrentlyCreatedAtlas(); atlas->draw(0,0, ofGetHeight(), ofGetHeight()); ofDrawBitmapStringHighlight("Creating Atlas: " + ofToString(atlasCreator.getPercentDone(), 2) + "\n" + atlasCreator.getCurrentCreatingFileName(), 30, 30 ); } if(atlasCreator.isIdle() ){ int x = 0; for(int i = 0; i < atlasCreator.getNumAtlases(); i++){ ofFbo & fbo = atlasCreator.getAtlasAtIndex(i)->getFbo(); fbo.draw(ofGetMouseX() + x, ofGetMouseY(), fbo.getWidth() * scale, fbo.getHeight() * scale); x += fbo.getWidth() * scale; } } if(debug && atlasCreator.isIdle()){ ofClear(0); int x = 0; for(int i = 0; i < atlasCreator.getNumAtlases(); i++){ atlasCreator.getAtlasAtIndex(i)->drawDebug(ofGetMouseX() + x,ofGetMouseY()); x += atlasCreator.getAtlasAtIndex(i)->getFbo().getWidth(); } } } void ofApp::keyPressed(int key){ debug ^= true; } void ofApp::mouseScrolled( float x, float y ){ scale += y * 0.02; scale = ofClamp(scale, 0.02, 1.0); } void ofApp::keyReleased(int key){ } void ofApp::mouseMoved(int x, int y ){ } void ofApp::mouseDragged(int x, int y, int button){ } void ofApp::mousePressed(int x, int y, int button){ } void ofApp::mouseReleased(int x, int y, int button){ } void ofApp::windowResized(int w, int h){ } void ofApp::gotMessage(ofMessage msg){ } void ofApp::dragEvent(ofDragInfo dragInfo){ }
21.078571
103
0.657743
armadillu
d3dad5e4742f11f9bf68785339a8b1d4e991c4e1
10,887
cpp
C++
SNCCore/SNCLib/SNCLink.cpp
rt-ispace/SNC
890acbbe336bb0429f47fa7bed499a46215aac64
[ "MIT" ]
1
2021-08-08T05:40:52.000Z
2021-08-08T05:40:52.000Z
SNCCore/SNCLib/SNCLink.cpp
rt-ispace/SNC
890acbbe336bb0429f47fa7bed499a46215aac64
[ "MIT" ]
null
null
null
SNCCore/SNCLib/SNCLink.cpp
rt-ispace/SNC
890acbbe336bb0429f47fa7bed499a46215aac64
[ "MIT" ]
1
2021-08-08T05:40:56.000Z
2021-08-08T05:40:56.000Z
//////////////////////////////////////////////////////////////////////////// // // This file is part of SNC // // Copyright (c) 2014-2021, Richard Barnett // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "SNCDefs.h" #include "SNCLink.h" //#define SNCLINK_TRACE #define TAG "SNCLink" SNCMessageWrapper::SNCMessageWrapper() { m_next = NULL; m_cmd = 0; m_len = 0; m_msg = NULL; m_ptr = NULL; m_bytesLeft = 0; } SNCMessageWrapper::~SNCMessageWrapper() { if (m_msg != NULL) { free(m_msg); m_msg = NULL; } } // Public routines // void SNCLink::send(int cmd, int len, int priority, SNC_MESSAGE *SNCMessage) { SNCMessageWrapper *wrapper; #ifdef SNCLINK_TRACE SNCUtils::logDebug(TAG, QString("Send - cmd = %1, len = %2, priority= %3").arg(cmd).arg(len).arg(priority); #endif QMutexLocker locker(&m_TXLock); wrapper = new SNCMessageWrapper(); wrapper->m_len = len; wrapper->m_msg = SNCMessage; wrapper->m_ptr = (unsigned char *)SNCMessage; wrapper->m_bytesLeft = len; // set up SNCMESSAGE header SNCMessage->cmd = cmd; SNCMessage->flags = priority; SNCMessage->spare = 0; SNCUtils::convertIntToUC4(len, SNCMessage->len); computeChecksum(SNCMessage); addToTXQueue(wrapper, priority); } bool SNCLink::receive(int priority, int *cmd, int *len, SNC_MESSAGE **SNCMessage) { SNCMessageWrapper *wrapper; QMutexLocker locker(&m_RXLock); if ((wrapper = getRXHead(priority)) != NULL) { *cmd = wrapper->m_cmd; *len = wrapper->m_len; *SNCMessage = wrapper->m_msg; wrapper->m_msg = NULL; #ifdef SNCLINK_TRACE SNCUtils::logDebug(TAG, QString("Receive - cmd = %1, len = %2, priority = %3").arg(*cmd).arg(*len).arg(priority); #endif delete wrapper; return true; } return false; } int SNCLink::tryReceiving(SNCSocket *sock) { int bytesRead; int len; SNCMessageWrapper *wrapper; QMutexLocker locker(&m_RXLock); while (1) { if (m_RXSM) { // still waiting for message header bytesRead = sock->sockReceive((unsigned char *)&m_SNCMessage + sizeof(SNC_MESSAGE) - m_RXIPBytesLeft , m_RXIPBytesLeft); if (bytesRead <= 0) return 0; m_RXIPBytesLeft -= bytesRead; if (m_RXIPBytesLeft == 0) { // got complete SNC_MESSAGE header if (!checkChecksum(&m_SNCMessage)) { SNCUtils::logError(TAG, QString("Incorrect header cksm")); flushReceive(sock); continue; } #ifdef SNCLINK_TRACE TRACE2("Received hdr %d %d", m_SNCMessage.cmd, SNCUtils::convertUC4ToInt(m_SNCMessage.len)); #endif m_RXIPPriority = m_SNCMessage.flags & SNCLINK_PRI; len = SNCUtils::convertUC4ToInt(m_SNCMessage.len); if (m_RXIP[m_RXIPPriority] == NULL) { // nothing in progress at this priority m_RXIP[m_RXIPPriority] = new SNCMessageWrapper(); m_RXIP[m_RXIPPriority]->m_cmd = m_SNCMessage.cmd; m_RXIP[m_RXIPPriority]->m_msg = (SNC_MESSAGE *)malloc(len); if (len > (int)sizeof(SNC_MESSAGE)) { m_RXIP[m_RXIPPriority]->m_ptr = (unsigned char *)m_RXIP[m_RXIPPriority]->m_msg + sizeof(SNC_MESSAGE); // we've already received that } } wrapper = m_RXIP[m_RXIPPriority]; memcpy(wrapper->m_msg, &m_SNCMessage, sizeof(SNC_MESSAGE)); wrapper->m_len = len; if (len == sizeof(SNC_MESSAGE)) { // no message part addToRXQueue(wrapper, m_RXIPPriority); m_RXIP[m_RXIPPriority] = NULL; resetReceive(m_RXIPPriority); continue; } else { // is a message part if ((m_SNCMessage.cmd < SNCMSG_HEARTBEAT) || (m_SNCMessage.cmd > SNCMSG_MAX)) { SNCUtils::logError(TAG, QString("Illegal cmd %1").arg(m_SNCMessage.cmd)); flushReceive(sock); free(wrapper->m_msg); wrapper->m_msg = NULL; resetReceive(m_RXIPPriority); continue; } if (len >= SNC_MESSAGE_MAX) { SNCUtils::logError(TAG, QString("Illegal length message cmd %1, len %2").arg(m_SNCMessage.cmd).arg(len)); flushReceive(sock); free(wrapper->m_msg); wrapper->m_msg = NULL; resetReceive(m_RXIPPriority); continue; } wrapper->m_bytesLeft = len - sizeof(SNC_MESSAGE); // since we've already received that m_RXSM = false; } } } else { // now waiting for data wrapper = m_RXIP[m_RXIPPriority]; bytesRead = sock->sockReceive(wrapper->m_ptr, wrapper->m_bytesLeft); if (bytesRead <= 0) return 0; wrapper->m_bytesLeft -= bytesRead; wrapper->m_ptr += bytesRead; if (wrapper->m_bytesLeft == 0) { // got complete message addToRXQueue(m_RXIP[m_RXIPPriority], m_RXIPPriority); m_RXIP[m_RXIPPriority] = NULL; m_RXSM = true; m_RXIPMsgPtr = (unsigned char *)&m_SNCMessage; m_RXIPBytesLeft = sizeof(SNC_MESSAGE); } } } } int SNCLink::trySending(SNCSocket *sock) { int bytesSent; int priority; SNCMessageWrapper *wrapper; QMutexLocker locker(&m_TXLock); if (sock == NULL) return 0; priority = SNCLINK_HIGHPRI; while(1) { if (m_TXIP[priority] == NULL) { m_TXIP[priority] = getTXHead(priority); if (m_TXIP[priority] == NULL) { priority++; if (priority > SNCLINK_LOWPRI) return 0; // nothing to do and no error continue; } } wrapper = m_TXIP[priority]; bytesSent = sock->sockSend(wrapper->m_ptr, wrapper->m_bytesLeft); if (bytesSent <= 0) return 0; // assume buffer full wrapper->m_bytesLeft -= bytesSent; wrapper->m_ptr += bytesSent; if (wrapper->m_bytesLeft == 0) { // finished this message delete m_TXIP[priority]; m_TXIP[priority] = NULL; } } } SNCLink::SNCLink(const QString& logTag) { m_logTag = logTag; for (int i = 0; i < SNCLINK_PRIORITIES; i++) { m_TXHead[i] = NULL; m_TXTail[i] = NULL; m_RXHead[i] = NULL; m_RXTail[i] = NULL; m_RXIP[i] = NULL; m_TXIP[i] = NULL; } m_RXSM = true; m_RXIPMsgPtr = (unsigned char *)&m_SNCMessage; m_RXIPBytesLeft = sizeof(SNC_MESSAGE); } SNCLink::~SNCLink(void) { clearTXQueue(); clearRXQueue(); } void SNCLink::addToTXQueue(SNCMessageWrapper *wrapper, int priority) { if (m_TXHead[priority] == NULL) { m_TXHead[priority] = wrapper; m_TXTail[priority] = wrapper; wrapper->m_next = NULL; return; } m_TXTail[priority]->m_next = wrapper; m_TXTail[priority] = wrapper; wrapper->m_next = NULL; } void SNCLink::addToRXQueue(SNCMessageWrapper *wrapper, int priority) { if (m_RXHead[priority] == NULL) { m_RXHead[priority] = wrapper; m_RXTail[priority] = wrapper; wrapper->m_next = NULL; return; } m_RXTail[priority]->m_next = wrapper; m_RXTail[priority] = wrapper; wrapper->m_next = NULL; } SNCMessageWrapper *SNCLink::getTXHead(int priority) { SNCMessageWrapper *wrapper; if (m_TXHead[priority] == NULL) return NULL; wrapper = m_TXHead[priority]; m_TXHead[priority] = wrapper->m_next; return wrapper; } SNCMessageWrapper *SNCLink::getRXHead(int priority) { SNCMessageWrapper *wrapper; if (m_RXHead[priority] == NULL) return NULL; wrapper = m_RXHead[priority]; m_RXHead[priority] = wrapper->m_next; return wrapper; } void SNCLink::clearTXQueue() { for (int i = 0; i < SNCLINK_PRIORITIES; i++) { while (m_TXHead[i] != NULL) delete getTXHead(i); if (m_TXIP[i] != NULL) delete m_TXIP[i]; m_TXIP[i] = NULL; } } void SNCLink::flushReceive(SNCSocket *sock) { unsigned char buf[1000]; while (sock->sockReceive(buf, 1000) > 0) ; } void SNCLink::resetReceive(int priority) { m_RXSM = true; m_RXIPMsgPtr = (unsigned char *)&m_SNCMessage; m_RXIPBytesLeft = sizeof(SNC_MESSAGE); if (m_RXIP[priority] != NULL) { delete m_RXIP[priority]; m_RXIP[priority] = NULL; } } void SNCLink::clearRXQueue() { for (int i = 0; i < SNCLINK_PRIORITIES; i++) { while (m_RXHead[i] != NULL) delete getRXHead(i); if (m_RXIP[i] != NULL) delete m_RXIP[i]; m_RXIP[i] = NULL; resetReceive(i); } } void SNCLink::computeChecksum(SNC_MESSAGE *SNCMessage) { unsigned char sum; unsigned char *array; sum = 0; array = (unsigned char *)SNCMessage; for (size_t i = 0; i < sizeof(SNC_MESSAGE)-1; i++) sum += *array++; SNCMessage->cksm = -sum; } bool SNCLink::checkChecksum(SNC_MESSAGE *SNCMessage) { unsigned char sum; unsigned char *array; sum = 0; array = (unsigned char *)SNCMessage; for (size_t i = 0; i < sizeof(SNC_MESSAGE); i++) sum += *array++; return sum == 0; }
28.725594
156
0.576467
rt-ispace
d3de2fad0c36ff5e1de05d695371ae10e9d0cf5e
2,220
cpp
C++
test/framework/tMatcherFactory.cpp
xiaohongchen1991/clang-xform
bd0cf899760b53b24e10ca4baab3c4e281535b97
[ "MIT" ]
2
2020-02-18T18:09:45.000Z
2020-05-10T18:38:38.000Z
test/framework/tMatcherFactory.cpp
xiaohongchen1991/clang-xform
bd0cf899760b53b24e10ca4baab3c4e281535b97
[ "MIT" ]
null
null
null
test/framework/tMatcherFactory.cpp
xiaohongchen1991/clang-xform
bd0cf899760b53b24e10ca4baab3c4e281535b97
[ "MIT" ]
1
2020-02-18T18:09:48.000Z
2020-02-18T18:09:48.000Z
/* MIT License Copyright (c) 2019 Xiaohong Chen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "MatcherFactory.hpp" #include "MockMatchCallback.hpp" #include "gtest/gtest.h" namespace { std::unique_ptr<MatchCallbackBase> CreateMockMatchCallback(const std::string& id, clang::tooling::Replacements& replacements, std::vector<std::string> args) { return std::make_unique<MockMatchCallback>(id, replacements, std::move(args)); } } // end of anonymous namespace TEST(MatcherFactoryTest, CreateMatchCallback) { MatcherFactory& factory = MatcherFactory::Instance(); std::string id = "TestMatcherFactory"; // register new matcher factory.RegisterMatchCallback(id, CreateMockMatchCallback); clang::tooling::Replacements replacements; std::vector<std::string> args; // create MatchCallback EXPECT_TRUE(factory.CreateMatchCallback(id, replacements, args)); EXPECT_FALSE(factory.CreateMatchCallback("not_registered", replacements, args)); ASSERT_TRUE(factory.getMatcherMap().count(id)); EXPECT_TRUE(factory.getMatcherMap().at(id) == CreateMockMatchCallback); }
43.529412
102
0.735135
xiaohongchen1991
d3deb3e3c43d1ea4de8861e5764160d62eb9ba17
4,465
cpp
C++
test/swap.cpp
sieren/variant
99ef8fb19f5ea5f229587da3dd425a7d24c4fd80
[ "BSL-1.0" ]
564
2015-10-07T06:23:04.000Z
2022-03-25T17:17:49.000Z
test/swap.cpp
sieren/variant
99ef8fb19f5ea5f229587da3dd425a7d24c4fd80
[ "BSL-1.0" ]
76
2015-10-28T10:19:02.000Z
2021-08-17T02:28:36.000Z
test/swap.cpp
sieren/variant
99ef8fb19f5ea5f229587da3dd425a7d24c4fd80
[ "BSL-1.0" ]
88
2015-10-23T00:26:58.000Z
2022-03-03T09:47:27.000Z
// MPark.Variant // // Copyright Michael Park, 2015-2017 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <mpark/variant.hpp> #include <string> #include <gtest/gtest.h> #include "util.hpp" TEST(Swap, Same) { mpark::variant<int, std::string> v("hello"); mpark::variant<int, std::string> w("world"); // Check `v`. EXPECT_EQ("hello", mpark::get<std::string>(v)); // Check `w`. EXPECT_EQ("world", mpark::get<std::string>(w)); // Swap. using std::swap; swap(v, w); // Check `v`. EXPECT_EQ("world", mpark::get<std::string>(v)); // Check `w`. EXPECT_EQ("hello", mpark::get<std::string>(w)); } TEST(Swap, Different) { mpark::variant<int, std::string> v(42); mpark::variant<int, std::string> w("hello"); // Check `v`. EXPECT_EQ(42, mpark::get<int>(v)); // Check `w`. EXPECT_EQ("hello", mpark::get<std::string>(w)); // Swap. using std::swap; swap(v, w); // Check `v`. EXPECT_EQ("hello", mpark::get<std::string>(v)); // Check `w`. EXPECT_EQ(42, mpark::get<int>(w)); } #ifdef MPARK_EXCEPTIONS TEST(Swap, OneValuelessByException) { // `v` normal, `w` corrupted. mpark::variant<int, move_thrower_t> v(42), w(42); EXPECT_THROW(w = move_thrower_t{}, MoveConstruction); EXPECT_EQ(42, mpark::get<int>(v)); EXPECT_TRUE(w.valueless_by_exception()); // Swap. using std::swap; swap(v, w); // Check `v`, `w`. EXPECT_TRUE(v.valueless_by_exception()); EXPECT_EQ(42, mpark::get<int>(w)); } TEST(Swap, BothValuelessByException) { // `v`, `w` both corrupted. mpark::variant<int, move_thrower_t> v(42); EXPECT_THROW(v = move_thrower_t{}, MoveConstruction); mpark::variant<int, move_thrower_t> w(v); EXPECT_TRUE(v.valueless_by_exception()); EXPECT_TRUE(w.valueless_by_exception()); // Swap. using std::swap; swap(v, w); // Check `v`, `w`. EXPECT_TRUE(v.valueless_by_exception()); EXPECT_TRUE(w.valueless_by_exception()); } #endif TEST(Swap, DtorsSame) { struct Obj { Obj(size_t *dtor_count) : dtor_count_(dtor_count) {} Obj(const Obj &) = default; Obj(Obj &&) = default; ~Obj() { ++(*dtor_count_); } Obj &operator=(const Obj &) = default; Obj &operator=(Obj &&) = default; size_t *dtor_count_; }; // Obj size_t v_count = 0; size_t w_count = 0; { mpark::variant<Obj> v{&v_count}, w{&w_count}; using std::swap; swap(v, w); // Calls `std::swap(Obj &lhs, Obj &rhs)`, with which we perform: // ``` // { // Obj temp(move(lhs)); // lhs = move(rhs); // rhs = move(temp); // } `++v_count` from `temp::~Obj()`. // ``` EXPECT_EQ(1u, v_count); EXPECT_EQ(0u, w_count); } EXPECT_EQ(2u, v_count); EXPECT_EQ(1u, w_count); } namespace detail { struct Obj { Obj(size_t *dtor_count) : dtor_count_(dtor_count) {} Obj(const Obj &) = default; Obj(Obj &&) = default; ~Obj() { ++(*dtor_count_); } Obj &operator=(const Obj &) = default; Obj &operator=(Obj &&) = default; size_t *dtor_count_; }; // Obj static void swap(Obj &lhs, Obj &rhs) noexcept { std::swap(lhs.dtor_count_, rhs.dtor_count_); } } // namespace detail TEST(Swap, DtorsSameWithSwap) { size_t v_count = 0; size_t w_count = 0; { mpark::variant<detail::Obj> v{&v_count}, w{&w_count}; using std::swap; swap(v, w); // Calls `detail::swap(Obj &lhs, Obj &rhs)`, with which doesn't call any destructors. EXPECT_EQ(0u, v_count); EXPECT_EQ(0u, w_count); } EXPECT_EQ(1u, v_count); EXPECT_EQ(1u, w_count); } TEST(Swap, DtorsDifferent) { struct V { V(size_t *dtor_count) : dtor_count_(dtor_count) {} V(const V &) = default; V(V &&) = default; ~V() { ++(*dtor_count_); } V &operator=(const V &) = default; V &operator=(V &&) = default; size_t *dtor_count_; }; // V struct W { W(size_t *dtor_count) : dtor_count_(dtor_count) {} W(const W &) = default; W(W &&) = default; ~W() { ++(*dtor_count_); } W &operator=(const W &) = default; W &operator=(W &&) = default; size_t *dtor_count_; }; // W size_t v_count = 0; size_t w_count = 0; { mpark::variant<V, W> v{mpark::in_place_type_t<V>{}, &v_count}; mpark::variant<V, W> w{mpark::in_place_type_t<W>{}, &w_count}; using std::swap; swap(v, w); EXPECT_EQ(1u, v_count); EXPECT_EQ(2u, w_count); } EXPECT_EQ(2u, v_count); EXPECT_EQ(3u, w_count); }
25.514286
89
0.610974
sieren
d3e1c859769c49e51a6c38d76fa289fd7bff8304
24,184
cpp
C++
src/examples/commonExamples/persistenceExample/src/TestModel.cpp
MDE4CPP/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
12
2017-02-17T10:33:51.000Z
2022-03-01T02:48:10.000Z
src/examples/commonExamples/persistenceExample/src/TestModel.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
28
2017-10-17T20:23:52.000Z
2021-03-04T16:07:13.000Z
src/examples/commonExamples/persistenceExample/src/TestModel.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
22
2017-03-24T19:03:58.000Z
2022-03-31T12:10:07.000Z
/* * TestModel.cpp * * Created on: 23.06.2017 * Author: Alexander */ #include "TestModel.hpp" #include "ecore/EAnnotation.hpp" #include "ecore/EAttribute.hpp" #include "ecore/EClass.hpp" #include "ecore/EEnum.hpp" #include "ecore/EEnumLiteral.hpp" #include "ecore/EStringToStringMapEntry.hpp" #include "ecore/EOperation.hpp" #include "ecore/EReference.hpp" #include "ecore/ecoreFactory.hpp" #include "ecore/ecorePackage.hpp" #include "uml/umlPackage.hpp" #include "abstractDataTypes/SubsetUnion.hpp" using namespace testmodel; TestModel::TestModel() { } TestModel::~TestModel() { } std::shared_ptr<ecore::EPackage> TestModel::getMetaMetaPackage() { return ecore::ecorePackage::eInstance(); } std::shared_ptr<ecore::EObject> TestModel::createEcoreTestMetaModel() { std::shared_ptr<ecore::ecorePackage> package = ecore::ecorePackage::eInstance(); std::shared_ptr<ecore::ecoreFactory> factory = ecore::ecoreFactory::eInstance(); // Create package 'pck_UniModel' and set some default package information std::shared_ptr<ecore::EPackage> pck_UniModel = factory->createEPackage(); { pck_UniModel->setName("UniModelPackage"); pck_UniModel->setNsPrefix("Uni"); pck_UniModel->setNsURI("http://www.examples.org/Uni"); } // Create new subpackage 'pck_enum' and insert into package 'pck_UniModel' std::shared_ptr<ecore::EPackage> pck_enum(factory->createEPackage_in_ESuperPackage(pck_UniModel)); { { // set name and prefix of subpackage pck_enum->setName("EnumPackage"); pck_enum->setNsPrefix("enum"); } } // Create new subpackage and insert into package 'pck_UniModel' (alternative variant) std::shared_ptr<ecore::EPackage> pck_class(factory->createEPackage_in_ESuperPackage(pck_UniModel)); { { // set name and prefix of subpackage pck_class->setName("ClassPackage"); pck_class->setNsPrefix("cls"); } } // Create ENUMs that are used in classes std::shared_ptr<ecore::EEnum> enum_Geschlecht(factory->createEEnum_in_EPackage(pck_enum)); { enum_Geschlecht->setName("EnumGeschlecht"); // Create const attributes (literals) std::shared_ptr<Bag<ecore::EEnumLiteral>> list_ELiteral = enum_Geschlecht->getELiterals(); { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Geschlecht)); literal->setName("MAENNLICH"); literal->setLiteral("MAENNLICH"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Geschlecht)); literal->setName("WEIBLICH"); literal->setLiteral("WEIBLICH"); literal->setValue(1); } } std::shared_ptr<ecore::EEnum> enum_Verein(factory->createEEnum_in_EPackage(pck_enum)); { enum_Verein->setName("EnumVerein"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Verein)); literal->setName("BC"); literal->setLiteral("BC"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Verein)); literal->setName("BD"); literal->setLiteral("BD"); literal->setValue(1); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Verein)); literal->setName("BH"); literal->setLiteral("BH"); literal->setValue(2); } } std::shared_ptr<ecore::EEnum> enum_Position(factory->createEEnum_in_EPackage(pck_enum)); { enum_Position->setName("EnumPosition"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Position)); literal->setName("PROFESSOR"); literal->setLiteral("PROFESSOR"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Position)); literal->setName("WMA"); literal->setLiteral("WMA"); literal->setValue(1); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Position)); literal->setName("HIWI"); literal->setLiteral("HIWI"); literal->setValue(2); } } std::shared_ptr<ecore::EEnum> enum_StudentStatus(factory->createEEnum_in_EPackage(pck_enum)); { enum_StudentStatus->setName("EnumStudentStatus"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_StudentStatus)); literal->setName("BACHELOR"); literal->setLiteral("BACHELOR"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_StudentStatus)); literal->setName("MASTER"); literal->setLiteral("MASTER"); literal->setValue(1); } } std::shared_ptr<ecore::EEnum> enum_Veranstaltung(factory->createEEnum_in_EPackage(pck_enum)); { enum_Veranstaltung->setName("EnumVeranstaltung"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Veranstaltung)); literal->setName("VORLESUNG"); literal->setLiteral("VORLESUNG"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Veranstaltung)); literal->setName("SEMINAR"); literal->setLiteral("SEMINAR"); literal->setValue(1); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Veranstaltung)); literal->setName("PRAKTIKUM"); literal->setLiteral("PRAKTIKUM"); literal->setValue(2); } } // Create some classes with attributes, operations, compositions and association to each other std::shared_ptr<ecore::EClass> cls_UniModel(factory->createEClass_in_EPackage(pck_class)); { cls_UniModel->setName("UniModel"); cls_UniModel->setInterface(false); cls_UniModel->setAbstract(false); } std::shared_ptr<ecore::EClass> cls_Universitaet(factory->createEClass_in_EPackage(pck_class)); { cls_Universitaet->setName("Universitaet"); cls_Universitaet->setInterface(false); cls_Universitaet->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Universitaet)); attrib->setName("name"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Mensch(factory->createEClass_in_EPackage(pck_class)); { cls_Mensch->setName("Mensch"); cls_Mensch->setInterface(false); cls_Mensch->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mensch)); attrib->setName("lastname"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mensch)); attrib->setName("firstname"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mensch)); attrib->setName("sex"); attrib->setEType(enum_Geschlecht); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Person(factory->createEClass_in_EPackage(pck_class)); { cls_Person->setName("Person"); cls_Person->setInterface(true); cls_Person->setAbstract(false); // Add SuperType { std::shared_ptr<Bag<ecore::EClass>> list_ESuperTypes = cls_Person->getESuperTypes(); list_ESuperTypes->push_back(cls_Mensch); list_ESuperTypes->push_back(cls_Universitaet); // TODO this does not make sense, and is just for testing multiple ESuperTypes. } // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Person)); attrib->setName("id"); attrib->setEType(package->getEBigInteger_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } // Create operations, set their names and types { std::shared_ptr<ecore::EOperation> operation(factory->createEOperation_in_EContainingClass(cls_Person)); operation->setName("addVeranstaltung"); // Type: void operation->setEType(package->getEBoolean_Class()); operation->setOrdered(true); // default: ordered=true operation->setUnique(true); // default: unique=true operation->setLowerBound(0); operation->setUpperBound(1); // default: upperBound=1 { std::shared_ptr<ecore::EAnnotation> annotation(factory->createEAnnotation_in_EModelElement(operation)); annotation->setSource("http://sse.tu-ilmenau.de/codegen"); std::shared_ptr<Bag<ecore::EStringToStringMapEntry>> list_EStringToStringMapEntry = annotation->getDetails(); { std::shared_ptr<ecore::EStringToStringMapEntry> stringToStringMapEntry(factory->createEStringToStringMapEntry()); stringToStringMapEntry->setKey("body"); stringToStringMapEntry->setValue( " if (someOperation->getEContainingClass()->isSuperTypeOf(getEContainingClass()) &amp;&amp; (someOperation->getName()==getName()))&#xD;&#xA; {&#xD;&#xA; std::shared_ptr&lt; Bag&lt;ecore::EParameter> > parameters = getEParameters();&#xD;&#xA; std::shared_ptr&lt; Bag&lt;ecore::EParameter> > otherParameters = someOperation->getEParameters();&#xD;&#xA; if (parameters->size() == otherParameters->size())&#xD;&#xA; {&#xD;&#xA; for (Bag&lt;EParameter> ::iterator i = parameters->begin(), j = otherParameters->begin(); i != parameters->end(); ++i,++j )&#xD;&#xA; &#x9;{&#xD;&#xA; &#x9;std::shared_ptr&lt;EParameter> parameter = *i;&#xD;&#xA; &#x9;std::shared_ptr&lt;EParameter> otherParameter = *j;&#xD;&#xA; if (!(parameter->getEType().get() == otherParameter->getEType().get()))&#xD;&#xA; &#x9;&#x9;{&#xD;&#xA; return false;&#xD;&#xA; &#x9;&#x9;}&#xD;&#xA; &#x9;}&#xD;&#xA;&#x9;&#x9;}&#xD;&#xA;&#x9;&#x9;return true;&#xD;&#xA;&#x9;}"); list_EStringToStringMapEntry->push_back(stringToStringMapEntry); } } { std::shared_ptr<ecore::EAnnotation> annotation(factory->createEAnnotation_in_EModelElement(operation)); annotation->setSource("http://sse.tu-ilmenau.de/HansPeter"); std::shared_ptr<Bag<ecore::EStringToStringMapEntry>> list_EStringToStringMapEntry = annotation->getDetails(); { std::shared_ptr<ecore::EStringToStringMapEntry> stringToStringMapEntry(factory->createEStringToStringMapEntry()); stringToStringMapEntry->setKey("body"); stringToStringMapEntry->setValue("any source \n here is newline \t here is a tabulator"); list_EStringToStringMapEntry->push_back(stringToStringMapEntry); } } } { std::shared_ptr<ecore::EOperation> operation(factory->createEOperation_in_EContainingClass(cls_Person)); operation->setName("removeVeranstaltung"); // Type: void operation->setEType(package->getEChar_Class()); operation->setOrdered(true); // default: ordered=true operation->setUnique(true); // default: unique=true operation->setLowerBound(0); operation->setUpperBound(1); // default: upperBound=1 } } std::shared_ptr<ecore::EClass> cls_Mitarbeiter(factory->createEClass_in_EPackage(pck_class)); { cls_Mitarbeiter->setName("Mitarbeiter"); cls_Mitarbeiter->setInterface(false); cls_Mitarbeiter->setAbstract(false); // Add SuperType { std::shared_ptr<Bag<ecore::EClass>> list_ESuperTypes = cls_Mitarbeiter->getESuperTypes(); list_ESuperTypes->push_back(cls_Person); } // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mitarbeiter)); attrib->setName("position"); attrib->setEType(enum_Position); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mitarbeiter)); attrib->setName("gehalt"); attrib->setEType(package->getEFloat_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mitarbeiter)); attrib->setName("office"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Student(factory->createEClass_in_EPackage(pck_class)); { cls_Student->setName("Student"); cls_Student->setInterface(false); cls_Student->setAbstract(false); // Add SuperType { std::shared_ptr<Bag<ecore::EClass>> list_ESuperTypes = cls_Student->getESuperTypes(); list_ESuperTypes->push_back(cls_Person); } // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Student)); attrib->setName("status"); attrib->setEType(enum_StudentStatus); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Veranstaltung(factory->createEClass_in_EPackage(pck_class)); { cls_Veranstaltung->setName("Veranstaltung"); cls_Veranstaltung->setInterface(false); cls_Veranstaltung->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Veranstaltung)); attrib->setName("name"); attrib->setEType(enum_Veranstaltung); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Veranstaltung)); attrib->setName("maxTeilnehmer"); attrib->setEType(package->getEInt_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Verein(factory->createEClass_in_EPackage(pck_class)); { cls_Verein->setName("Verein"); cls_Verein->setInterface(false); cls_Verein->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Verein)); attrib->setName("name"); attrib->setEType(enum_Verein); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } // Create Compositions and Associations { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_UniModel)); reference->setName("universitaet"); reference->setEType(cls_Universitaet); reference->setContainment(true); // set reference as composition reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Universitaet)); reference->setName("person"); reference->setEType(cls_Person); reference->setContainment(true); // set reference as composition reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Universitaet)); reference->setName("veranstaltung"); reference->setEType(cls_Veranstaltung); reference->setContainment(true); // set reference as composition reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Person)); reference->setName("veranstaltung"); reference->setEType(cls_Veranstaltung); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Veranstaltung)); reference->setName("dozent"); reference->setEType(cls_Person); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Veranstaltung)); reference->setName("student"); reference->setEType(cls_Person); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Student)); reference->setName("verein"); reference->setEType(cls_Verein); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } return std::dynamic_pointer_cast<ecore::EObject>(pck_UniModel); }
34.401138
1,069
0.724405
MDE4CPP
d3e2fdd3f504c29cb6ad9b28fd086f457d16fdb9
1,215
cpp
C++
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/bn/exp.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/bn/exp.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/bn/exp.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
/* unused */ #include <openssl/tmdiff.h> #include "bn_lcl.h" #ifdef OPENSSL_SYS_WINDOWS #include <stdio.h> #endif #define SIZE 256 #define NUM (8*8*8) #define MOD (8*8*8*8*8) main(argc,argv) int argc; char *argv[]; { BN_CTX ctx; BIGNUM a,b,c,r,rr,t,l; int j,i,size=SIZE,num=NUM,mod=MOD; char *start,*end; BN_MONT_CTX mont; double d,md; BN_MONT_CTX_init(&mont); BN_CTX_init(&ctx); BN_init(&a); BN_init(&b); BN_init(&c); BN_init(&r); start=ms_time_new(); end=ms_time_new(); while (size <= 1024*8) { BN_rand(&a,size,0,0); BN_rand(&b,size,1,0); BN_rand(&c,size,0,1); BN_mod(&a,&a,&c,&ctx); ms_time_get(start); for (i=0; i<10; i++) BN_MONT_CTX_set(&mont,&c,&ctx); ms_time_get(end); md=ms_time_diff(start,end); ms_time_get(start); for (i=0; i<num; i++) { /* bn_mull(&r,&a,&b,&ctx); */ /* BN_sqr(&r,&a,&ctx); */ BN_mod_exp_mont(&r,&a,&b,&c,&ctx,&mont); } ms_time_get(end); d=ms_time_diff(start,end)/* *50/33 */; TINYCLR_SSL_PRINTF("%5d bit:%6.2f %6d %6.4f %4d m_set(%5.4f)\n",size, d,num,d/num,(int)((d/num)*mod),md/10.0); num/=8; mod/=8; if (num <= 0) num=1; size*=2; } }
18.692308
72
0.566255
PervasiveDigital
d3e38cd7842b0930f499e645a371ac410f5f4d08
17,368
cpp
C++
source/response/Netcdf4ClassicResponse.cpp
fmidev/smartmet-plugin-wcs
60aee4d3ef9d2bba5de44b4a871f669fc1b47d08
[ "MIT" ]
null
null
null
source/response/Netcdf4ClassicResponse.cpp
fmidev/smartmet-plugin-wcs
60aee4d3ef9d2bba5de44b4a871f669fc1b47d08
[ "MIT" ]
8
2017-04-07T13:14:46.000Z
2018-04-25T08:04:22.000Z
source/response/Netcdf4ClassicResponse.cpp
fmidev/smartmet-plugin-wcs
60aee4d3ef9d2bba5de44b4a871f669fc1b47d08
[ "MIT" ]
1
2017-06-03T19:07:22.000Z
2017-06-03T19:07:22.000Z
#include "Netcdf4ClassicResponse.h" #include "DataContainer.h" #include "Options.h" #include "ParamConfig.h" #include "UniqueTemporaryPath.h" #include "WcsConvenience.h" #include "WcsException.h" #include <macgyver/StringConversion.h> #include <spine/ParameterFactory.h> namespace SmartMet { namespace Plugin { namespace WCS { void Netcdf4ClassicResponse::get(std::ostream& output) { const auto querydata = dynamic_cast<const Engine::Querydata::Engine*>(getEngine()); if (not querydata) throw std::runtime_error("Cast from SmartMetEngine to Querydata failded."); if (not getOptions()) throw std::runtime_error("Options object is not set."); auto opt = std::dynamic_pointer_cast<Options>(getOptions()); if (not opt) throw std::runtime_error("Cannot cast query options object from OptionsBase to Options."); Abbreviations::Shared abbreviations = opt->getAbbreviations(); if (not abbreviations) { std::ostringstream msg; msg << "Dimension abbreviations not found."; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } auto q = querydata->get(opt->getProducer()); if (not q) { std::ostringstream msg; msg << "Data not found: '" << opt->getProducer() + "'."; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } if (not q->firstLevel()) { std::ostringstream msg; msg << "Level data not found: '" << opt->getProducer() + "'."; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } if (not q->firstTime()) { std::ostringstream msg; msg << "Time dimension not found: '" << opt->getProducer() + "'."; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } if (not q->isGrid()) throw WcsException(WcsException::NO_APPLICABLE_CODE, "Missing Grid."); boost::optional<Spine::Parameter> parameter = Spine::ParameterFactory::instance().parse(opt->getParameterName()); if (not parameter) { std::ostringstream msg; msg << "ParameterFactory can not parse '" << opt->getParameterName() << "' parameter of '" << opt->getProducer() << "' producer."; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } if (not q->param(parameter->number())) { std::ostringstream msg; msg << "Producer '" << opt->getProducer() << "' data not found for '" << opt->getParameterName() << "' parameter\n"; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } auto rangeZ = solveRangeZ(q); q->firstLevel(); std::vector<unsigned long> levelIds; boost::optional<DimensionTrim> trim; boost::optional<DimensionSlice> slice; auto axisLabel = abbreviations->getAbbreviation(2); if (slice = opt->getDimensionSlice(axisLabel)) { const double sPoint = slice->get("SlicePoint").get_double(); if (sPoint < rangeZ.first or sPoint > rangeZ.second) { std::ostringstream msg; msg << "SlicePoint '" << sPoint << "' is out of z range [" << rangeZ.first << "," << rangeZ.second << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionSlice"); throw wcsException; } const auto nearestLevel = solveNearestLevel(q, sPoint); levelIds.push_back(nearestLevel.first); } else if (trim = opt->getDimensionTrim(axisLabel)) { const auto low = trim->get("TrimLow").get_double(); const auto high = trim->get("TrimHigh").get_double(); if (high < rangeZ.first or low > rangeZ.second) { std::ostringstream msg; msg << "DimensionTrim range '[" << low << "," << high << "]' is out of z range [" << rangeZ.first << "," << rangeZ.second << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionTrim"); throw wcsException; } auto nearestLow = solveNearestLevel(q, low); auto nearesthigh = solveNearestLevel(q, high); for (auto id = nearestLow.first; id <= nearesthigh.first; ++id) levelIds.push_back(id); } else { levelIds.push_back(q->levelIndex()); } float missingValue = kFloatMissing; const unsigned long NX = q->grid().XNumber(); const unsigned long NY = q->grid().YNumber(); unsigned long minXId = 0; unsigned long minYId = 0; unsigned long maxXId = NX - 1; unsigned long maxYId = NY - 1; unsigned long xDelta = NX; unsigned long yDelta = NY; unsigned long zDelta = levelIds.size(); const auto& qWgs84Envelope = q->getWGS84Envelope(); const auto& rangeLon = qWgs84Envelope.getRangeLon(); bool swapCoord = opt->getSwap(); axisLabel = (swapCoord ? abbreviations->getAbbreviation(1) : abbreviations->getAbbreviation(0)); if (slice = opt->getDimensionSlice(axisLabel)) { const auto step = (rangeLon.getMax() - rangeLon.getMin()) / maxXId; const Engine::Querydata::Range range(rangeLon.getMin() - step, rangeLon.getMax() + step); const auto sPoint = slice->get("SlicePoint").get_double(); if (sPoint < range.getMin() or sPoint > range.getMax()) { std::ostringstream msg; msg << "SlicePoint '" << sPoint << "' is out of x range [" << range.getMin() << "," << range.getMax() << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionSlice"); throw wcsException; } auto nearestLoc = solveNearestX(q, sPoint); minXId = nearestLoc.first; maxXId = nearestLoc.first; xDelta = maxXId - minXId + 1; } else if (trim = opt->getDimensionTrim(axisLabel)) { double low = trim->get("TrimLow").get_double(); double high = trim->get("TrimHigh").get_double(); if (high < low) { double tmp = low; low = high; high = tmp; } if (high < rangeLon.getMin() or low > rangeLon.getMax()) { std::ostringstream msg; msg << "DimensionTrim range '[" << low << "," << high << "]' is out of x range [" << rangeLon.getMin() << "," << rangeLon.getMax() << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionTrim"); throw wcsException; } auto nearestLow = solveNearestX(q, low); auto nearestHigh = solveNearestX(q, high); minXId = nearestLow.first; maxXId = nearestHigh.first; xDelta = maxXId - minXId + 1; } const auto& rangeLat = qWgs84Envelope.getRangeLat(); axisLabel = (swapCoord ? abbreviations->getAbbreviation(0) : abbreviations->getAbbreviation(1)); if (slice = opt->getDimensionSlice(axisLabel)) { const auto step = (rangeLat.getMax() - rangeLat.getMin()) / maxYId; const Engine::Querydata::Range range(rangeLat.getMin() - step, rangeLat.getMax() + step); const auto sPoint = slice->get("SlicePoint").get_double(); if (sPoint < range.getMin() or sPoint > range.getMax()) { std::ostringstream msg; msg << "SlicePoint '" << sPoint << "' is out of y range [" << range.getMin() << "," << range.getMax() << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionSlice"); throw wcsException; } auto nearestLoc = solveNearestY(q, sPoint); minYId = nearestLoc.first; maxYId = nearestLoc.first; yDelta = maxYId - minYId + 1; } else if (trim = opt->getDimensionTrim(axisLabel)) { double low = trim->get("TrimLow").get_double(); double high = trim->get("TrimHigh").get_double(); if (high < low) { double tmp = low; low = high; high = tmp; } if (high < rangeLat.getMin() or low > rangeLat.getMax()) { std::ostringstream msg; msg << "DimensionTrim range '[" << low << "," << high << "]' is out of y range [" << rangeLat.getMin() << "," << rangeLat.getMax() << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionTrim"); throw wcsException; } auto nearestLow = solveNearestY(q, low); auto nearestHigh = solveNearestY(q, high); minYId = nearestLow.first; maxYId = nearestHigh.first; yDelta = maxYId - minYId + 1; } std::pair<boost::posix_time::ptime, boost::posix_time::ptime> rangeT = solveRangeT(q); std::vector<long> t; std::vector<unsigned long> timeIds; axisLabel = abbreviations->getAbbreviation(3); if (slice = opt->getDimensionSlice(axisLabel)) { const auto sPoint = slice->get("SlicePoint").get_ptime(); if (sPoint < rangeT.first or sPoint > rangeT.second) { std::ostringstream msg; msg << "SlicePoint '" << sPoint << "' is out of t range [" << rangeT.first << "," << rangeT.second << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionSlice"); throw wcsException; } // Return only the nearest time slice auto nearestTime = solveNearestTime(q, sPoint); q->firstLevel(); q->resetTime(); if (not q->timeIndex(nearestTime.first)) throw WcsException(WcsException::NO_APPLICABLE_CODE, "Cannot set a time dimension slice"); timeIds.push_back(nearestTime.first); t.push_back(q->validTime().DifferenceInMinutes(q->originTime())); } else if (trim = opt->getDimensionTrim(axisLabel)) { auto low = trim->get("TrimLow").get_ptime(); auto high = trim->get("TrimHigh").get_ptime(); if (high < rangeT.first or low > rangeT.second) { std::ostringstream msg; msg << "DimensionTrim range '[" << low << "," << high << "]' is out of t range [" << rangeT.first << "," << rangeT.second << "]"; WcsException wcsException(WcsException::INVALID_PARAMETER_VALUE, msg.str()); wcsException.setLocation("DimensionTrim"); throw wcsException; } auto nearestLow = solveNearestTime(q, low); auto nearestHigh = solveNearestTime(q, high); q->firstLevel(); q->resetTime(); for (unsigned long id = nearestLow.first; id <= nearestHigh.first; id++) { if (not q->timeIndex(id)) throw WcsException(WcsException::NO_APPLICABLE_CODE, "Cannot set a time dimension: trim"); timeIds.push_back(q->timeIndex()); t.push_back(q->validTime().DifferenceInMinutes(q->originTime())); } } else { // Return all the time steps q->firstLevel(); q->resetTime(); while (q->nextTime()) { timeIds.push_back(q->timeIndex()); t.push_back(q->validTime().DifferenceInMinutes(q->originTime())); } } if (getDebugLevel() > 2) { std::cout << "DataTime: " << q->validTime() << "\nOriginTime: " << q->originTime() << "\nProducer: " << opt->getProducer() << "\nParameterId: " << q->parameterName() << "\nParameterName: " << parameter->name() << "\nLevelName: " << q->levelName() << "\nLevelValue: " << q->levelValue() << "\nGridSizeX: " << q->grid().XNumber() << "\nGridSizeY: " << q->grid().YNumber() << "\n"; } unsigned long tDelta = t.size(); DataContainer<float> xc(xDelta * yDelta, "X coordinates"); DataContainer<float> yc(xDelta * yDelta, "Y coordinates"); DataContainer<float> zc(zDelta, "Z coordinates"); DataContainer<float> dataOut(xDelta * yDelta * zDelta * tDelta, "Data values"); auto transformation = opt->getTransformation(); // XY coordinates auto llCache = q->latLonCache(); auto it = llCache->cbegin(); auto itEnd = it; for (unsigned long yId = minYId; yId <= maxYId; yId++) { it = llCache->cbegin() + yId * NX + minXId; itEnd = it + xDelta; while (it < itEnd) { NFmiPoint tP = swap(transformation->transform(swap(*it++, true)), swapCoord); xc.add(tP.X()); yc.add(tP.Y()); } } for (const auto& lId : levelIds) { if (not q->levelIndex(lId)) throw std::runtime_error("Cannot set a data level to get "); zc.add(q->levelValue()); } NFmiDataMatrix<float> dem; NFmiDataMatrix<bool> flags; q->resetLevel(); ParamConfig::ParamIdType parameterId = parameter->number(); std::shared_ptr<ParamConfig::ParamMetaItemType> paramMetaItem; auto paramConfig = getParamConfig(); if (paramConfig) paramMetaItem = paramConfig->getParamMetaItem(parameterId); if (not paramMetaItem) { std::ostringstream msg; msg << "Parameter '" << parameterId << "' meta data configuration is missing"; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } for (const auto& tId : timeIds) { if (not q->timeIndex(tId)) { std::ostringstream msg; msg << "Error occured while setting time index: " << tId; throw std::runtime_error(msg.str()); } for (const auto& lId : levelIds) { q->levelIndex(lId); NFmiDataMatrix<float> dataMatrix; q->croppedValues(dataMatrix, minXId, minYId, maxXId, maxYId, dem, flags); if (dataMatrix.NX() != xDelta or dataMatrix.NY() != yDelta) throw WcsException(WcsException::NO_APPLICABLE_CODE, "Data size error."); for (unsigned long yId = 0; yId < yDelta; yId++) { for (unsigned xId = 0; xId < xDelta; xId++) { float val = dataMatrix.At(xId, yId, missingValue); if (val == missingValue) dataOut.add(val); else dataOut.add(paramMetaItem->mConversionScale * val + paramMetaItem->mConversionBase); } } } } UniqueTemporaryPath::Unique name1(new UniqueTemporaryPath()); NcFile dataFile(name1->get().c_str(), NcFile::FileMode::Replace, nullptr, 0, NcFile::Netcdf4Classic); if (not dataFile.is_valid()) { std::ostringstream msg; msg << "Cannot create or open temporary path passed to NcFile object: '" << name1->get().c_str() << "'."; throw WcsException(WcsException::NO_APPLICABLE_CODE, msg.str()); } dataFile.add_att("Conventions", "CF-1.6"); dataFile.add_att( "title", std::string("Dataset from ").append(opt->getProducer()).append(" producer").c_str()); dataFile.add_att("institution", "fmi.fi"); dataFile.add_att("source", "<undefined>"); dataFile.add_att("references", "<undefined>"); dataFile.add_att("comment", "<undefined>"); const NcType ncType = ncFloat; NcVar* var = nullptr; const std::string grid_mapping_name = "latitude_longitude"; if (grid_mapping_name == "latitude_longitude") { var = dataFile.add_var("grid_mapping", ncShort); var->add_att("grid_mapping_name", "latitude_longitude"); } else if (grid_mapping_name == "rotated_latitude_longitude") { var = dataFile.add_var("grid_mapping", ncChar); var->add_att("grid_mapping_name", "rotated_latitude_longitude"); var->add_att("grid_north_pole_latitude", 30.0); var->add_att("grid_north_pole_longitude", 0.0); } else { throw std::runtime_error("NetCDF grid_mapping is not configured"); } const NcDim* timeDim = dataFile.add_dim("time", tDelta); var = dataFile.add_var("time", ncInt, timeDim); var->add_att("long_name", "time"); var->add_att("calendar", "gregorian"); var->add_att("units", std::string("minutes since ") .append(Fmi::to_iso_string(q->originTime().PosixTime())) .append("Z") .c_str()); var->put(t.data(), tDelta); const NcDim* levelDim = dataFile.add_dim("level", zDelta); var = dataFile.add_var("level", ncType, levelDim); var->add_att("standard_name", "level"); var->add_att("units", "m"); var->add_att("axis", "Z"); var->add_att("long_name", "height"); var->add_att("positive", "up"); var->put(zc.array().get(), zDelta); const NcDim* ycDim = dataFile.add_dim("yc", yDelta); const NcDim* xcDim = dataFile.add_dim("xc", xDelta); var = dataFile.add_var("lat", ncType, ycDim, xcDim); var->add_att("standard_name", "latitude"); var->add_att("units", "degrees_north"); var->add_att("axis", "Y"); var->add_att("long_name", "latitude"); var->put(yc.array().get(), yDelta, xDelta); var = dataFile.add_var("lon", ncType, ycDim, xcDim); var->add_att("standard_name", "longitude"); var->add_att("units", "degrees_east"); var->add_att("axis", "X"); var->add_att("long_name", "longitude"); var->put(xc.array().get(), yDelta, xDelta); std::string varName = Fmi::ascii_tolower_copy(parameter->name()); varName.append("_").append(Fmi::to_string(parameterId)); var = dataFile.add_var(varName.c_str(), ncType, timeDim, levelDim, ycDim, xcDim); var->add_att("_FillValue", missingValue); var->add_att("missing_value", missingValue); var->add_att("grid_mapping", "grid_mapping"); var->add_att("coordinates", "lon lat"); if (paramMetaItem->mStdName) var->add_att("standard_name", paramMetaItem->mStdName.get().c_str()); if (paramMetaItem->mUnit) var->add_att("units", paramMetaItem->mUnit.get().c_str()); if (paramMetaItem->mLongName) var->add_att("long_name", paramMetaItem->mLongName.get().c_str()); var->put(dataOut.array().get(), tDelta, zDelta, yDelta, xDelta); dataFile.close(); std::ifstream ifs; ifs.open(name1->get().c_str(), std::ifstream::in); if (ifs.is_open()) { output << ifs.rdbuf(); ifs.close(); } else output << ""; } } // namespace WCS } // namespace Plugin } // namespace SmartMet
34.188976
103
0.641409
fmidev
d3e3a51f7a5bf21d4eef98b144015d838e79e4e0
13,894
cc
C++
android/art/compiler/common_compiler_test.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
206
2020-04-13T03:19:33.000Z
2022-03-27T13:52:25.000Z
android/art/compiler/common_compiler_test.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
9
2020-06-07T12:51:09.000Z
2022-03-28T23:55:09.000Z
android/art/compiler/common_compiler_test.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
42
2020-04-13T03:37:58.000Z
2022-03-23T15:08:12.000Z
/* * Copyright (C) 2011 The Android Open Source Project * * 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 "common_compiler_test.h" #include "arch/instruction_set_features.h" #include "art_field-inl.h" #include "art_method-inl.h" #include "base/callee_save_type.h" #include "base/enums.h" #include "base/utils.h" #include "class_linker.h" #include "compiled_method-inl.h" #include "dex/descriptors_names.h" #include "dex/quick_compiler_callbacks.h" #include "dex/verification_results.h" #include "driver/compiler_driver.h" #include "driver/compiler_options.h" #include "interpreter/interpreter.h" #include "mirror/class-inl.h" #include "mirror/class_loader.h" #include "mirror/dex_cache.h" #include "mirror/object-inl.h" #include "oat_quick_method_header.h" #include "scoped_thread_state_change-inl.h" #include "thread-current-inl.h" namespace art { CommonCompilerTest::CommonCompilerTest() {} CommonCompilerTest::~CommonCompilerTest() {} void CommonCompilerTest::MakeExecutable(ArtMethod* method) { CHECK(method != nullptr); const CompiledMethod* compiled_method = nullptr; if (!method->IsAbstract()) { mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache(); const DexFile& dex_file = *dex_cache->GetDexFile(); compiled_method = compiler_driver_->GetCompiledMethod(MethodReference(&dex_file, method->GetDexMethodIndex())); } // If the code size is 0 it means the method was skipped due to profile guided compilation. if (compiled_method != nullptr && compiled_method->GetQuickCode().size() != 0u) { ArrayRef<const uint8_t> code = compiled_method->GetQuickCode(); const uint32_t code_size = code.size(); ArrayRef<const uint8_t> vmap_table = compiled_method->GetVmapTable(); const uint32_t vmap_table_offset = vmap_table.empty() ? 0u : sizeof(OatQuickMethodHeader) + vmap_table.size(); // The method info is directly before the vmap table. ArrayRef<const uint8_t> method_info = compiled_method->GetMethodInfo(); const uint32_t method_info_offset = method_info.empty() ? 0u : vmap_table_offset + method_info.size(); OatQuickMethodHeader method_header(vmap_table_offset, method_info_offset, compiled_method->GetFrameSizeInBytes(), compiled_method->GetCoreSpillMask(), compiled_method->GetFpSpillMask(), code_size); header_code_and_maps_chunks_.push_back(std::vector<uint8_t>()); std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back(); const size_t max_padding = GetInstructionSetAlignment(compiled_method->GetInstructionSet()); const size_t size = method_info.size() + vmap_table.size() + sizeof(method_header) + code_size; chunk->reserve(size + max_padding); chunk->resize(sizeof(method_header)); memcpy(&(*chunk)[0], &method_header, sizeof(method_header)); chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end()); chunk->insert(chunk->begin(), method_info.begin(), method_info.end()); chunk->insert(chunk->end(), code.begin(), code.end()); CHECK_EQ(chunk->size(), size); const void* unaligned_code_ptr = chunk->data() + (size - code_size); size_t offset = dchecked_integral_cast<size_t>(reinterpret_cast<uintptr_t>(unaligned_code_ptr)); size_t padding = compiled_method->AlignCode(offset) - offset; // Make sure no resizing takes place. CHECK_GE(chunk->capacity(), chunk->size() + padding); chunk->insert(chunk->begin(), padding, 0); const void* code_ptr = reinterpret_cast<const uint8_t*>(unaligned_code_ptr) + padding; CHECK_EQ(code_ptr, static_cast<const void*>(chunk->data() + (chunk->size() - code_size))); MakeExecutable(code_ptr, code.size()); const void* method_code = CompiledMethod::CodePointer(code_ptr, compiled_method->GetInstructionSet()); LOG(INFO) << "MakeExecutable " << method->PrettyMethod() << " code=" << method_code; method->SetEntryPointFromQuickCompiledCode(method_code); } else { // No code? You must mean to go into the interpreter. // Or the generic JNI... class_linker_->SetEntryPointsToInterpreter(method); } } void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) { CHECK(code_start != nullptr); CHECK_NE(code_length, 0U); uintptr_t data = reinterpret_cast<uintptr_t>(code_start); uintptr_t base = RoundDown(data, kPageSize); uintptr_t limit = RoundUp(data + code_length, kPageSize); uintptr_t len = limit - base; int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC); CHECK_EQ(result, 0); FlushInstructionCache(reinterpret_cast<char*>(base), reinterpret_cast<char*>(base + len)); } void CommonCompilerTest::MakeExecutable(ObjPtr<mirror::ClassLoader> class_loader, const char* class_name) { std::string class_descriptor(DotToDescriptor(class_name)); Thread* self = Thread::Current(); StackHandleScope<1> hs(self); Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader)); mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader); CHECK(klass != nullptr) << "Class not found " << class_name; PointerSize pointer_size = class_linker_->GetImagePointerSize(); for (auto& m : klass->GetMethods(pointer_size)) { MakeExecutable(&m); } } // Get the set of image classes given to the compiler-driver in SetUp. Note: the compiler // driver assumes ownership of the set, so the test should properly release the set. std::unordered_set<std::string>* CommonCompilerTest::GetImageClasses() { // Empty set: by default no classes are retained in the image. return new std::unordered_set<std::string>(); } // Get the set of compiled classes given to the compiler-driver in SetUp. Note: the compiler // driver assumes ownership of the set, so the test should properly release the set. std::unordered_set<std::string>* CommonCompilerTest::GetCompiledClasses() { // Null, no selection of compiled-classes. return nullptr; } // Get the set of compiled methods given to the compiler-driver in SetUp. Note: the compiler // driver assumes ownership of the set, so the test should properly release the set. std::unordered_set<std::string>* CommonCompilerTest::GetCompiledMethods() { // Null, no selection of compiled-methods. return nullptr; } // Get ProfileCompilationInfo that should be passed to the driver. ProfileCompilationInfo* CommonCompilerTest::GetProfileCompilationInfo() { // Null, profile information will not be taken into account. return nullptr; } void CommonCompilerTest::SetUp() { CommonRuntimeTest::SetUp(); { ScopedObjectAccess soa(Thread::Current()); const InstructionSet instruction_set = kRuntimeISA; // Take the default set of instruction features from the build. instruction_set_features_ = InstructionSetFeatures::FromCppDefines(); runtime_->SetInstructionSet(instruction_set); for (uint32_t i = 0; i < static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType); ++i) { CalleeSaveType type = CalleeSaveType(i); if (!runtime_->HasCalleeSaveMethod(type)) { runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type); } } CreateCompilerDriver(compiler_kind_, instruction_set); } } void CommonCompilerTest::CreateCompilerDriver(Compiler::Kind kind, InstructionSet isa, size_t number_of_threads) { compiler_options_->boot_image_ = true; compiler_options_->SetCompilerFilter(GetCompilerFilter()); compiler_driver_.reset(new CompilerDriver(compiler_options_.get(), verification_results_.get(), kind, isa, instruction_set_features_.get(), GetImageClasses(), GetCompiledClasses(), GetCompiledMethods(), number_of_threads, /* swap_fd */ -1, GetProfileCompilationInfo())); // We typically don't generate an image in unit tests, disable this optimization by default. compiler_driver_->SetSupportBootImageFixup(false); } void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) { CommonRuntimeTest::SetUpRuntimeOptions(options); compiler_options_.reset(new CompilerOptions); verification_results_.reset(new VerificationResults(compiler_options_.get())); QuickCompilerCallbacks* callbacks = new QuickCompilerCallbacks(CompilerCallbacks::CallbackMode::kCompileApp); callbacks->SetVerificationResults(verification_results_.get()); callbacks_.reset(callbacks); } Compiler::Kind CommonCompilerTest::GetCompilerKind() const { return compiler_kind_; } void CommonCompilerTest::SetCompilerKind(Compiler::Kind compiler_kind) { compiler_kind_ = compiler_kind; } InstructionSet CommonCompilerTest::GetInstructionSet() const { DCHECK(compiler_driver_.get() != nullptr); return compiler_driver_->GetInstructionSet(); } void CommonCompilerTest::TearDown() { compiler_driver_.reset(); callbacks_.reset(); verification_results_.reset(); compiler_options_.reset(); image_reservation_.reset(); CommonRuntimeTest::TearDown(); } void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) { std::string class_descriptor(DotToDescriptor(class_name)); Thread* self = Thread::Current(); StackHandleScope<1> hs(self); Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader)); mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader); CHECK(klass != nullptr) << "Class not found " << class_name; auto pointer_size = class_linker_->GetImagePointerSize(); for (auto& m : klass->GetMethods(pointer_size)) { CompileMethod(&m); } } void CommonCompilerTest::CompileMethod(ArtMethod* method) { CHECK(method != nullptr); TimingLogger timings("CommonTest::CompileMethod", false, false); TimingLogger::ScopedTiming t(__FUNCTION__, &timings); compiler_driver_->CompileOne(Thread::Current(), method, &timings); TimingLogger::ScopedTiming t2("MakeExecutable", &timings); MakeExecutable(method); } void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader, const char* class_name, const char* method_name, const char* signature) { std::string class_descriptor(DotToDescriptor(class_name)); Thread* self = Thread::Current(); mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader); CHECK(klass != nullptr) << "Class not found " << class_name; auto pointer_size = class_linker_->GetImagePointerSize(); ArtMethod* method = klass->FindClassMethod(method_name, signature, pointer_size); CHECK(method != nullptr && method->IsDirect()) << "Direct method not found: " << class_name << "." << method_name << signature; CompileMethod(method); } void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader, const char* class_name, const char* method_name, const char* signature) { std::string class_descriptor(DotToDescriptor(class_name)); Thread* self = Thread::Current(); mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader); CHECK(klass != nullptr) << "Class not found " << class_name; auto pointer_size = class_linker_->GetImagePointerSize(); ArtMethod* method = klass->FindClassMethod(method_name, signature, pointer_size); CHECK(method != nullptr && !method->IsDirect()) << "Virtual method not found: " << class_name << "." << method_name << signature; CompileMethod(method); } void CommonCompilerTest::ReserveImageSpace() { // Reserve where the image will be loaded up front so that other parts of test set up don't // accidentally end up colliding with the fixed memory address when we need to load the image. std::string error_msg; MemMap::Init(); image_reservation_.reset(MemMap::MapAnonymous("image reservation", reinterpret_cast<uint8_t*>(ART_BASE_ADDRESS), (size_t)120 * 1024 * 1024, // 120MB PROT_NONE, false /* no need for 4gb flag with fixed mmap*/, false /* not reusing existing reservation */, &error_msg)); CHECK(image_reservation_.get() != nullptr) << error_msg; } void CommonCompilerTest::UnreserveImageSpace() { image_reservation_.reset(); } } // namespace art
45.405229
100
0.677343
Solotov
d3e5ef0c6abd060d037184253795954185c0f745
269
cpp
C++
src/foreachprint.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
src/foreachprint.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
src/foreachprint.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <iostream> void print(int x) { std::cout << "print: "<< x << '\n'; } void printReverse(std::vector<int> v) { std::for_each(crbegin(v), crend(v), print); } int main(){ std::vector v{1,2,3,4,5}; printReverse(v); }
17.933333
45
0.613383
PeterSommerlad
d3e78bf353de3c32d39691300a33f6f236bb39ea
4,738
hpp
C++
include/freertos_cpp_util/object_pool/Object_pool.hpp
jacobschloss/freertos_cpp_util
8251809738922c84b1ce12db6a77000b73287a8b
[ "BSD-3-Clause" ]
5
2019-03-28T22:05:50.000Z
2022-03-29T16:20:01.000Z
include/freertos_cpp_util/object_pool/Object_pool.hpp
jacobschloss/freertos_cpp_util
8251809738922c84b1ce12db6a77000b73287a8b
[ "BSD-3-Clause" ]
null
null
null
include/freertos_cpp_util/object_pool/Object_pool.hpp
jacobschloss/freertos_cpp_util
8251809738922c84b1ce12db6a77000b73287a8b
[ "BSD-3-Clause" ]
1
2020-06-17T04:04:26.000Z
2020-06-17T04:04:26.000Z
/** * @brief Object_pool * @author Jacob Schloss <jacob@schloss.io> * @copyright Copyright (c) 2018 Jacob Schloss. All rights reserved. * @license Licensed under the 3-Clause BSD license. See LICENSE for details */ #pragma once #include "freertos_cpp_util/Queue_static_pod.hpp" #include "freertos_cpp_util/object_pool/Object_pool_node.hpp" #include "freertos_cpp_util/object_pool/Object_pool_base.hpp" #include <chrono> #include <type_traits> #include <utility> template< typename T, size_t LEN > class Object_pool : public Object_pool_base<T> { public: using typename Object_pool_base<T>::Aligned_T; using typename Object_pool_base<T>::Node_T; using typename Object_pool_base<T>::Heap_element_T; Object_pool() { for(size_t i = 0; i < LEN; i++) { Heap_element_T* const mem_ptr = &m_mem_node_pool[i]; mem_ptr->node = Node_T(this, reinterpret_cast<T*>( &(mem_ptr->val)) ); m_free_nodes.push_back(&mem_ptr->node); } } template<class Rep, class Period, typename... Args> T* try_allocate_for(const std::chrono::duration<Rep,Period>& duration, Args&&... args) { std::chrono::milliseconds duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration); return try_allocate_for_ticks(pdMS_TO_TICKS(duration_ms.count()), std::forward<Args>(args)...); } template<typename... Args> T* try_allocate_for_ticks(const TickType_t xTicksToWait, Args&&... args) { Node_T* node = nullptr; if(!m_free_nodes.pop_front(&node, xTicksToWait)) { return nullptr; } return node->allocate(std::forward<Args>(args)...); } template<typename... Args> T* try_allocate_isr(BaseType_t* const pxHigherPriorityTaskWoken, Args&&... args) { Node_T* node = nullptr; if(!m_free_nodes.pop_front_isr(&node, pxHigherPriorityTaskWoken)) { return nullptr; } return node->allocate(std::forward<Args>(args)...); } template<typename... Args> T* allocate(Args&&... args) { return try_allocate_for_ticks(0, std::forward<Args>(args)...); } class Node_T_deleter { public: void operator()(T* ptr) const { Node_T* node = Node_T::get_this_from_val_ptr(ptr); Object_pool_base<T>* pool = node->get_pool_ptr(); pool->deallocate(node); } }; typedef std::unique_ptr<T, Node_T_deleter> unique_node_ptr; class Node_T_deleter_isr { public: void operator()(T* ptr) const { Node_T* node = Node_T::get_this_from_val_ptr(ptr); Object_pool_base<T>* pool = node->get_pool_ptr(); pool->deallocate_isr(node); } }; typedef std::unique_ptr<T, Node_T_deleter_isr> isr_unique_node_ptr; template<typename... Args> unique_node_ptr try_allocate_for_ticks_unique(const TickType_t xTicksToWait, Args&&... args) { T* val = try_allocate_for_ticks(xTicksToWait, std::forward<Args>(args)...); return unique_node_ptr(val); } template<typename... Args> unique_node_ptr allocate_unique(Args&&... args) { T* val = allocate(std::forward<Args>(args)...); return unique_node_ptr(val); } template<typename... Args> isr_unique_node_ptr allocate_unique_isr(BaseType_t* const pxHigherPriorityTaskWoken, Args&&... args) { T* val = try_allocate_isr(pxHigherPriorityTaskWoken, std::forward<Args>(args)...); return isr_unique_node_ptr(val); } //the "best" deallocator //node must belong to this pool void deallocate(Node_T* const node) override { if(node == nullptr) { return; } node->deallocate(); // Object_pool_base<T>* pool = node->get_pool(); // if(pool != this) // { // //you tried to delete a foreign node // //that is bad // } if(!m_free_nodes.push_front(node)) { //this should never fail //very bad if this fails } } //look up the node based on the ptr //ptr must belong to this pool void deallocate(T* const ptr) override { if(ptr == nullptr) { return; } Node_T* node = Node_T::get_this_from_val_ptr(ptr); deallocate(node); } //the "best" deallocator //node must belong to this pool void deallocate_isr(Node_T* const node) override { if(node == nullptr) { return; } node->deallocate(); // Object_pool_base<T>* pool = node->get_pool(); // if(pool != this) // { // //you tried to delete a foreign node // //that is bad // } if(!m_free_nodes.push_front_isr(node)) { //this should never fail //very bad if this fails } } //look up the node based on the ptr //ptr must belong to this pool void deallocate_isr(T* const ptr) override { if(ptr == nullptr) { return; } Node_T* node = Node_T::get_this_from_val_ptr(ptr); deallocate_isr(node); } protected: //heap element: node and aligned storage std::array<Heap_element_T, LEN> m_mem_node_pool; //tracks free nodes Queue_static_pod<Node_T*, LEN> m_free_nodes; };
22.140187
106
0.695019
jacobschloss
d3e93b4a64afe604470a51fc7b70e85ea86ba495
1,670
hpp
C++
Source/Cerise/CR_Text.hpp
BubbleChien/Path
950f65b9fcd99bebf4cb5b20fecd3df085161912
[ "MIT" ]
1
2018-07-07T15:14:33.000Z
2018-07-07T15:14:33.000Z
Source/Cerise/CR_Text.hpp
BubbleChien/Path
950f65b9fcd99bebf4cb5b20fecd3df085161912
[ "MIT" ]
null
null
null
Source/Cerise/CR_Text.hpp
BubbleChien/Path
950f65b9fcd99bebf4cb5b20fecd3df085161912
[ "MIT" ]
null
null
null
#ifndef CR_TEXT_HPP #define CR_TEXT_HPP #include "./CR_Common.hpp" #include "./CR_Error.hpp" #include "./CR_Math.hpp" #include "./CR_Vector.hpp" namespace CR { class Text { CR_PRIVATE C2D_TextBuf m_buffer = nullptr; C2D_Text m_text; Vector m_pos; uint32_t m_color = 0xFFFFFFFF; float m_size = 1.0f; CR_PUBLIC void Init(uint32_t size); void Free(); void CenterAt(float x, float y); CR_PUBLIC inline ~Text(); inline void Clear(); inline void Append(const char* str); inline void SetPosition(float x, float y); inline void Move(float x, float y); inline void SetColor(uint32_t color); inline void SetSize(float s); inline void Render(); }; Text::~Text() { this->Free(); } void Text::Clear() { #if CR_DEV_BUILD if(m_buffer == nullptr) { Error::Show("Text has not been initialized."); return; } #endif C2D_TextBufClear(m_buffer); } void Text::Append(const char* str) { #if CR_DEV_BUILD if(m_buffer == nullptr) { Error::Show("Text has not been initialized."); return; } #endif C2D_TextParse(&m_text, m_buffer, str); } void Text::SetPosition(float x, float y) { m_pos.Set(Math::Pixel(x), Math::Pixel(y)); } void Text::Move(float x, float y) { m_pos.Move(x, y); } void Text::SetColor(uint32_t color) { m_color = color; } void Text::SetSize(float s) { m_size = s; } void Text::Render() { #if CR_DEV_BUILD if(m_buffer == nullptr) { Error::Show("Text has not been initialized."); return; } #endif C2D_DrawText(&m_text, CR_TEXT_FLAGS, m_pos.x, m_pos.y, 0.5f, m_size, m_size, m_color); } } #endif
11.678322
88
0.636527
BubbleChien
d3f6b620fb3cb66b4be843d879506f938c5cf2f0
16,727
cpp
C++
src/PropBindingDialog.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/PropBindingDialog.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/PropBindingDialog.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
#include "PropBindingDialog.h" #include <wx/dataview.h> #include <wx/statline.h> /////////////////////////////////////////////////////////////////////////// enum { ID_BIND = 100, ID_UNBIND }; BEGIN_EVENT_TABLE(PropBindingDialog, wxDialog) EVT_BUTTON(ID_BIND, PropBindingDialog::OnBindButton) EVT_BUTTON(ID_UNBIND, PropBindingDialog::OnUnbindButton) END_EVENT_TABLE() PropBindingSubscriberModelNode::PropBindingSubscriberModelNode ( PropBindingSubscriberModelNode* parent, const wxString &subscriber_name, Property * subscriber_prop, const wxString &binding, Property * observed_prop, bool is_container ) : m_parent ( parent ), m_subscriber_name ( subscriber_name ), m_subscriber ( subscriber_prop ), m_binding ( binding ), m_observed ( observed_prop ), m_container ( is_container ) { } PropBindingSubscriberModelNode::~PropBindingSubscriberModelNode ( ) { // free all our children nodes size_t count = m_children.GetCount(); for (size_t i = 0; i < count; i++) { PropBindingSubscriberModelNode *child = m_children[i]; delete child; } } void PropBindingSubscriberModelNode::UpdateNode ( ) { m_subscriber_name = m_subscriber->GetName ( ); Binding * binding = m_subscriber->GetBinding ( ); if ( binding ) { m_binding = binding->GetPropertyTypeName ( ); m_observed = binding->GetOtherProperty ( m_subscriber ); } else { m_binding = wxEmptyString; m_observed = NULL; } m_container = m_subscriber->IsContainer ( ); } PropBindingSubscriberModel::PropBindingSubscriberModel ( HeeksObj *obj ) { wxString str = obj->GetTitle ( ); if ( str.IsEmpty ( ) ) { str = obj->GetTypeString ( ); } m_root = new PropBindingSubscriberModelNode ( NULL, str, NULL, wxEmptyString, NULL, true ); for ( DomainObjectIterator it = obj->begin ( ); it != obj->end ( ); it++ ) { Property * prop = *it; if ( prop->IsBindable ( ) ) { PropBindingSubscriberModelNode* node; Binding * binding = prop->GetBinding ( ); if ( binding ) { wxString binding_type = binding->GetPropertyTypeName ( ); Property * observed = binding->GetOtherProperty ( prop ); node = new PropBindingSubscriberModelNode ( m_root, prop->GetName ( ), prop, binding_type, observed, prop->IsContainer ( ) ); } else { node = new PropBindingSubscriberModelNode ( m_root, prop->GetName ( ), prop, wxEmptyString, NULL, prop->IsContainer ( ) ); } m_root->Append ( node ); } } } PropBindingSubscriberModel::~PropBindingSubscriberModel ( ) { delete m_root; } void PropBindingSubscriberModel::GetValue ( wxVariant &variant, const wxDataViewItem &item, unsigned int col ) const { wxASSERT(item.IsOk()); PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) item.GetID(); switch (col) { case 0: variant = node->m_subscriber_name; break; case 1: if ( node->m_subscriber ) variant = node->m_subscriber->GetPropertyTypeName(); else variant = wxEmptyString; break; case 2: variant = node->m_binding; break; case 3: if ( node->m_observed ) { HeeksObj * obj = (HeeksObj*)node->m_observed->GetOwner(); wxString str = obj->GetTitle ( ); if ( str.IsEmpty ( ) ) { str = obj->GetTypeString ( ); } variant = str; } else variant = wxEmptyString; break; case 4: if ( node->m_observed ) variant = node->m_observed->GetName(); else variant = wxEmptyString; break; default: wxLogError ( "PropBindingSubscriberModel::GetValue: wrong column %d", col ); } } bool PropBindingSubscriberModel::SetValue ( const wxVariant &variant, const wxDataViewItem &item, unsigned int col ) { return false; } bool PropBindingSubscriberModel::IsEnabled ( const wxDataViewItem &item, unsigned int col ) const { return true; } wxDataViewItem PropBindingSubscriberModel::GetParent ( const wxDataViewItem &item ) const { // the invisible root node has no parent if (!item.IsOk()) return wxDataViewItem(0); PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) item.GetID(); if (node == m_root) return wxDataViewItem(0); return wxDataViewItem ( (void*) node->GetParent() ); } bool PropBindingSubscriberModel::IsContainer ( const wxDataViewItem &item ) const { if (!item.IsOk()) return true; PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) item.GetID(); return ( node->m_container ); } unsigned int PropBindingSubscriberModel::GetChildren ( const wxDataViewItem &parent, wxDataViewItemArray &array ) const { PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) parent.GetID(); if (!node) { array.Add( wxDataViewItem( (void*) m_root ) ); return 1; } unsigned int count = node->GetChildren().GetCount(); for (unsigned int pos = 0; pos < count; pos++) { PropBindingSubscriberModelNode *child = node->GetChildren().Item ( pos ); array.Add( wxDataViewItem( (void*) child ) ); } return count; } PropBindingObservedModelNode::PropBindingObservedModelNode ( PropBindingObservedModelNode* parent, const wxString &observed_name, Property * observed_prop, bool is_container ) : m_parent ( parent ), m_observed_name ( observed_name ), m_observed ( observed_prop ), m_container ( is_container ) { } PropBindingObservedModelNode::~PropBindingObservedModelNode ( ) { // free all our children nodes size_t count = m_children.GetCount(); for (size_t i = 0; i < count; i++) { PropBindingObservedModelNode *child = m_children[i]; delete child; } } PropBindingObservedModel::PropBindingObservedModel ( HeeksObj *obj ) { wxString str = obj->GetTitle ( ); if ( str.IsEmpty ( ) ) { str = obj->GetTypeString ( ); } m_root = new PropBindingObservedModelNode ( NULL, str, NULL, true ); for ( DomainObjectIterator it = obj->begin ( ); it != obj->end ( ); it++ ) { Property * prop = *it; if ( prop->IsBindable ( ) ) { m_root->Append ( new PropBindingObservedModelNode ( m_root, prop->GetName ( ), prop, prop->IsContainer ( ) ) ); } } } PropBindingObservedModel::~PropBindingObservedModel ( ) { delete m_root; } void PropBindingObservedModel::GetValue ( wxVariant &variant, const wxDataViewItem &item, unsigned int col ) const { wxASSERT(item.IsOk()); PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) item.GetID(); switch (col) { case 0: variant = node->m_observed_name; break; case 1: if ( node->m_observed ) variant = node->m_observed->GetPropertyTypeName(); else variant = wxEmptyString; break; default: wxLogError ( "PropBindingObservedModel::GetValue: wrong column %d", col ); } } bool PropBindingObservedModel::SetValue ( const wxVariant &variant, const wxDataViewItem &item, unsigned int col ) { return false; } bool PropBindingObservedModel::IsEnabled ( const wxDataViewItem &item, unsigned int col ) const { return true; } wxDataViewItem PropBindingObservedModel::GetParent ( const wxDataViewItem &item ) const { // the invisible root node has no parent if (!item.IsOk()) return wxDataViewItem(0); PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) item.GetID(); if (node == m_root) return wxDataViewItem(0); return wxDataViewItem ( (void*) node->GetParent() ); } bool PropBindingObservedModel::IsContainer ( const wxDataViewItem &item ) const { if (!item.IsOk()) return true; PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) item.GetID(); return ( node->m_container ); } unsigned int PropBindingObservedModel::GetChildren ( const wxDataViewItem &parent, wxDataViewItemArray &array ) const { PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) parent.GetID(); if (!node) { array.Add ( wxDataViewItem( (void*) m_root ) ); return 1; } unsigned int count = node->GetChildren().GetCount(); for (unsigned int pos = 0; pos < count; pos++) { PropBindingObservedModelNode *child = node->GetChildren().Item ( pos ); array.Add ( wxDataViewItem( (void*) child ) ); } return count; } PropBindingDialog::PropBindingDialog ( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog ( parent, id, title, pos, size, style), m_subscriber_model ( NULL ), m_observed_model ( NULL ) { this->SetSize ( wxSize ( 845, 480 ) ); // wxFlexGridSizer (int rows, int cols, int vgap, int hgap) wxFlexGridSizer* topSizer = new wxFlexGridSizer ( 4, 1, 0, 0 ); topSizer->AddGrowableCol ( 0 ); topSizer->AddGrowableRow ( 0 ); wxFlexGridSizer* gridSizer = new wxFlexGridSizer ( 1, 2, 0, 0 ); gridSizer->AddGrowableCol ( 0, 70 ); gridSizer->AddGrowableCol ( 1, 30 ); gridSizer->AddGrowableRow ( 0 ); prop1 = new wxDataViewCtrl ( this, wxID_ANY ); // Add (wxWindow *window, int proportion=0, int flag=0, int border=0, wxObject *userData=NULL) gridSizer->Add( prop1, 0, wxALL | wxEXPAND, 5 ); wxDataViewTextRenderer *text_renderer = new wxDataViewTextRenderer(); wxDataViewColumn* column; column = new wxDataViewColumn ( "subscriber", text_renderer, 0, 115, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "type", text_renderer, 1, 100, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "binding", text_renderer, 2, 95, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "observed", text_renderer, 3, 115, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "property", text_renderer, 4, 115, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); prop2 = new wxDataViewCtrl ( this, wxID_ANY ); gridSizer->Add ( prop2, 0, wxEXPAND | wxALL, 5 ); column = new wxDataViewColumn ( "observed", text_renderer, 0, 120, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop2->AppendColumn ( column ); column = new wxDataViewColumn ( "type", text_renderer, 1, 100, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop2->AppendColumn ( column ); topSizer->Add ( gridSizer, 1, wxEXPAND | wxALL, 5 ); wxStaticBoxSizer *actionSizer = new wxStaticBoxSizer ( wxHORIZONTAL, this ); m_buttonBind = new wxButton ( actionSizer->GetStaticBox(), ID_BIND, _("Bind") ); actionSizer->Add ( m_buttonBind, 0, wxALL, 5 ); m_buttonUnbind = new wxButton ( actionSizer->GetStaticBox(), ID_UNBIND, _("Unbind") ); actionSizer->Add ( m_buttonUnbind, 0, wxALL, 5 ); actionSizer->Insert ( 0, 260, 0 ); actionSizer->Insert ( 1, 50, 0 ); topSizer->Add ( actionSizer, 1, wxEXPAND | wxALL, 5 ); m_staticline1 = new wxStaticLine ( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); topSizer->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); m_buttonSizer = new wxStdDialogButtonSizer ( ); m_buttonOK = new wxButton ( this, wxID_OK ); m_buttonSizer->AddButton ( m_buttonOK ); m_buttonSizer->Realize ( ); m_buttonSizer->SetMinSize ( wxSize ( -1, 40 ) ); topSizer->Add ( m_buttonSizer, 1, wxEXPAND, 5 ); this->SetSizer ( topSizer ); this->Layout ( ); this->Centre( wxBOTH ); } PropBindingDialog::~PropBindingDialog() { if ( m_subscriber_model ) { m_subscriber_model->DecRef(); } if ( m_observed_model ) { m_observed_model->DecRef(); } } void PropBindingDialog::ExpandSubscriberRecursive ( PropBindingSubscriberModel* model, wxDataViewItem& item ) { prop1->Expand ( item ); wxDataViewItemArray children; int count = model->GetChildren ( item, children ); for ( int i = 0; i < count; i++ ) { wxDataViewItem child = children[i]; ExpandSubscriberRecursive ( model, child ); } } void PropBindingDialog::AddSubscriberModel ( PropBindingSubscriberModel* model ) { m_subscriber_model = model; prop1->AssociateModel ( model ); wxDataViewItem root ( NULL ); ExpandSubscriberRecursive ( model, root ); wxGetApp().RegisterObserver ( this ); } void PropBindingDialog::ExpandObservedRecursive ( PropBindingObservedModel* model, wxDataViewItem& item ) { prop2->Expand ( item ); wxDataViewItemArray children; int count = model->GetChildren ( item, children ); for ( int i = 0; i < count; i++ ) { wxDataViewItem child = children[i]; ExpandObservedRecursive ( model, child ); } } void PropBindingDialog::AddObservedModel ( PropBindingObservedModel* model ) { m_observed_model = model; prop2->AssociateModel ( model ); wxDataViewItem root ( NULL ); ExpandObservedRecursive ( model, root ); } void PropBindingDialog::OnBindButton ( wxCommandEvent& event ) { wxDataViewItem selected1 = prop1->GetSelection ( ); if ( !selected1.IsOk ( ) ) { return; } PropBindingSubscriberModelNode* subscriber = (PropBindingSubscriberModelNode*) selected1.GetID ( ); wxDataViewItem selected2 = prop2->GetSelection ( ); if ( !selected2.IsOk ( ) ) { return; } PropBindingObservedModelNode* observed = (PropBindingObservedModelNode*) selected2.GetID ( ); new EqualityBinding ( subscriber->m_subscriber, observed->m_observed ); // At this point, the subscriber may be a completely new object. subscriber->UpdateNode ( ); m_subscriber_model->ItemChanged ( selected1 ); } void PropBindingDialog::OnUnbindButton ( wxCommandEvent& event ) { wxDataViewItem selected1 = prop1->GetSelection ( ); if ( !selected1.IsOk ( ) ) { return; } PropBindingSubscriberModelNode* subscriber = (PropBindingSubscriberModelNode*) selected1.GetID ( ); wxDataViewItem selected2 = prop2->GetSelection ( ); if ( !selected2.IsOk ( ) ) { return; } PropBindingObservedModelNode* observed = (PropBindingObservedModelNode*) selected2.GetID ( ); Binding * binding = observed->m_observed->GetBinding ( ); delete binding; } void PropBindingDialog::WhenMarkedListChanges ( bool selection_cleared, const std::list<HeeksObj*>* added_list, const std::list<HeeksObj*>* removed_list ) { if ( !added_list || added_list->empty ( ) ) { return; } HeeksObj* observed = added_list->back ( ); PropBindingObservedModel* observed_model = new PropBindingObservedModel ( observed ); this->AddObservedModel ( observed_model ); }
33.521042
147
0.609972
tapeguy
108cb9c126208baa6d96f4f71d32fac108adc580
1,440
cpp
C++
CF-Upsolving v001/Solutions/red_maple/A/main.cpp
gmeligio/axon_training
657f181b732265856c71e97697bfde2062744e5a
[ "MIT" ]
null
null
null
CF-Upsolving v001/Solutions/red_maple/A/main.cpp
gmeligio/axon_training
657f181b732265856c71e97697bfde2062744e5a
[ "MIT" ]
5
2019-04-30T22:31:36.000Z
2019-05-07T00:15:23.000Z
CF-Upsolving v001/Solutions/red_maple/A/main.cpp
gmeligio/axon_training
657f181b732265856c71e97697bfde2062744e5a
[ "MIT" ]
5
2019-05-01T05:08:43.000Z
2019-05-07T18:13:18.000Z
/* Date 05/12/2019 Brenda E Ramirez. */ /* Statement: */ #include <bits/stdc++.h> #include <limits.h> #include <algorithm> #include <numeric> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define endl '\n' using ll = long long; const int precision = 16; const int modulo = 1000000007; // 10^9 + 7 const ll lmodulo = 1000000007; // 10^9 + 7 const double EPS = 1e-9; void solveA() { int n; cin >> n; int pp = 0; int p = 0; ll ret = 0; while(n--) { int cur; cin >> cur; if(cur == p) { cout << "Infinite"; return; } if(pp == 3 and p == 1 and cur == 2) { ret += 2; } else { int tp = p; int tcur = cur; if(tp > tcur) swap(tp, tcur); if(tp == 2 and tcur == 3) { cout << "Infinite"; return; } else if(tp == 1 and tcur == 2) { ret += 3; } else if(tp == 1 and tcur == 3) { ret += 4; } } pp = p; p = cur; } cout <<"Finite" << endl << ret; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.precision(precision); cout.setf(ios_base::fixed); solveA(); return 0;
19.2
68
0.465278
gmeligio
108ee3df534bebc0f003c1a1d476c137aca231d1
23,882
cpp
C++
UDPEchoWithBroadcast/server.cpp
henry9836/UDPChat
8a31662236f8a223e7b73a2c5267999becc11837
[ "MIT" ]
1
2019-05-20T00:06:02.000Z
2019-05-20T00:06:02.000Z
UDPEchoWithBroadcast/server.cpp
henry9836/UDPChat
8a31662236f8a223e7b73a2c5267999becc11837
[ "MIT" ]
null
null
null
UDPEchoWithBroadcast/server.cpp
henry9836/UDPChat
8a31662236f8a223e7b73a2c5267999becc11837
[ "MIT" ]
null
null
null
// // (c) 2015 Media Design School // // File Name : server.cpp // Description : Does server work // Author : Henry Oliver // Mail : henry983615@gmail.com // //Library Includes #include <WS2tcpip.h> #include <iostream> #include <utility> #include <thread> #include <chrono> #include <stdlib.h> #include <time.h> #include <math.h> //Local Includes #include "utils.h" #include "network.h" #include "consoletools.h" #include "socket.h" //Local Includes #include "server.h" //Global Temps std::string addrTmp = ""; CServer::CServer() :m_pcPacketData(0), m_pServerSocket(0) { ZeroMemory(&m_ClientAddress, sizeof(m_ClientAddress)); } CServer::~CServer() { delete m_pConnectedClients; m_pConnectedClients = 0; delete m_pServerSocket; m_pServerSocket = 0; delete m_pWorkQueue; m_pWorkQueue = 0; delete[] m_pcPacketData; m_pcPacketData = 0; } bool CServer::Initialise() { m_pcPacketData = new char[MAX_MESSAGE_LENGTH]; //Create a work queue to distribute messages between the main thread and the receive thread. m_pWorkQueue = new CWorkQueue<std::pair<sockaddr_in, std::string>>(); //Create a socket object m_pServerSocket = new CSocket(); //Get the port number to bind the socket to unsigned short _usServerPort = QueryPortNumber(DEFAULT_SERVER_PORT); //Initialise the socket to the local loop back address and port number if (!m_pServerSocket->Initialise(_usServerPort)) { return false; } //Qs 2: Create the map to hold details of all connected clients m_pConnectedClients = new std::map < std::string, TClientDetails >() ; return true; } bool CServer::AddClient(std::string _strClientName) { //TO DO : Add the code to add a client to the map here... for (auto it = m_pConnectedClients->begin(); it != m_pConnectedClients->end(); ++it) { //Check to see that the client to be added does not already exist in the map, if(it->first == ToString(m_ClientAddress)) { TPacket _packetToSend; std::string message = "Connection Refused: IP Already Exists"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, m_ClientAddress); return false; } //also check for the existence of the username if (it->second.m_strName == _strClientName) { TPacket _packetToSend; std::string message = "Connection Refused: User Already Exists"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, m_ClientAddress); return false; } } //Add the client to the map. TClientDetails _clientToAdd; _clientToAdd.m_strName = _strClientName; _clientToAdd.m_ClientAddress = this->m_ClientAddress; std::string _strAddress = ToString(m_ClientAddress); addrTmp = _strAddress; //Add security info _clientToAdd.SECURITY.authIP = _strAddress; _clientToAdd.SECURITY.authStatus = _clientToAdd.SECURITY.NOAUTH; _clientToAdd.SECURITY.authUser = _clientToAdd.m_strName; _clientToAdd.SECURITY.authUser = _clientToAdd.SECURITY.authUser.substr(1, _clientToAdd.SECURITY.authUser.length()); //get rid of padding _clientToAdd.SECURITY.key = 4 + rand() % 150; //Check for bad chars in security info std::string ENDLN = "$END"; size_t pos = _clientToAdd.SECURITY.authUser.find(ENDLN); while (pos != std::string::npos) { _clientToAdd.SECURITY.authUser.replace(pos, ENDLN.size(), ""); pos = _clientToAdd.SECURITY.authUser.find(ENDLN, pos + 0); } //Insert into the map m_pConnectedClients->insert(std::pair < std::string, TClientDetails > (_strAddress, _clientToAdd)); return true; } bool CServer::SendData(char* _pcDataToSend) { int _iBytesToSend = (int)strlen(_pcDataToSend) + 1; int iNumBytes = sendto( m_pServerSocket->GetSocketHandle(), // socket to send through. _pcDataToSend, // data to send _iBytesToSend, // number of bytes to send 0, // flags reinterpret_cast<sockaddr*>(&m_ClientAddress), // address to be filled with packet target sizeof(m_ClientAddress) // size of the above address struct. ); //iNumBytes; if (_iBytesToSend != iNumBytes) { std::cout << "There was an error in sending data from client to server" << std::endl; return false; } return true; } bool CServer::SendDataTo(char* _pcDataToSend, sockaddr_in _clientAdrress) { int _iBytesToSend = (int)strlen(_pcDataToSend) + 1; int iNumBytes = sendto( m_pServerSocket->GetSocketHandle(), // socket to send through. _pcDataToSend, // data to send _iBytesToSend, // number of bytes to send 0, // flags reinterpret_cast<sockaddr*>(&_clientAdrress), // address to be filled with packet target sizeof(_clientAdrress) // size of the above address struct. ); //iNumBytes; if (_iBytesToSend != iNumBytes) { std::cout << "There was an error in sending data from client to server" << std::endl; return false; } return true; } void CServer::ReceiveData(char* _pcBufferToReceiveData) { int iSizeOfAdd = sizeof(m_ClientAddress); int _iNumOfBytesReceived; int _iPacketSize; //Make a thread local buffer to receive data into char _buffer[MAX_MESSAGE_LENGTH]; while (true) { // pull off the packet(s) using recvfrom() _iNumOfBytesReceived = recvfrom( // pulls a packet from a single source... m_pServerSocket->GetSocketHandle(), // client-end socket being used to read from _buffer, // incoming packet to be filled MAX_MESSAGE_LENGTH, // length of incoming packet to be filled 0, // flags reinterpret_cast<sockaddr*>(&m_ClientAddress), // address to be filled with packet source &iSizeOfAdd // size of the above address struct. ); if (_iNumOfBytesReceived < 0) { int _iError = WSAGetLastError(); ErrorRoutines::PrintWSAErrorInfo(_iError); //return false; } else { _iPacketSize = static_cast<int>(strlen(_buffer)) + 1; strcpy_s(_pcBufferToReceiveData, _iPacketSize, _buffer); char _IPAddress[100]; inet_ntop(AF_INET, &m_ClientAddress.sin_addr, _IPAddress, sizeof(_IPAddress)); std::cout << "Server Received \"" << _pcBufferToReceiveData << "\" from " << _IPAddress << ":" << ntohs(m_ClientAddress.sin_port) << std::endl; //Push this packet data into the WorkQ m_pWorkQueue->push(std::make_pair(m_ClientAddress,_pcBufferToReceiveData)); } //std::this_thread::yield(); } //End of while (true) } void CServer::GetRemoteIPAddress(char *_pcSendersIP) { char _temp[MAX_ADDRESS_LENGTH]; int _iAddressLength; inet_ntop(AF_INET, &(m_ClientAddress.sin_addr), _temp, sizeof(_temp)); _iAddressLength = static_cast<int>(strlen(_temp)) + 1; strcpy_s(_pcSendersIP, _iAddressLength, _temp); } unsigned short CServer::GetRemotePort() { return ntohs(m_ClientAddress.sin_port); } std::string XOR(std::string input, int key, bool encode) { std::string output = ""; std::string split = "\\"; std::string tmpstr = ""; std::vector<int> toDecode; char decodeTMP; int position = 0; int xor = 0; if (encode) { int xor = 0; for (size_t i = 0; i < input.length(); i++) { xor = ((input.at(i)) ^ key); output += std::to_string(xor) + split; } } else { //decode for (size_t i = 0; i < input.length(); i++) { if (input.at(i) != split.at(0)) { tmpstr += input.at(i); } else { //std::cout << tmpstr << std::endl; toDecode.push_back(std::atoi(tmpstr.c_str())); tmpstr = ""; } } //std::cout << tmpstr << std::endl; toDecode.push_back(std::atoi(tmpstr.c_str())); tmpstr = ""; for (size_t k = 0; k < toDecode.size(); k++) { xor = (toDecode.at(k) ^ key); //decode decodeTMP = xor; //convert to ascii output += decodeTMP; //add to output } } return output; } void CServer::CheckPulse() { TPacket _packetToSend; std::string templ = "Ping"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if (((*m_pConnectedClients)[it->first].SECURITY.authStatus != (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHING) || (*m_pConnectedClients)[it->first].SECURITY.markedforDeath) { //only check authed clients std::string message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(KEEPALIVE, const_cast<char*>(message.c_str())); (*m_pConnectedClients)[it->first].m_bIsAlive = false; SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } } void CServer::DropTheDead(){ TPacket _packetToSend; std::string templ = ""; std::string message = ""; int amountremoved = 0; std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); while (it != (*m_pConnectedClients).end()) { if (((*m_pConnectedClients)[it->first].SECURITY.authStatus != (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHING) || (*m_pConnectedClients)[it->first].SECURITY.markedforDeath) { //only check authed clients if (!(*m_pConnectedClients)[it->first].m_bIsAlive) { templ += "$END User: " + (*m_pConnectedClients)[it->first].SECURITY.authUser + " disconnected (Timed Out)"; (*m_pConnectedClients).erase(it); it = (*m_pConnectedClients).begin(); } else { ++it; } } else {//otherwise if we are authing the client then check a flag to say client has taken at least one dead loop and if it is marked next time to drop it (*m_pConnectedClients)[it->first].SECURITY.markedforDeath = true; ++it; } } if (templ != "") { for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { //only authed clients can see msgs message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } } } void CServer::ProcessData(std::pair<sockaddr_in, std::string> dataItem) { TPacket _packetRecvd, _packetToSend; _packetRecvd = _packetRecvd.Deserialize(const_cast<char*>(dataItem.second.c_str())); switch (_packetRecvd.MessageType) { case INITCONN: { std::string message = ""; std::cout << "Server received a request to start a handshake" << std::endl; if (AddClient(_packetRecvd.MessageContent)) { //Qs 3: To DO : Add the code to do a handshake here //If this is first AUTH then we need create an xor challenge std::map<std::string, char> m; int key = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key; m_pConnectedClients->at(ToString(m_ClientAddress)).SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHING; message = "%" + XOR((dataItem.second.substr(2, dataItem.second.length()) + "#" + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b1) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b2) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b3) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b4)), key, true); //ADD XOR KEY ON int amountofch = static_cast<int>(floor(key / 10)); for (size_t i = 0; i < amountofch; i++) { int tmp = (48 + rand() % 78); char ctmp = tmp; message = ctmp + message; } _packetToSend.Serialize(AUTHCH, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); } else { std::cout << "Could not add user" << std::endl; } break; } case AUTHRE: { std::cout << "Server received a handshake response" << std::endl; std::string message = "ACCEPT"; std::string check = ""; //CHECK RESPONSE int key = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key; check = XOR(_packetRecvd.MessageContent, key, false); //decode if (check.find((*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser) != std::string::npos) { //correct response std::cout << "HANDSHAKE COMPLETED" << std::endl; _packetToSend.Serialize(AUTHRE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); message = MOTD + "Welcome to the chat " + (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + "$ENDUsers in Chat:"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { message += "$END [" + (*m_pConnectedClients)[it->first].SECURITY.authUser + "]"; } message += "$END"; _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE; (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.markedforDeath = false; //reset if was set by drop dead //Send to each user that user has joined chat std::string templ = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + " has connected to the chat!"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { std::string message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } else { //incorrect response std::cout << "HANDSHAKE FAILED" << std::endl; message = "REJECT"; _packetToSend.Serialize(AUTHRE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.NOAUTH; message = "QUIT"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); m_pConnectedClients->erase(ToString(m_ClientAddress)); //remove user from list } } case DATA: { if ((*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { std::string message = XOR(_packetRecvd.MessageContent, (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key, false); //decode std::cout << "Decoded: " << message << std::endl; message = message.substr(0, message.length()-1); //fix padding bool isCommand = false; if (message.length() >= 1){ //stop null strings from crashing server if (message.at(0) == COMMANDID.at(0)) { isCommand = true; } if (!isCommand){ //Chat //Send to each user message = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + "> " + message; std::string templ = message; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { //only authed clients can see msgs message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } } else { //Command if (message == COMMANDHELP) { message = HELP; } else if (message.find(COMMANDCHGMOTD) != std::string::npos) { if (message.length() > (COMMANDCHGMOTD.length() + 1)) { MOTD = message.substr(COMMANDCHGMOTD.length() + 1, message.length()); message = "motd changed to: " + MOTD; } } else if (message == COMMANDMOTD) { message = MOTD; } else if (message.find(COMMANDKICK) != std::string::npos) { if (message.length() > (COMMANDKICK.length() + 1)) { std::string target = message.substr(COMMANDKICK.length() + 1, message.length()); bool hasKicked = false; std::map<std::string, TClientDetails>::const_iterator targetLock; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authUser == target) { (*m_pConnectedClients)[it->first].SECURITY.authStatus = (*m_pConnectedClients)[it->first].SECURITY.NOAUTH; (*m_pConnectedClients)[it->first].SECURITY.markedforDeath = true; std::string message = XOR("You have been kicked from the server", (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); message = "QUIT"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); hasKicked = true; targetLock = it; } } if (hasKicked) { std::string templ = (*m_pConnectedClients)[targetLock->first].SECURITY.authUser + " has been kicked from the chat!"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { std::string message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } m_pConnectedClients->erase(targetLock); //remove user from list } else { std::string message = XOR("Could not find username", (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); } } } else if (message == COMMANDQUIT) { //CLOSE CONNECTION (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.NOAUTH; //Deauth user message = "User: " + (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + " has disconnected (User Disconnect)"; std::string templ = message; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { //only authed clients can see msgs message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } message = "QUIT"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); m_pConnectedClients->erase(ToString(m_ClientAddress)); //remove user from list } else if (message == COMMANDLIST) { message = "$ENDUsers in Chat:"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { message += "$END [" + (*m_pConnectedClients)[it->first].SECURITY.authUser + "]"; } message += "$END"; } else { message = "Unknown Command"; } message = XOR(message, (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); } } } else { std::string out = (std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b1) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b2) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b3) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b4)); std::cout << "CLIENT WAS BLOCKED FROM USING SERVER AS THEY ARE NOT AUTHED: " << out << std::endl; out = "REJECT"; _packetToSend.Serialize(AUTHRE, const_cast<char*>(out.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); } break; } case BROADCAST: { std::cout << "Received a broadcast packet" << std::endl; //Just send out a packet to the back to the client again which will have the server's IP and port in it's sender fields std::string message = "<SERVER INFO>"; _packetToSend.Serialize(BROADCASTINIT, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); break; } case KEEPALIVEC: { std::string message = "<SERVER INFO>"; _packetToSend.Serialize(KEEPALIVEC, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); break; } case KEEPALIVE: { m_pConnectedClients->at(ToString(m_ClientAddress)).m_bIsAlive = true; //we have ping-pong break; } default: std::string message = "You are not authorised to connect to this server!"; //go from 0-10 and give error msg _packetToSend.Serialize(PACKERROR, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR1, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR2, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR3, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR4, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR5, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR6, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR7, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR8, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR9, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR10, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); break; } } CWorkQueue<std::pair<sockaddr_in, std::string>>* CServer::GetWorkQueue() { return m_pWorkQueue; }
39.15082
350
0.679549
henry9836
1090a9fb484f4c10c2600fd71d0ac46dc4b445c3
490
cpp
C++
engine/src/PhysicsEngine/API/ActivationListener.cpp
nuclearkevin/Strontium
88045e7ab50f614bbbcb8c283e2a7802fd435207
[ "MIT" ]
null
null
null
engine/src/PhysicsEngine/API/ActivationListener.cpp
nuclearkevin/Strontium
88045e7ab50f614bbbcb8c283e2a7802fd435207
[ "MIT" ]
null
null
null
engine/src/PhysicsEngine/API/ActivationListener.cpp
nuclearkevin/Strontium
88045e7ab50f614bbbcb8c283e2a7802fd435207
[ "MIT" ]
null
null
null
#include "PhysicsEngine/API/ActivationListener.h" // Project includes. #include "Core/Logs.h" // THIS MUST BE THREAD SAFE namespace Strontium::PhysicsEngine { ActivationListener::ActivationListener() { } ActivationListener::~ActivationListener() { } void ActivationListener::OnBodyActivated(const JPH::BodyID &inBodyID, JPH::uint64 inBodyUserData) { } void ActivationListener::OnBodyDeactivated(const JPH::BodyID &inBodyID, JPH::uint64 inBodyUserData) { } }
22.272727
96
0.738776
nuclearkevin
1091a31f094613e73f1bd2363b52f25b7704ec7a
664
cpp
C++
CS2370/Code/default_args.cpp
Davidjbennett/DavidBennett.github.io
09a2652b7ace8741bf23c6432abd58ee790b9f0c
[ "MIT" ]
3
2021-05-18T16:17:29.000Z
2022-01-20T15:46:59.000Z
CS2370/Code/default_args.cpp
Davidjbennett/DavidBennett
09a2652b7ace8741bf23c6432abd58ee790b9f0c
[ "MIT" ]
null
null
null
CS2370/Code/default_args.cpp
Davidjbennett/DavidBennett
09a2652b7ace8741bf23c6432abd58ee790b9f0c
[ "MIT" ]
null
null
null
#include <cassert> #include <iostream> #include <string> using namespace std; char digit_chars[] = {'0','1','2','3','4','5','6','7', '8','9','A','B','C','D','E','F'}; string convert(int num, int base = 10) { assert(2 <= base && base <= 16); string result; while (num > 0) { int digit = num % base; result = digit_chars[digit] + result; num /= base; } return result; } int main() { cout << convert(30, 2) << endl; // Binary cout << "\""s + convert(30) + "\""s << endl; // Decimal (default) cout << convert(30, 16) << endl; // Hexadecimal } /* Output: 11110 "30" 1E */
20.75
76
0.49247
Davidjbennett
10a5e59cbd5f17b1323edd441eb4c343b699da6e
3,371
cpp
C++
utility/BoundingBox.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
utility/BoundingBox.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
utility/BoundingBox.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
#include "utility/BoundingBox.hpp" #include <algorithm> namespace math { BoundingBox::BoundingBox(const math::Vertex& min, const math::Vertex& max) { setCorners(min, max); } void BoundingBox::transform(const math::Matrix& mat) { float min = std::numeric_limits<float>::lowest(); float max = std::numeric_limits<float>::max(); math::Vertex newMin = {max, max, max}; math::Vertex newMax = {min, min, min}; math::Vertex corners[8]; getCorners(corners); for (auto& v : corners) { v = math::Vertex::Transform(v, mat); newMin = takeMinimum(newMin, v); newMax = takeMaximum(newMax, v); } setCorners(newMin, newMax); } void BoundingBox::setCorners(const math::Vertex& min, const math::Vertex& max) { MinCorner = min; MaxCorner = max; } void BoundingBox::getCorners(math::Vertex corners[8]) const { corners[0] = {MinCorner.X, MinCorner.Y, MinCorner.Z}; corners[1] = {MaxCorner.X, MinCorner.Y, MinCorner.Z}; corners[2] = {MaxCorner.X, MaxCorner.Y, MinCorner.Z}; corners[3] = {MinCorner.X, MaxCorner.Y, MinCorner.Z}; corners[4] = {MinCorner.X, MinCorner.Y, MaxCorner.Z}; corners[5] = {MaxCorner.X, MinCorner.Y, MaxCorner.Z}; corners[6] = {MaxCorner.X, MaxCorner.Y, MaxCorner.Z}; corners[7] = {MinCorner.X, MaxCorner.Y, MaxCorner.Z}; } void BoundingBox::connectWith(const BoundingBox& b) { MinCorner = takeMinimum(MinCorner, b.MinCorner); MaxCorner = takeMaximum(MaxCorner, b.MaxCorner); } void BoundingBox::update(const math::Vector3& v) { MinCorner.X = (std::min)(MinCorner.X, v.X); MaxCorner.X = (std::max)(MaxCorner.X, v.X); MinCorner.Y = (std::min)(MinCorner.Y, v.Y); MaxCorner.Y = (std::max)(MaxCorner.Y, v.Y); MinCorner.Z = (std::min)(MinCorner.Z, v.Z); MaxCorner.Z = (std::max)(MaxCorner.Z, v.Z); } float BoundingBox::getVolume() const { math::Vector3 e = MaxCorner - MinCorner; return e.X * e.Y * e.Z; } float BoundingBox::getSurfaceArea() const { math::Vector3 e = MaxCorner - MinCorner; return 2.0f * (e.X * e.Y + e.X * e.Z + e.Y * e.Z); } math::Vector3 BoundingBox::getCenter() const { return 0.5f * (MaxCorner + MinCorner); } math::Vector3 BoundingBox::getExtent() const { return 0.5f * (MaxCorner - MinCorner); } math::Vector3 BoundingBox::getVector() const { return MaxCorner - MinCorner; } const math::Vector3& BoundingBox::getMinimum() const { return MinCorner; } const math::Vector3& BoundingBox::getMaximum() const { return MaxCorner; } bool BoundingBox::intersect2d(const BoundingBox& b) const { if (MaxCorner.X < b.MinCorner.X) return false; if (MinCorner.X > b.MaxCorner.X) return false; if (MaxCorner.Y < b.MinCorner.Y) return false; if (MinCorner.Y > b.MaxCorner.Y) return false; return true; } bool BoundingBox::intersect(const BoundingBox& b) const { if (!intersect2d(b)) return false; if (MaxCorner.Z < b.MinCorner.Z) return false; if (MinCorner.Z > b.MaxCorner.Z) return false; return true; // boxes overlap } std::ostream& operator<<(std::ostream& o, const BoundingBox& b) { o << b.MinCorner << b.MaxCorner; return o; } std::istream& operator>>(std::istream& i, BoundingBox& b) { i >> b.MinCorner >> b.MaxCorner; return i; } } // namespace math
23.573427
78
0.643429
coolzoom
10a7c0a1e611695162b9a5d34a4093d64198bf88
8,678
cpp
C++
BBB_cci_gemm/sw/lib/gemmHelper.cpp
ddcc/intel-fpga-bbb
254217f47123f0e83300c3240349b7308fb7e037
[ "BSD-3-Clause" ]
5
2020-04-04T12:13:30.000Z
2022-01-26T19:48:29.000Z
BBB_cci_gemm/sw/lib/gemmHelper.cpp
ddcc/intel-fpga-bbb
254217f47123f0e83300c3240349b7308fb7e037
[ "BSD-3-Clause" ]
null
null
null
BBB_cci_gemm/sw/lib/gemmHelper.cpp
ddcc/intel-fpga-bbb
254217f47123f0e83300c3240349b7308fb7e037
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2017, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // Neither the name of the Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL 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 "gemmHelper.hpp" ////////////////////////////////////////////////////////////////////////////// // Generic Function Implementations ////////////////////////////////////////////////////////////////////////////// template <typename T> void gemmHelper<T>::fillMatrix(vector<T> &mat, const uint32_t nrows, const uint32_t ncols, bool isRands) { for (int i = 0; i < nrows; i++) { for (int j = 0; j < ncols; j++) { if (isRands) { mat[i * ncols + j] = randRange(static_cast<T>(-20), static_cast<T>(20)); } else { if (j > (ncols - 16)) { mat[i * ncols + j] = randRange(static_cast<T>(-2), static_cast<T>(2)); } else if ((i == nrows - 1) && (j == ncols - 1)) { mat[i * ncols + j] = static_cast<T>(2); } else if (i % (16) == 0) { mat[i * ncols + j] = static_cast<T>(1); } else { mat[i * ncols + j] = static_cast<T>(0); } } } } } template <typename T> void gemmHelper<T>::fillPadded(vector<T> &matIn, vector<T> &matOut, const uint32_t req_lead, const uint32_t req_common, const uint32_t num_lead, const uint32_t num_common) { for (int i = 0; i < req_lead; i++) { for (int j = 0; j < req_common; j++) { matOut[i * num_common + j] = matIn[i * req_common + j]; } } } template <typename T> void gemmHelper<T>::fillUnPadded(vector<T> &matIn, vector<T> &matOut, const uint32_t req_lead, const uint32_t req_common, const uint32_t num_lead, const uint32_t num_common) { for (int i = 0; i < req_lead; i++) { for (int j = 0; j < req_common; j++) { matOut[i * req_common + j] = matIn[i * num_common + j]; } } } template <typename T> void gemmHelper<T>::zeroMatrix(vector<T> &mat, const uint32_t nrows, const uint32_t ncols) { for (int i = 0; i < nrows; i++) { for (int j = 0; j < ncols; j++) { mat[i * ncols + j] = static_cast<T>(0); } } } template <typename T> void gemmHelper<T>::unpack(vector<T> &matIn, vector<T> &matOut, const uint32_t num_partsb, const uint32_t num_partsa, const uint32_t sgemm_rows, const uint32_t sgemm_cols, const uint32_t a_lead_interleave, const uint32_t b_lead_interleave) { for (uint32_t bi = 0; bi < num_partsb; bi++) { for (uint32_t ai = 0; ai < num_partsa; ai++) { for (uint32_t l = 0; l < sgemm_rows; l++) { for (uint32_t j = 0; j < sgemm_cols; j++) { for (uint32_t i = 0; i < a_lead_interleave; i++) { for (uint32_t k = 0; k < b_lead_interleave; k++) { uint32_t m_index = (ai * num_partsb * sgemm_rows * sgemm_cols * a_lead_interleave * b_lead_interleave) + (bi * sgemm_cols * b_lead_interleave) + (sgemm_rows - 1 - l) * a_lead_interleave * num_partsb * b_lead_interleave * sgemm_cols + j * b_lead_interleave + i * num_partsb * b_lead_interleave * sgemm_cols + k; uint32_t cl_index = (bi * num_partsa * sgemm_rows * a_lead_interleave * b_lead_interleave + ai * sgemm_rows * a_lead_interleave * b_lead_interleave + l * a_lead_interleave * b_lead_interleave + i * b_lead_interleave + k) * sgemm_cols + j; matOut[m_index] = matIn[cl_index]; } } } } } } } ////////////////////////////////////////////////////////////////////////////// // Specialized Function Implementations ////////////////////////////////////////////////////////////////////////////// template <> int gemmHelper<int>::randRange(int min, int max) { int randNum = rand() % (max - min); return randNum + min; } template <> float gemmHelper<float>::randRange(float min, float max) { return min + static_cast<float>( rand() / ((static_cast<float>(RAND_MAX) / (max - min)))); } template <> void gemmHelper<float>::pack(vector<float> &matIn, vector<float> &matOut, const uint32_t nrows, const uint32_t ncols, bool type, const uint32_t DATA_WIDTH, const uint32_t PACK_SIZE) { for (uint32_t ii = 0; ii < nrows; ii++) { for (uint32_t jj = 0; jj < ncols; jj++) { matOut[ii * ncols + jj] = matIn[ii * ncols + jj]; } } } // Special Functions for Binary and Ternary template <> void gemmHelper<int>::fillTMatrix(vector<int> &mat, const uint32_t nrows, const uint32_t ncols, bool isRands) { int i, j; for (i = 0; i < nrows; i++) { for (j = 0; j < ncols; j++) { if (isRands) { mat[i * ncols + j] = (rand() % 3); } else { mat[i * ncols + j] = 0x1; } } } } template <> void gemmHelper<int>::fillBMatrix(vector<int> &mat, const uint32_t nrows, const uint32_t ncols, bool isRands) { int i, j; for (i = 0; i < nrows; i++) { for (j = 0; j < ncols; j++) { mat[i * ncols + j] = (rand() % 2) ? 1 : -1; } } } template <> void gemmHelper<int>::zeroBMatrix(vector<int> &mat, const uint32_t nrows, const uint32_t ncols) { int i, j; for (i = 0; i < nrows; i++) { for (j = 0; j < ncols; j++) { // Special XOR GEMM Zeroing mat[i * ncols + j] = (i % 2) ? 1 : -1; } } } template <> void gemmHelper<int>::packB(vector<int> &matIn, vector<int> &matOut, const uint32_t nrows, const uint32_t ncols, bool type, const uint32_t PACK_SIZE) { if (type) { // Pack A for (int mm = 0; mm < nrows; mm++) // each row for (int kk = 0; kk < (ncols / PACK_SIZE); kk++) { // each 32 cols in row int packbits = 0; // Pack 32 A row elements into bin32 for (int t = 0; t < PACK_SIZE; t++) { if (matIn[(mm * ncols) + (kk * PACK_SIZE) + t] == 1) packbits |= (0x00000001 << t); } matOut[(mm * (ncols / PACK_SIZE)) + kk] = packbits; } } else { // Pack B for (int nn = 0; nn < nrows / PACK_SIZE; nn++) // each col for (int kk = 0; kk < ncols; kk++) { // each 32 rows in col int packbits = 0; // Pack 32 B col elements into bin32 for (int t = 0; t < PACK_SIZE; t++) { if (matIn[(nn * ncols * PACK_SIZE) + (kk) + (t * ncols)] == 1) packbits |= (0x00000001 << t); } matOut[(nn * ncols) + kk] = packbits; } } } template class gemmHelper<int>; template class gemmHelper<float>;
36.92766
80
0.528002
ddcc
10a7f4d0f9d6cf651919cc9afaa9a60453cf2f31
595
hpp
C++
include/cvtools.hpp
Biblbrox/point-cloud-annotation-tool
66947974914243af8e5f1bb622ffaa93c2fdb47d
[ "MIT" ]
null
null
null
include/cvtools.hpp
Biblbrox/point-cloud-annotation-tool
66947974914243af8e5f1bb622ffaa93c2fdb47d
[ "MIT" ]
null
null
null
include/cvtools.hpp
Biblbrox/point-cloud-annotation-tool
66947974914243af8e5f1bb622ffaa93c2fdb47d
[ "MIT" ]
null
null
null
#ifndef CVTOOLS_HPP #define CVTOOLS_HPP #include <opencv2/imgproc.hpp> #include <algorithm> namespace cvtools { /** * Add border to image * @param mat * @param borderSize * @return */ cv::Mat addBorder(const cv::Mat& mat, int borderSize); /** * Calculate truncation of rect in image coordinates. * @param mat * @param rect * @param mat * @param rect * @param imgPos * @return float from 0 to 1x */ float calcTruncated(const cv::Mat& mat, const cv::Rect& rect, const cv::Point& imgPos); }; #endif //CVTOOLS_HPP
19.833333
91
0.610084
Biblbrox
10a831ddd2342ec7a67a532f9ed465005f71bc9e
4,561
cpp
C++
Source/Game/MainMenuState.cpp
Fiskmans/Old_Betsy
6610586165250d21de9b9efb57b4e8e56e82ecdf
[ "MIT" ]
3
2021-05-06T19:54:20.000Z
2021-05-06T21:15:50.000Z
Source/Game/MainMenuState.cpp
Fiskmans/Old_Betsy
6610586165250d21de9b9efb57b4e8e56e82ecdf
[ "MIT" ]
null
null
null
Source/Game/MainMenuState.cpp
Fiskmans/Old_Betsy
6610586165250d21de9b9efb57b4e8e56e82ecdf
[ "MIT" ]
null
null
null
#include "pch.h" #include "MainMenuState.h" #include "GraphicEngine.h" #include "DirectX11Framework.h" #include "SpriteInstance.h" #include <Xinput.h> #include "AssetManager.h" #include "GamlaBettan\Scene.h" MainMenuState::MainMenuState(bool aShouldDeleteOnPop) : BaseState(aShouldDeleteOnPop), Observer( { MessageType::InputMouseMoved }), myStateInitData{ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } { SetUpdateThroughEnabled(false); SetDrawThroughEnabled(false); myBackground = nullptr; myMousePointer = nullptr; } MainMenuState::~MainMenuState() { Deactivate(); for (Button* button : myButtons) { delete button; } myButtons.clear(); delete myMousePointer; delete myBackground; WIPE(*this); } void MainMenuState::Update(const float aDeltaTime) { if (myGameStateToStart) { myGameStateToStart->PreSetup(aDeltaTime); } #if DIRECTTOGAME static bool first = true; if (first) { myPlayButton.TriggerOnPressed(); first = false; } #endif } void MainMenuState::RecieveMessage(const Message& aMessage) { if (aMessage.myMessageType == MessageType::InputMouseMoved) { myMousePointer->SetPosition(*reinterpret_cast<const V2f*>(aMessage.myData)); } } bool MainMenuState::Init(InputManager* aInputManager, SpriteFactory* aSpritefactory, LightLoader* aLightLoader, DirectX11Framework* aFramework, AudioManager* aAudioManager, SpriteRenderer* aSpriteRenderer) { myIsMain = true; myMousePointer = aSpritefactory->CreateSprite("ui/mouse.dds"); myStateInitData.myFrameWork = aFramework; myStateInitData.myInputManager = aInputManager; myStateInitData.myLightLoader = aLightLoader; myStateInitData.mySpriteFactory = aSpritefactory; myStateInitData.myAudioManager = aAudioManager; myStateInitData.mySpriteRenderer = aSpriteRenderer; InitLayout(aSpritefactory); return true; } void MainMenuState::Render(CGraphicsEngine* aGraphicsEngine) { aGraphicsEngine->RenderFrame(); } void MainMenuState::Activate() { for (Button* button : myButtons) { button->Enable(); } Scene::GetInstance().AddToScene(myMousePointer); Scene::GetInstance().AddToScene(myBackground); } void MainMenuState::Deactivate() { for (Button* button : myButtons) { button->Disable(); } Scene::GetInstance().RemoveFromScene(myMousePointer); Scene::GetInstance().RemoveFromScene(myBackground); } void MainMenuState::Unload() { } void MainMenuState::InitLayout(SpriteFactory* aSpritefactory) { FiskJSON::Object& root = AssetManager::GetInstance().GetJSON("menu/MainMenuLayout.json").GetAsJSON(); std::string imagesPath = root["ImagesPath"].Get<std::string>(); myBackground = aSpritefactory->CreateSprite(imagesPath + "\\" + root["GameTitleImage"]["name"].Get<std::string>()); myBackground->SetPosition({ root["GameTitleImage"]["PosX"].Get<float>(), root["GameTitleImage"]["PosY"].Get<float>() }); myBackground->SetUVMinMaxInTexels(V2f(0, 0), V2f(1920.f, 1080.f)); myBackground->SetDepth(1.f); myBackground->SetSize(V2f(1, 1)); Button* playButton = new Button(); Button* exitButton = new Button(); playButton->Init(imagesPath, root["StartButton"]["name"].Get<std::string>(), { root["StartButton"]["PosX"].Get<float>(), root["StartButton"]["PosY"].Get<float>() }, V2f(0.545f, 1.f), aSpritefactory); exitButton->Init(imagesPath, root["ExitButton"]["name"].Get<std::string>(), { root["ExitButton"]["PosX"].Get<float>(), root["ExitButton"]["PosY"].Get<float>() }, V2f(0.545f, 1.f), aSpritefactory); if (!myGameStateToStart) { myGameStateToStart = CreateGameState(0); } playButton->SetOnPressedFunction([this]() -> void { Message message; message.myMessageType = MessageType::PushState; if (myGameStateToStart) { message.myData = myGameStateToStart; myGameStateToStart = nullptr; } else { message.myData = CreateGameState(0); } PostMaster::GetInstance().SendMessages(message); }); exitButton->SetOnPressedFunction([this]() -> void { bool mainState = true; PostMaster::GetInstance().SendMessages(MessageType::PopState,&mainState); }); myButtons.push_back(playButton); myButtons.push_back(exitButton); } GameState* MainMenuState::CreateGameState(const int& aStartLevel) { GameState* state = new GameState(); if (state->Init(myStateInitData.myInputManager, myStateInitData.mySpriteFactory, myStateInitData.myLightLoader, myStateInitData.myFrameWork, myStateInitData.myAudioManager, myStateInitData.mySpriteRenderer) == false) { delete state; return nullptr; } state->SetMain(true); state->LoadLevel(aStartLevel); return state; }
25.338889
201
0.740627
Fiskmans
10a8f11069f0035c59ae3fdba72c2e7128d7aee0
426
cpp
C++
AtCoder/ABC187/C.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
AtCoder/ABC187/C.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
AtCoder/ABC187/C.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; unordered_set<string> sSet; string s; for(int i = 0; i < n; ++i){ cin >> s; sSet.insert(s); } string answer = "satisfiable"; for(string s: sSet){ if(sSet.count("!" + s)){ answer = s; break; } } cout << answer; return 0; }
16.384615
35
0.42723
Tudor67
10a96920a382c79fa8690483d17ba10ad342fd40
1,292
cpp
C++
test/list_test.cpp
jgke/putkijuoksu
bf34eb707a7a5681341940ec203aec9b42f75bc7
[ "MIT" ]
null
null
null
test/list_test.cpp
jgke/putkijuoksu
bf34eb707a7a5681341940ec203aec9b42f75bc7
[ "MIT" ]
null
null
null
test/list_test.cpp
jgke/putkijuoksu
bf34eb707a7a5681341940ec203aec9b42f75bc7
[ "MIT" ]
null
null
null
#define DEBUG #include "test.hpp" #include "coord.hpp" #include "list.hpp" #include "list_test.hpp" void list_test() { NO_DEATH_TEST("List doesn't crash when constructor/destructor is called", { List<int> *tmp = new List<int>(); delete tmp; }); List<int> cur; test_equal("List starts with size 0", 0, cur.size()); cur.add(1); test_equal("List grows to size 1", 1, cur.size()); test_equal("List contains element 1", 1, cur.get(0)); cur.remove(0); test_equal("List shrinks to size 0", 0, cur.size()); int a = 2; cur.add(a); test_equal("List contains element 2", 2, cur.get(0)); a = 3; test_equal("List content doesn't change on variable change", 2, cur.get(0)); List<Coord> coords; coords.add(Coord(1, 2)); test_equal("Can add class to list", Coord(1, 2), coords.get(0)); Coord tmpcoord(3, 4); coords.add(tmpcoord); test_equal("Adding variable doesn't change order", Coord(1, 2), coords.get(0)); test_equal("Can add class to List", Coord(3, 4), coords.get(1)); tmpcoord = Coord(5, 6); test_equal("List content doesn't change on variable change", Coord(3, 4), coords.get(1)); DEATH_TEST("List crashes on out of bounds get", { List<int> tmp; tmp.get(0); }); }
31.512195
93
0.619969
jgke
10aa0375a751f008a6f77356abc3511d7bcce66f
2,125
cpp
C++
tests/quasiquote_tests.cpp
rosholger/Lispis
16eaa785580b5ea2b1ff5a0e0c6e9f006af9b1bd
[ "MIT" ]
3
2017-05-02T14:50:18.000Z
2020-04-22T08:11:31.000Z
tests/quasiquote_tests.cpp
rosholger/Lispis
16eaa785580b5ea2b1ff5a0e0c6e9f006af9b1bd
[ "MIT" ]
null
null
null
tests/quasiquote_tests.cpp
rosholger/Lispis
16eaa785580b5ea2b1ff5a0e0c6e9f006af9b1bd
[ "MIT" ]
null
null
null
#include "tests.h" TEST(quoteEqualQuasiquote) { TEST_SETUP; RUN_STR(q, s1, "'(a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923)))"); RUN_STR(qq, s2, "(quasiquote (a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923))))"); t_assert("quote equals quasiquote", deepEqual(q, qq) && s1 && s2); } TEST(quoteEqualQuasiquoteUnquote) { TEST_SETUP; RUN_STR(q, s1, "'(a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923)))"); RUN_STR(qq, s2, "(let! t '(23 + 8545 . a))" "(quasiquote (a b c 1 (unquote t)" "(((aksf ag) asd) . (asd 923))))"); t_assert("quote equals quasiquote", deepEqual(q, qq) && s1 && s2); } TEST(quoteEqualQuasiquoteUnquoteSplice) { TEST_SETUP; RUN_STR(q, s1, "'(asd sasd asd dass sasd ads asd " " a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923)))"); RUN_STR(qq, s2, "(let! t '(23 + 8545 . a))" "(let! t2 '((((aksf ag) asd) . (asd 923))))" "(quasiquote (asd sasd asd dass sasd ads asd " " a b c 1 (unquote t)" "(unquote-splice t2)))"); t_assert("quote equals quasiquote", deepEqual(q, qq) && s1 && s2); } // Thinks that define! is a function, that is a LARGE bug TEST(quasiquoteDefine) { TEST_SETUP; #if 1 RUN_STR(res, s, "(quasiquote (a (unquote (define! a 1))))" "a"); t_assert("unquoted define", unpackInt(res) == 1 && s); #else t_assert("unquoted define", false); #endif } TEST(quasiquoteNestingBasic) { TEST_SETUP; RUN_STR(res1, s1, "(let! a 1) ``,a"); RUN_STR(res2, s2, "`(quasiquote (unquote a))"); t_assert("basic quasiquote nesting", (s1 && s2 && deepEqual(res1, res2))); } TEST(quasiquoteNestingUnquote) { TEST_SETUP; RUN_STR(res1, s1, "(let! a 1) ``,,a"); RUN_STR(res2, s2, "`(quasiquote (unquote 1))"); t_assert("quasiquote unquote nesting", (s1 && s2 && deepEqual(res1, res2))); }
31.25
84
0.505412
rosholger
10b4fca646eb6b292a8c534f43c6ff103f639547
1,041
hpp
C++
SCLT/Shading/ShadingModelFactory.hpp
chicio/Multispectral-Ray-tracing
ea5b399770eddd1927aae8a8ae4640dead42c48c
[ "MIT" ]
95
2016-05-05T10:46:49.000Z
2021-12-20T12:51:41.000Z
SCLT/Shading/ShadingModelFactory.hpp
chicio/Multispectral-Ray-tracing
ea5b399770eddd1927aae8a8ae4640dead42c48c
[ "MIT" ]
1
2021-12-06T03:21:32.000Z
2021-12-06T03:21:32.000Z
SCLT/Shading/ShadingModelFactory.hpp
chicio/Multispectral-Ray-tracing
ea5b399770eddd1927aae8a8ae4640dead42c48c
[ "MIT" ]
8
2017-03-12T03:04:08.000Z
2022-03-17T01:27:41.000Z
// // ShadingModelFactory.hpp // Spectral Clara Lux tracer // // Created by Fabrizio Duroni on 14/11/15. // Copyright © 2015 Fabrizio Duroni. All rights reserved. // #ifndef ShadingModelFactory_hpp #define ShadingModelFactory_hpp #include "ShadingModel.hpp" #include "ShadingSpectrumModel.hpp" #include "ShadingRGBModel.hpp" #include "ShadingModelType.hpp" class ShadingModelFactory { public: /*! Generate the shading model to be used during rendering of the current scene. @param shadingModelType the type of shading model to be used. @returns a shading model. */ ShadingRGBModel* createShadingModelRGB(ShadingModelType shadingModelType); /*! Generate the shading model to be used during rendering of the current scene. @param shadingModelType the type of shading model to be used. @returns a shading model. */ ShadingSpectrumModel* createShadingModelSpectrum(ShadingModelType shadingModelType); }; #endif /* ShadingModelFactory_hpp */
24.785714
88
0.720461
chicio
10b8f89c528690f720871e29821ceb9ba01ef0c6
647
cpp
C++
array.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
array.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
array.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int size = 5; //Initialize array int Roll_Number[] = {100,101,102,103,104}; //print array for (int i = 0; i < size; i++){ //Access element at index i cout << Roll_Number[i] << " "; } cout << endl; // Update values of array element at index 3 and 4 Roll_Number[3] = 22222; Roll_Number[4] = 33333; cout << "Values of array after updation: " << endl; //Print updated values of array for (int i = 0; i < size; i++){ //Access elements of array at index i cout << Roll_Number[i] << " "; } cout << endl; }
23.962963
55
0.553323
gptakhil
10bb50ee8e00270ca2f8658dd55f8d5892e24df3
10,382
hh
C++
tce/src/applibs/LLVMBackend/TCETargetMachine.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/LLVMBackend/TCETargetMachine.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/LLVMBackend/TCETargetMachine.hh
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2015 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file TCETargetMachine.h * * Declaration of TCETargetMachine class. * * @author Veli-Pekka J��skel�inen 2007 (vjaaskel-no.spam-cs.tut.fi) * @author Mikael Lepist� 2009 (mikael.lepisto-no.spam-tut.fi) */ #ifndef TCE_TARGET_MACHINE_H #define TCE_TARGET_MACHINE_H #include <set> #include "tce_config.h" #include "CompilerWarnings.hh" IGNORE_COMPILER_WARNING("-Wunused-parameter") #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/CodeGen/SelectionDAGTargetInfo.h" #include "llvm/IR/PassManager.h" //#include "TCESubtarget.hh" #include "TCEStubTargetMachine.hh" #include "TCETargetMachinePlugin.hh" // tce_config.h defines these. this undef to avoid warning. // TODO: how to do this in tce_config.h??? #ifdef LLVM_LIBDIR #undef LLVM_LIBDIR #endif #include "llvm/CodeGen/Passes.h" #include "llvm/IR/DataLayout.h" #include "llvm/CodeGen/TargetPassConfig.h" POP_COMPILER_DIAGS namespace TTAMachine { class Machine; } class PipelineableLoopFinder; class PluginTools; // just to be able to manually register tce target if needed. extern "C" void LLVMInitializeTCETarget(); namespace llvm { class TCEPassConfig : public TargetPassConfig { public: TCEPassConfig( LLVMTargetMachine* tm, PassManagerBase& pm, TCETargetMachinePlugin* plugin) : TargetPassConfig(*tm, pm), plugin_(plugin) { assert(plugin_ != NULL); } virtual bool addPreISel(); virtual bool addInstSelector(); virtual void addPreRegAlloc(); virtual void addPreSched2(); TCETargetMachinePlugin* plugin_; }; class Module; /** * TCE Universal machine target description. */ class TCETargetMachine : public TCEBaseTargetMachine { public: TCETargetMachine( const Target &T, const Triple& TTriple, const llvm::StringRef& CPU, const llvm::StringRef& FS, const TargetOptions &Options, Optional<Reloc::Model> RM, Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool isLittle); virtual ~TCETargetMachine(); virtual void setTargetMachinePlugin( TCETargetMachinePlugin& plugin, TTAMachine::Machine& target); virtual TCETargetMachinePlugin& targetPlugin() const { return *plugin_; } /** * These two parameter passing should be rethought... maybe TTAMach can be avoided * by changing pass to use plugin_ instead. */ Module* emulationModule_; virtual void setEmulationModule(Module* mod) { emulationModule_ = mod; } virtual void setTTAMach( const TTAMachine::Machine* mach) override { TCEBaseTargetMachine::setTTAMach(mach); calculateSupportedImmediates(); } virtual const TTAMachine::Machine& ttaMachine() const { return *ttaMach_; } // This method is only in llvm < 3.7, but keep this here to // allow calling this ourselves. virtual const TCESubtarget* getSubtargetImpl() const { // compiler does not know it's derived without the plugin, // but this class cannow include the plugin. return reinterpret_cast<const TCESubtarget*>(plugin_->getSubtarget()); } virtual const TargetSubtargetInfo* getSubtargetImpl(const Function&) const override { return plugin_->getSubtarget(); } virtual const TargetInstrInfo* getInstrInfo() const { return plugin_->getInstrInfo(); } virtual const TargetRegisterInfo* getRegisterInfo() const { return plugin_->getRegisterInfo(); } virtual const DataLayout* getDataLayout() const { return plugin_->getDataLayout(); } virtual const TargetFrameLowering* getFrameLowering() const { return plugin_->getFrameLowering(); } virtual TargetLowering* getTargetLowering() const { return plugin_->getTargetLowering(); } virtual TargetPassConfig *createPassConfig( PassManagerBase &PM) override; std::string operationName(unsigned opc) const { return plugin_->operationName(opc); } /** * Returns true if LLVM opcode if valid for stack variable accesses. * */ bool validStackAccessOperation(const std::string& opName) const { return plugin_->validStackAccessOperation(opName); } bool hasOperation(TCEString operationName) const { return plugin_->hasOperation(operationName); } std::string rfName(unsigned dwarfRegNum) const { return plugin_->rfName(dwarfRegNum); } unsigned registerIndex(unsigned dwarfRegNum) const { return plugin_->registerIndex(dwarfRegNum); } /** * Returns full name of the register. * */ std::string registerName(unsigned dwarfRegNum) const { return rfName(dwarfRegNum) + "." + std::to_string(registerIndex(dwarfRegNum)); } unsigned llvmRegisterId(const TCEString& ttaRegister) { return plugin_->llvmRegisterId(ttaRegister); } TTAMachine::Machine* createMachine(); std::string dataASName() { return plugin_->dataASName(); } unsigned raPortDRegNum() const { return plugin_->raPortDRegNum(); } void loadPlugin(); unsigned spDRegNum() const { return plugin_->spDRegNum(); } unsigned opcode(TCEString operationName) const { return plugin_->opcode(operationName); } int getMinOpcode(llvm::SDNode* n) { return plugin_->getMinOpcode(n); } int getMinuOpcode(llvm::SDNode* n) { return plugin_->getMinuOpcode(n); } int getMaxOpcode(llvm::SDNode* n) { return plugin_->getMaxOpcode(n); } int getMaxuOpcode(llvm::SDNode* n) { return plugin_->getMaxuOpcode(n); } int getAddOpcode(const llvm::EVT& vt) const { return plugin_->getAddOpcode(vt); } int getShlOpcode(const llvm::EVT& vt) const { return plugin_->getShlOpcode(vt); } int getIorOpcode(const llvm::EVT& vt) const { return plugin_->getIorOpcode(vt); } void setStackAlignment(unsigned align) { stackAlignment_ = align; } unsigned stackAlignment() const { if (stackAlignment_ == 0) { std::cerr << "ZERO STACK ALIGN\n"; abort(); } assert(stackAlignment_ > 0); return stackAlignment_; } bool has8bitLoads() const { return plugin_->has8bitLoads(); } bool has16bitLoads() const { return plugin_->has16bitLoads(); } int bitness() const { return plugin_->is64bit() ? 64 : 32; } const std::set< std::pair<unsigned, llvm::MVT::SimpleValueType> >* missingOperations(); const std::set< std::pair<unsigned, llvm::MVT::SimpleValueType> >* promotedOperations(); const std::set< std::pair<unsigned, llvm::MVT::SimpleValueType> >* customLegalizedOperations(); int64_t smallestImmValue() const { assert(ttaMach_ && "setTargetMachinePlugin() was not called"); return smallestImm_; } uint64_t largestImmValue() const { assert(ttaMach_ && "setTargetMachinePlugin() was not called"); return largestImm_; } bool canEncodeAsMOVI(const llvm::MVT& vt, int64_t val) const; bool canEncodeAsMOVF(const llvm::APFloat& fp) const; bool canMaterializeConstant(const ConstantInt& ci) const { return plugin_->canMaterializeConstant(ci); } int getLoadOpcode(int asid, int align, const llvm::EVT& vt) const; private: /* more or less llvm naming convention to make it easier to track llvm changes */ TCETargetMachinePlugin* plugin_; PluginTools* pluginTool_; /// llvm::ISD opcode list of operations that have to be expanded. std::set<std::pair<unsigned, llvm::MVT::SimpleValueType> > missingOps_; std::set<std::pair<unsigned, llvm::MVT::SimpleValueType> > promotedOps_; std::set<std::pair<unsigned, llvm::MVT::SimpleValueType> > customLegalizedOps_; void calculateSupportedImmediates(); int64_t smallestImm_ = std::numeric_limits<int64_t>::max(); uint64_t largestImm_ = std::numeric_limits<int64_t>::min(); int SupportedFPImmWidth_ = std::numeric_limits<int>::min(); // The stack alignment. Note: this should be overridden per // generated Module if the Module requires a larger one. unsigned stackAlignment_; }; } #endif
30.89881
93
0.633115
kanishkan
10bd4ffae98d8423d847bcb6d83ad774bbf2ea9f
312
cpp
C++
src/StraightEnemyMove.cpp
yubeneko/Shooting_2D
614476bd9fec654535e05e349b122d076ccd76e5
[ "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
1
2022-03-18T08:16:22.000Z
2022-03-18T08:16:22.000Z
src/StraightEnemyMove.cpp
yubeneko/Shooting_2D
614476bd9fec654535e05e349b122d076ccd76e5
[ "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
src/StraightEnemyMove.cpp
yubeneko/Shooting_2D
614476bd9fec654535e05e349b122d076ccd76e5
[ "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
#include "StraightEnemyMove.h" #include "Actor.h" StraightEnemyMove::StraightEnemyMove(Actor* owner, int updateOrder) : Component(owner, updateOrder) { } void StraightEnemyMove::Update(float deltaTime) { glm::vec2 pos = mOwner->GetPosition(); pos.x += mRightSpeed * deltaTime; mOwner->SetPosition(pos); }
20.8
67
0.746795
yubeneko
10c02db4da7fc8e72d6418b0011ea020609ab931
2,025
cpp
C++
contrib/C++/id3lib/source/globals.cpp
finnianr/Eiffel-Loop-safe
ee2fb9e3f6329c1faf2716ebfc53dc4e53fad80f
[ "MIT" ]
1
2019-09-28T16:03:45.000Z
2019-09-28T16:03:45.000Z
contrib/C++/id3lib/source/globals.cpp
finnianr/Eiffel-Loop-safe
ee2fb9e3f6329c1faf2716ebfc53dc4e53fad80f
[ "MIT" ]
1
2019-09-28T16:07:48.000Z
2019-09-28T16:07:48.000Z
contrib/C++/id3lib/source/globals.cpp
finnianr/Eiffel-Loop-safe
ee2fb9e3f6329c1faf2716ebfc53dc4e53fad80f
[ "MIT" ]
null
null
null
// $Id: globals.cpp,v 1.6 2002/07/02 22:12:57 t1mpy Exp $ // id3lib: a C++ library for creating and manipulating id3v1/v2 tags // Copyright 1999, 2000 Scott Thomas Haug // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published by // the Free Software Foundation; either version 2 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public // License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // The id3lib authors encourage improvements and optimisations to be sent to // the id3lib coordinator. Please see the README file for details on where to // send such submissions. See the AUTHORS file for a list of people who have // contributed to id3lib. See the ChangeLog file for a list of changes to // id3lib. These files are distributed with id3lib at // http://download.sourceforge.net/id3lib/ #include "id3/globals.h" //has <stdlib.h> "id3/sized_types.h" #if defined HAVE_CONFIG_H #include <config.h> #endif #ifdef _cplusplus extern "C" { #endif const char * const ID3LIB_NAME = _ID3LIB_NAME; const char * const ID3LIB_VERSION = _ID3LIB_VERSION; const char * const ID3LIB_FULL_NAME = _ID3LIB_FULLNAME; const int ID3LIB_MAJOR_VERSION = _ID3LIB_MAJOR_VERSION; const int ID3LIB_MINOR_VERSION = _ID3LIB_MINOR_VERSION; const int ID3LIB_PATCH_VERSION = _ID3LIB_PATCH_VERSION; const int ID3LIB_INTERFACE_AGE = _ID3LIB_INTERFACE_AGE; const int ID3LIB_BINARY_AGE = _ID3LIB_BINARY_AGE; #ifdef _cplusplus } #endif
39.705882
78
0.735802
finnianr
10c861988c00f5e1a4b9532490e526741b81559b
1,043
cpp
C++
external_codes/mpi_wrapper/mpi3/exercise/03-isend.cpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
14
2020-12-22T21:20:10.000Z
2022-03-15T21:27:51.000Z
external_codes/mpi_wrapper/mpi3/exercise/03-isend.cpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
11
2020-05-09T20:57:21.000Z
2020-06-10T00:00:17.000Z
external_codes/mpi_wrapper/mpi3/exercise/03-isend.cpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
null
null
null
#if COMPILATION_INSTRUCTIONS mpicxx -O3 -std=c++17 -Wfatal-errors $0 -o $0x.x && time mpirun -np 4 $0x.x $@ && rm -f $0x.x; exit #endif #include "alf/boost/mpi3/main.hpp" #include "alf/boost/mpi3/version.hpp" #include<iostream> namespace mpi3 = boost::mpi3; using std::cout; int mpi3::main(int argc, char* argv[], mpi3::communicator& world){ if(world.size() % 2 != 0){ if(world.root()) cout << "Quitting. Need an even number of tasks: numtasks = " << world.size() << "\n"; return 1; } int message = -1; cout << "Hello from task " << world.rank() << " on host " << mpi3::processor_name() << "\n"; if(world.root()) cout << "MASTER: number of mpi tasks is " << world.size() << "\n"; int partner = world.rank()<world.size()/2?world.rank() + world.size()/2:world.rank()-world.size()/2; auto r1 = world.ireceive_value(message, partner, 1); auto r2 = world.isend_value(world.rank(), partner, 1); // r1.wait(); // r2.wait(); mpi3::wait(r1, r2); cout << "Task " << world.rank() << " is partner with " << message << std::endl; }
29.8
105
0.621285
djstaros
10c8eec391aeb73be4da1128f631c31763b58841
2,154
cpp
C++
Official Windows Platform Sample/Windows 8.1 desktop samples/[C++]-Windows 8.1 desktop samples/Input Method Editor (IME) sample/C++/SampleIME/DisplayAttributeProvider.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/IME/cpp/SampleIME/DisplayAttributeProvider.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Samples/IME/cpp/SampleIME/DisplayAttributeProvider.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "Private.h" #include "globals.h" #include "SampleIME.h" #include "DisplayAttributeInfo.h" #include "EnumDisplayAttributeInfo.h" //+--------------------------------------------------------------------------- // // ITfDisplayAttributeProvider::EnumDisplayAttributeInfo // //---------------------------------------------------------------------------- STDAPI CSampleIME::EnumDisplayAttributeInfo(__RPC__deref_out_opt IEnumTfDisplayAttributeInfo **ppEnum) { CEnumDisplayAttributeInfo* pAttributeEnum = nullptr; if (ppEnum == nullptr) { return E_INVALIDARG; } *ppEnum = nullptr; pAttributeEnum = new (std::nothrow) CEnumDisplayAttributeInfo(); if (pAttributeEnum == nullptr) { return E_OUTOFMEMORY; } *ppEnum = pAttributeEnum; return S_OK; } //+--------------------------------------------------------------------------- // // ITfDisplayAttributeProvider::GetDisplayAttributeInfo // //---------------------------------------------------------------------------- STDAPI CSampleIME::GetDisplayAttributeInfo(__RPC__in REFGUID guidInfo, __RPC__deref_out_opt ITfDisplayAttributeInfo **ppInfo) { if (ppInfo == nullptr) { return E_INVALIDARG; } *ppInfo = nullptr; // Which display attribute GUID? if (IsEqualGUID(guidInfo, Global::SampleIMEGuidDisplayAttributeInput)) { *ppInfo = new (std::nothrow) CDisplayAttributeInfoInput(); if ((*ppInfo) == nullptr) { return E_OUTOFMEMORY; } } else if (IsEqualGUID(guidInfo, Global::SampleIMEGuidDisplayAttributeConverted)) { *ppInfo = new (std::nothrow) CDisplayAttributeInfoConverted(); if ((*ppInfo) == nullptr) { return E_OUTOFMEMORY; } } else { return E_INVALIDARG; } return S_OK; }
26.268293
125
0.579851
zzgchina888
10c9bbf2a00f59dc3739a171357a9ac3b6af25c7
136
cpp
C++
cppcode/cpp execise/day02/main.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day02/main.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day02/main.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; extern "C" int add (int, int); int main (void) { cout << add (123, 456) << endl; return 0; }
17
32
0.632353
jiedou
10cd39e2858d32895cc14235b47b86e80c1a8562
3,283
cc
C++
cassandra/src/model/DescribeNodeToolExecutionHistoryResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
cassandra/src/model/DescribeNodeToolExecutionHistoryResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
cassandra/src/model/DescribeNodeToolExecutionHistoryResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cassandra/model/DescribeNodeToolExecutionHistoryResult.h> #include <json/json.h> using namespace AlibabaCloud::Cassandra; using namespace AlibabaCloud::Cassandra::Model; DescribeNodeToolExecutionHistoryResult::DescribeNodeToolExecutionHistoryResult() : ServiceResult() {} DescribeNodeToolExecutionHistoryResult::DescribeNodeToolExecutionHistoryResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeNodeToolExecutionHistoryResult::~DescribeNodeToolExecutionHistoryResult() {} void DescribeNodeToolExecutionHistoryResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["JobId"].isNull()) jobId_ = value["JobId"].asString(); if(!value["Command"].isNull()) command_ = value["Command"].asString(); if(!value["Nodes"].isNull()) nodes_ = value["Nodes"].asString(); if(!value["ModifyTime"].isNull()) modifyTime_ = std::stol(value["ModifyTime"].asString()); if(!value["CreateTime"].isNull()) createTime_ = std::stol(value["CreateTime"].asString()); if(!value["RegionId"].isNull()) regionId_ = value["RegionId"].asString(); if(!value["IsEnded"].isNull()) isEnded_ = value["IsEnded"].asString() == "true"; if(!value["Arguments"].isNull()) arguments_ = value["Arguments"].asString(); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); if(!value["DataCenterId"].isNull()) dataCenterId_ = value["DataCenterId"].asString(); if(!value["Result"].isNull()) result_ = value["Result"].asString(); } long DescribeNodeToolExecutionHistoryResult::getModifyTime()const { return modifyTime_; } std::string DescribeNodeToolExecutionHistoryResult::getDataCenterId()const { return dataCenterId_; } bool DescribeNodeToolExecutionHistoryResult::getIsEnded()const { return isEnded_; } std::string DescribeNodeToolExecutionHistoryResult::getCommand()const { return command_; } long DescribeNodeToolExecutionHistoryResult::getCreateTime()const { return createTime_; } std::string DescribeNodeToolExecutionHistoryResult::getArguments()const { return arguments_; } std::string DescribeNodeToolExecutionHistoryResult::getRegionId()const { return regionId_; } std::string DescribeNodeToolExecutionHistoryResult::getErrorMessage()const { return errorMessage_; } std::string DescribeNodeToolExecutionHistoryResult::getJobId()const { return jobId_; } std::string DescribeNodeToolExecutionHistoryResult::getNodes()const { return nodes_; } std::string DescribeNodeToolExecutionHistoryResult::getResult()const { return result_; }
26.909836
108
0.762717
iamzken
10cedd7e2501814e0a6470110e97c6e2f2154d6f
547
cpp
C++
Example/Network/Http/Http/ConnectionMgr.cpp
chenyu2202863/iocpframework
292fbf820af0d96b1d3be18d3616dce3e421f9c2
[ "FSFAP" ]
51
2015-01-28T08:50:43.000Z
2022-02-28T02:31:47.000Z
Example/Network/Http/Http/ConnectionMgr.cpp
lvyong1943/iocpframework
292fbf820af0d96b1d3be18d3616dce3e421f9c2
[ "FSFAP" ]
1
2016-09-26T06:38:44.000Z
2016-10-16T11:42:02.000Z
Example/Network/Http/Http/ConnectionMgr.cpp
lvyong1943/iocpframework
292fbf820af0d96b1d3be18d3616dce3e421f9c2
[ "FSFAP" ]
52
2015-01-10T08:28:52.000Z
2021-10-30T12:10:23.000Z
#include "stdafx.h" #include "ConnectionMgr.h" namespace http { void ConnectionMgr::Start(const ConnectionPtr &c) { { AutoLock lock(lock_); connections_.insert(c); } c->Start(); } void ConnectionMgr::Stop(const ConnectionPtr &c) { { AutoLock lock(lock_); connections_.erase(c); } c->Stop(); } void ConnectionMgr::StopAll() { std::for_each(connections_.begin(), connections_.end(), std::tr1::bind(&Connection::Stop, std::placeholders::_1)); { AutoLock lock(lock_); connections_.clear(); } } }
14.394737
61
0.645338
chenyu2202863
10d1ddad473fde2bd771fc1330ddfca1c0ca4e72
3,636
cc
C++
chrome/browser/chromeos/kerberos/kerberos_credentials_manager_factory.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/kerberos/kerberos_credentials_manager_factory.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/kerberos/kerberos_credentials_manager_factory.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/kerberos/kerberos_credentials_manager_factory.h" #include <memory> #include <utility> #include "base/memory/singleton.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" namespace chromeos { namespace { Profile* GetPrimaryProfileFromContext(content::BrowserContext* context) { if (!user_manager::UserManager::IsInitialized()) return nullptr; // Get original profile, so it gets primary profile faster if context is // incognito profile. Profile* profile = Profile::FromBrowserContext(context)->GetOriginalProfile(); if (!ProfileHelper::IsPrimaryProfile(profile)) { const auto* primary_user = user_manager::UserManager::Get()->GetPrimaryUser(); if (!primary_user) return nullptr; // Get primary profile from primary user. Note that it only gets primary // profile if it is fully created. profile = chromeos::ProfileHelper::Get()->GetProfileByUser(primary_user); } return profile; } } // namespace // static KerberosCredentialsManager* KerberosCredentialsManagerFactory::GetExisting( content::BrowserContext* context) { Profile* const primary_profile = GetPrimaryProfileFromContext(context); if (!primary_profile) return nullptr; return static_cast<KerberosCredentialsManager*>( GetInstance()->GetServiceForBrowserContext(primary_profile, false)); } // static KerberosCredentialsManager* KerberosCredentialsManagerFactory::Get( content::BrowserContext* context) { Profile* const primary_profile = GetPrimaryProfileFromContext(context); if (!primary_profile) return nullptr; return static_cast<KerberosCredentialsManager*>( GetInstance()->GetServiceForBrowserContext(primary_profile, true)); } // static KerberosCredentialsManagerFactory* KerberosCredentialsManagerFactory::GetInstance() { return base::Singleton<KerberosCredentialsManagerFactory>::get(); } KerberosCredentialsManagerFactory::KerberosCredentialsManagerFactory() : BrowserContextKeyedServiceFactory( "KerberosCredentialsManager", BrowserContextDependencyManager::GetInstance()), service_instance_created_(false) {} KerberosCredentialsManagerFactory::~KerberosCredentialsManagerFactory() = default; bool KerberosCredentialsManagerFactory::ServiceIsCreatedWithBrowserContext() const { return true; } KeyedService* KerberosCredentialsManagerFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* const profile = Profile::FromBrowserContext(context); // Verify that UserManager is initialized before calling IsPrimaryProfile. if (!user_manager::UserManager::IsInitialized()) return nullptr; // Verify that we create instance for a primary profile. if (!ProfileHelper::IsPrimaryProfile(profile)) return nullptr; // Verify that this is not a testing profile. if (profile->AsTestingProfile()) return nullptr; // Make sure one and only one instance is ever created. if (service_instance_created_) return nullptr; service_instance_created_ = true; PrefService* local_state = g_browser_process->local_state(); return new KerberosCredentialsManager(local_state, profile); } } // namespace chromeos
33.981308
82
0.775853
sarang-apps
10d25ff719079320b47be0257d94630865ff17dd
3,652
cpp
C++
src/Date.cpp
aymanexpo/Date
94863151cab43148b8770ae258ff351af2de195e
[ "MIT" ]
null
null
null
src/Date.cpp
aymanexpo/Date
94863151cab43148b8770ae258ff351af2de195e
[ "MIT" ]
null
null
null
src/Date.cpp
aymanexpo/Date
94863151cab43148b8770ae258ff351af2de195e
[ "MIT" ]
null
null
null
#include "Date.h" #include <iostream> using namespace std; Date::Date() { this->d_ = 1; this->m_ = 1; this->y_ = 1970; } Date::Date(const Date &date) { this->d_ = date.d_; this->m_ = date.m_; this->y_ = date.y_; } Date::Date(int y, int m, int d) { if (y%400==0) { if(m==2&&(d>29||d<1)){ cerr << "*** Erreur : " << d_ << "/" << m_ << "/ " << y_ << " date fausse" << endl; } else if(((m==1||m==3||m==5||m==7||m==8||m==10||m==12)&&(d<0||d>31))) { cerr << "*** Erreur : " << d_ << "/" << m_ << "/ " << y_ << " date fausse" << endl; } else if (((m == 4 || m == 6 || m ==9 || m == 11) && (d < 0 || d>30))) { cerr << "*** Erreur : " << d_ << "/" << m_ << "/ " << y_ << " date fausse" << endl; } } else if (y%400 != 0) { if (m == 2 && (d > 28 || d < 1)) { cerr << "*** Erreur : " << d_ << "/" << m_ << "/ " << y_ << " date fausse" << endl; } else if (((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) && (d < 0 || d>31))) { cerr << "*** Erreur : " << d_ << "/" << m_ << "/ " << y_ << " date fausse" << endl; } else if (((m == 4 || m == 6 || m == 9 || m == 11) && (d < 0 || d>30))) { cerr << "*** Erreur : " << d_ << "/" << m_ << "/ " << y_ << " date fausse" << endl; } } else { this->d_ = d; this->m_ = m; this->y_ = y; } } Date::~Date() { } Date &Date::decr() { if (this->d_ > 1) { this->d_ -= 1; } else if (this->d_ == 1) { if (this->m_ == 3 && this->y_ % 400 == 0) { this->d_ = 29; this->m_ -= 1; } else if (this->m_ == 3 && this->y_ % 400 != 0) { this->d_ = 28; this->m_ -= 1; } else { if (this->m_ == 1) { this->d_ = 31; this->m_ = 12; this->y_ -= 1; } else if (this->m_ == 5 || this->m_ == 7 || this->m_ == 10 || this->m_ == 12) { this->d_ = 30; this->m_ -= 1; } else if (this->m_ == 2 || this->m_ == 4 || this->m_ == 8 || this->m_ == 9 || this->m_ == 11) { this->d_ = 31; this->m_ -= 1; } } } return *this; } Date &Date::incr() { if (this->d_ == 31 && (this->m_ == 1 || this->m_ == 3 || this->m_ == 5 || this->m_ == 7 || this->m_ == 8 || this->m_ == 10 || this->m_ == 12)) { if (this->m_ == 12) { this->d_ = 1; this->m_ = 1; this->y_ += 1; } else{ this->d_ = 1; this->m_ += 1; } } else if (this->d_ == 30 && (this->m_ == 4 || this->m_ == 6 || this->m_ == 9 || this->m_ == 11)) { this->d_ = 1; this->m_ += 1; } else if (this->m_ == 2 && this->y_ % 400 == 0 && this->d_ == 29) { this->d_ = 1; this->m_ += 1; } else if (this->m_ == 2 && this->y_ % 400 != 0 && this->d_ == 28) { this->d_ = 1; this->m_ += 1; } else { this->d_ += 1; } return *this; } void Date::print() { if (this->d_<10) { if (this->m_ < 10){ std::cout << "0" << this->d_ << "/" << "0" << this->m_ << "/" << this->y_ << endl; } else { std::cout << "0" << this->d_ << "/" << this->m_ << "/" << this->y_ << endl; } } else { std::cout << this->d_ << "/" << this->m_ << "/" << this->y_ << endl; } }
27.666667
148
0.324206
aymanexpo
10d4060ff81c8fe4932b765600f9bb22f9bb92db
41,288
cpp
C++
agent/browser/ie/pagetest/TestState.cpp
LeeLiangze/web_test
50ce21afb153b105569e31ef08ddc098743208e5
[ "IJG" ]
null
null
null
agent/browser/ie/pagetest/TestState.cpp
LeeLiangze/web_test
50ce21afb153b105569e31ef08ddc098743208e5
[ "IJG" ]
null
null
null
agent/browser/ie/pagetest/TestState.cpp
LeeLiangze/web_test
50ce21afb153b105569e31ef08ddc098743208e5
[ "IJG" ]
null
null
null
/* Copyright (c) 2005-2007, AOL, LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the company 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 "StdAfx.h" #include "TestState.h" #include <atlutil.h> #include <Mmsystem.h> #include "Psapi.h" CTestState::CTestState(void): hTimer(0) ,lastBytes(0) ,lastCpuIdle(0) ,lastCpuKernel(0) ,lastCpuUser(0) ,lastTime(0) ,imageCount(0) ,lastImageTime(0) ,lastRealTime(0) ,cacheCleared(false) ,heartbeatEvent(NULL) { // Load the ad regular expressions from disk. LoadAdPatterns(); } CTestState::~CTestState(void) { if( heartbeatEvent ) CloseHandle(heartbeatEvent); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CTestState::Reset(void) { __super::Reset(); EnterCriticalSection(&cs); currentState = READYSTATE_UNINITIALIZED; painted = false; SetBrowserWindowUpdated(true); LeaveCriticalSection(&cs); } /*----------------------------------------------------------------------------- Do all of the startup checks and evaluations -----------------------------------------------------------------------------*/ void CTestState::DoStartup(CString& szUrl, bool initializeDoc) { USES_CONVERSION; CString msg; if( !active && available ) { msg.Format(_T("[Pagetest] *** DoStartup() - '%s'\n"), (LPCTSTR)szUrl); OutputDebugString(msg); bool ok = true; CheckABM(); domElementId.Empty(); domRequest.Empty(); domRequestType = END; endRequest.Empty(); if( interactive ) { checkOpt = true; if( runningScript ) { CString szEventName = szUrl; // default this to the url for right now if( !script_eventName.IsEmpty() ) szEventName = script_eventName; domElementId = script_domElement; domRequest = script_domRequest; domRequestType = script_domRequestType; endRequest = script_endRequest; if( script_timeout != -1 ) timeout = script_timeout; if( script_activity_timeout ) activityTimeout = script_activity_timeout; if( !szEventName.IsEmpty() && szEventName == somEventName ) ok = false; else somEventName = szEventName; } } else { // load the automation settings from the registry CRegKey key; if( key.Open(HKEY_CURRENT_USER, _T("Software\\America Online\\SOM"), KEY_READ | KEY_WRITE) == ERROR_SUCCESS ) { CString szEventName = szUrl; // default this to the url for right now TCHAR buff[100000]; ULONG len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("EventName"), buff, &len) == ERROR_SUCCESS ) szEventName = buff; if( runningScript ) { if( script_active ) { if( !script_eventName.IsEmpty() ) { if( szEventName.IsEmpty() ) szEventName = script_eventName; else { if( !szEventName.Replace(_T("%STEP%"), (LPCTSTR)script_eventName) ) szEventName += CString(_T("_")) + script_eventName; } } domElementId = script_domElement; domRequest = script_domRequest; domRequestType = script_domRequestType; endRequest = script_endRequest; } else ok = false; } else { len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("DOM Element ID"), buff, &len) == ERROR_SUCCESS ) if( lstrlen(buff) ) domElementId = buff; key.DeleteValue(_T("DOM Element ID")); } len = sizeof(buff) / sizeof(TCHAR); logFile.Empty(); if( key.QueryStringValue(_T("IEWatchLog"), buff, &len) == ERROR_SUCCESS ) logFile = buff; len = sizeof(buff) / sizeof(TCHAR); linksFile.Empty(); if( key.QueryStringValue(_T("Links File"), buff, &len) == ERROR_SUCCESS ) linksFile = buff; key.DeleteValue(_T("Links File")); len = sizeof(buff) / sizeof(TCHAR); s404File.Empty(); if( key.QueryStringValue(_T("404 File"), buff, &len) == ERROR_SUCCESS ) s404File = buff; key.DeleteValue(_T("404 File")); len = sizeof(buff) / sizeof(TCHAR); htmlFile.Empty(); if( key.QueryStringValue(_T("HTML File"), buff, &len) == ERROR_SUCCESS ) htmlFile = buff; key.DeleteValue(_T("HTML File")); len = sizeof(buff) / sizeof(TCHAR); cookiesFile.Empty(); if( key.QueryStringValue(_T("Cookies File"), buff, &len) == ERROR_SUCCESS ) cookiesFile = buff; key.DeleteValue(_T("Cookies File")); // if we're running a script, the block list will come from the script if( !runningScript ) { len = sizeof(buff) / sizeof(TCHAR); blockRequests.RemoveAll(); if( key.QueryStringValue(_T("Block"), buff, &len) == ERROR_SUCCESS ) { CString block = buff; int pos = 0; CString token = block.Tokenize(_T(" "), pos); while( pos >= 0 ) { token.Trim(); blockRequests.AddTail(token); token = block.Tokenize(_T(" "), pos); } } key.DeleteValue(_T("Block")); } len = sizeof(buff) / sizeof(TCHAR); basicAuth.Empty(); if( key.QueryStringValue(_T("Basic Auth"), buff, &len) == ERROR_SUCCESS ) { basicAuth = buff; script_basicAuth = buff; } key.DeleteValue(_T("Basic Auth")); if( ok ) { if( runningScript ) logUrl[0]=0; else { len = _countof(logUrl); key.QueryStringValue(_T("URL"), logUrl, &len); } key.QueryDWORDValue(_T("Cached"), cached); includeObjectData = 1; key.QueryDWORDValue(_T("Include Object Data"), includeObjectData); saveEverything = 0; key.QueryDWORDValue(_T("Save Everything"), saveEverything); captureVideo = 0; key.QueryDWORDValue(_T("Capture Video"), captureVideo); checkOpt = 1; key.QueryDWORDValue(_T("Check Optimizations"), checkOpt); ignoreSSL = 0; key.QueryDWORDValue(_T("ignoreSSL"), ignoreSSL); blockads = 0; key.QueryDWORDValue(_T("blockads"), blockads); pngScreenShot = 0; key.QueryDWORDValue(_T("pngScreenShot"), pngScreenShot); imageQuality = JPEG_DEFAULT_QUALITY; key.QueryDWORDValue(_T("imageQuality"), imageQuality); imageQuality = max(JPEG_DEFAULT_QUALITY, min(100, imageQuality)); bodies = 0; key.QueryDWORDValue(_T("bodies"), bodies); htmlbody = 0; key.QueryDWORDValue(_T("htmlbody"), htmlbody); keepua = 0; key.QueryDWORDValue(_T("keepua"), keepua); minimumDuration = 0; key.QueryDWORDValue(_T("minimumDuration"), minimumDuration); clearShortTermCacheSecs = 0; key.QueryDWORDValue(_T("clearShortTermCacheSecs"), clearShortTermCacheSecs); noHeaders = 0; key.QueryDWORDValue(_T("No Headers"), noHeaders); noImages = 0; key.QueryDWORDValue(_T("No Images"), noImages); len = sizeof(buff) / sizeof(TCHAR); customHost.Empty(); if( key.QueryStringValue(_T("Host"), buff, &len) == ERROR_SUCCESS ) customHost = buff; if( !heartbeatEvent ) { len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("Heartbeat Event"), buff, &len) == ERROR_SUCCESS ) heartbeatEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, buff); } if( heartbeatEvent ) SetEvent(heartbeatEvent); if( !runningScript ) { len = _countof(descriptor); key.QueryStringValue(_T("Descriptor"), descriptor, &len); // delete values that shouldn't be re-used key.DeleteValue(_T("Descriptor")); key.DeleteValue(_T("URL")); key.DeleteValue(_T("Cached")); key.DeleteValue(_T("Save Everything")); key.DeleteValue(_T("ignoreSSL")); key.DeleteValue(_T("Host")); } len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("customRules"), buff, &len) == ERROR_SUCCESS && len > 1 ) { CString rules = buff; int pos = 0; CString rule = rules.Tokenize(_T("\n"), pos); while (pos >= 0) { rule = rule.Trim(); if (rule.GetLength()) { int separator = rule.Find(_T('=')); if (separator > 0) { CString name = rule.Left(separator).Trim(); rule = rule.Mid(separator + 1).Trim(); int separator = rule.Find(_T('\t')); if (separator > 0) { CString mime = rule.Left(separator).Trim(); rule = rule.Mid(separator + 1).Trim(); if (name.GetLength() && mime.GetLength() && rule.GetLength()) { CCustomRule newrule; newrule.name = name; newrule.mime = mime; newrule.regex = rule; customRules.AddTail(newrule); } } } } rule = rules.Tokenize(_T("\n"), pos); } } customMetrics.RemoveAll(); len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("customMetricsFile"), buff, &len) == ERROR_SUCCESS && len > 1 ) { HANDLE hFile = CreateFile(buff, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (hFile != INVALID_HANDLE_VALUE) { DWORD custom_len = GetFileSize(hFile, NULL); if (custom_len) { char * custom_metrics = (char *)malloc(custom_len + 1); char * decoded = (char *)malloc(custom_len + 1); if (custom_metrics && decoded) { custom_metrics[custom_len] = 0; DWORD bytes = 0; if (ReadFile(hFile, custom_metrics, custom_len, &bytes, 0) && bytes == custom_len) { char * line = strtok(custom_metrics, "\r\n"); while (line) { CStringA metric_line(line); int divider = metric_line.Find(":"); if (divider > 0) { CCustomMetric metric; metric.name = (LPCTSTR)CA2T((LPCSTR)metric_line.Left(divider)); CStringA code = metric_line.Mid(divider + 1); int nDestLen = custom_len; if (Base64Decode((LPCSTR)code, code.GetLength(), (BYTE*)decoded, &nDestLen) && nDestLen) { decoded[nDestLen] = 0; metric.code = (LPCTSTR)CA2T(decoded); customMetrics.AddTail(metric); } } line = strtok(NULL, "\r\n"); } } free(decoded); free(custom_metrics); } } CloseHandle(hFile); } } key.DeleteValue(_T("Basic Auth")); // make sure the event name has changed // this is to prevent a page with navigate script on it // from adding test entries to the log file if( !szEventName.IsEmpty() && szEventName == somEventName ) { msg.Format(_T("[Pagetest] *** Ingoring event, event name has not changed - '%s'\n"), (LPCTSTR)somEventName); OutputDebugString(msg); ok = false; } else somEventName = szEventName; } key.Close(); } else ok = false; // load iewatch settings if( ok ) { if( script_activity_timeout ) activityTimeout = script_activity_timeout; if( key.Open(HKEY_CURRENT_USER, _T("SOFTWARE\\AOL\\ieWatch"), KEY_READ) == ERROR_SUCCESS ) { if( runningScript && script_timeout != -1 ) timeout = script_timeout; else key.QueryDWORDValue(_T("Timeout"), timeout); key.Close(); } if( key.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\AOL\\ieWatch"), KEY_READ) == ERROR_SUCCESS ) { key.QueryDWORDValue(_T("Include Header"), includeHeader); key.Close(); } } #ifdef _DEBUG timeout = timeout * 10; #endif } // Delete short lifetime cache elements if configured (Blaze patch) // TODO: replace this with proper cache aging if we can figure out how to do it if( ok && cached && clearShortTermCacheSecs > 0 ) ClearShortTermCache(clearShortTermCacheSecs); // clear the cache if necessary (extra precaution) if( ok && !cached && !cacheCleared ) { HANDLE hEntry; DWORD len, entry_size = 0; GROUPID id; INTERNET_CACHE_ENTRY_INFO * info = NULL; HANDLE hGroup = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, 0, 0, &id, 0); if (hGroup) { do { len = entry_size; hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, id, info, &len, NULL, NULL, NULL); if (!hEntry && GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, id, info, &len, NULL, NULL, NULL); } } if (hEntry && info) { bool ok = true; do { DeleteUrlCacheEntry(info->lpszSourceUrlName); len = entry_size; if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { ok = false; } } } else { ok = false; } } } while (ok); } if (hEntry) { FindCloseUrlCache(hEntry); } DeleteUrlCacheGroup(id, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, 0); } while(FindNextUrlCacheGroup(hGroup, &id,0)); FindCloseUrlCache(hGroup); } len = entry_size; hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, 0, info, &len, NULL, NULL, NULL); if (!hEntry && GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, 0, info, &len, NULL, NULL, NULL); } } if (hEntry && info) { bool ok = true; do { DeleteUrlCacheEntry(info->lpszSourceUrlName); len = entry_size; if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { ok = false; } } } else { ok = false; } } } while (ok); } if (hEntry) { FindCloseUrlCache(hEntry); } len = entry_size; hEntry = FindFirstUrlCacheEntry(NULL, info, &len); if (!hEntry && GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { hEntry = FindFirstUrlCacheEntry(NULL, info, &len); } } if (hEntry && info) { bool ok = true; do { DeleteUrlCacheEntry(info->lpszSourceUrlName); len = entry_size; if (!FindNextUrlCacheEntry(hEntry, info, &len)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { if (!FindNextUrlCacheEntry(hEntry, info, &len)) { ok = false; } } } else { ok = false; } } } while (ok); } if (hEntry) { FindCloseUrlCache(hEntry); } if (info) free(info); cacheCleared = true; } if( ok ) { // check for any machine-wide overrides CRegKey keyMachine; if( keyMachine.Open(HKEY_LOCAL_MACHINE, _T("Software\\America Online\\Pagetest"), KEY_READ) == ERROR_SUCCESS ) { DWORD val = checkOpt; if( ERROR_SUCCESS == keyMachine.QueryDWORDValue(_T("Check Optimizations"), val) ) checkOpt = val; keyMachine.Close(); } // parse any test options that came in on the url ParseTestOptions(); msg.Format(_T("[Pagetest] *** DoStartup() - Starting measurement - '%s'\n"), (LPCTSTR)somEventName); OutputDebugString(msg); // create the dialog if we need to Create(); // delete any old data Reset(); // track the document that everything belongs to if( initializeDoc ) { EnterCriticalSection(&cs); currentDoc = nextDoc; nextDoc++; LeaveCriticalSection(&cs); } EnterCriticalSection(&cs); active = true; available = false; reportSt = NONE; // collect the starting TCP stats GetTcpStatistics(&tcpStatsStart); // keep the activity tracking up to date QueryPerfCounter(lastRequest); lastActivity = lastRequest; startTime = CTime::GetCurrentTime(); url = szUrl; GetCPUTime(startCPU, startCPUtotal); LeaveCriticalSection(&cs); StartTimer(1, 100); } } else { msg.Format(_T("[Pagetest] *** DoStartup() - event dropped because we are already active or not available - '%s'\n"), (LPCTSTR)szUrl); OutputDebugString(msg); } } /*----------------------------------------------------------------------------- See if the test is complete -----------------------------------------------------------------------------*/ void CTestState::CheckComplete() { ATLTRACE(_T("[Pagetest] - Checking to see if the test is complete\n")); if( heartbeatEvent ) SetEvent(heartbeatEvent); if( active ) { CString buff; bool expired = false; bool done = false; __int64 now; QueryPerfCounter(now); DWORD elapsed = (DWORD)((now - start) / freq); bool keepOpen = false; if (minimumDuration && elapsed < minimumDuration) keepOpen = true; // only do the request checking if we're actually active if( active ) { EnterCriticalSection(&cs); // has our timeout expired? if( !keepOpen && timeout && start ) { if( elapsed > timeout ) { buff.Format(_T("[Pagetest] - Test timed out (timout set to %d sec)\n"), timeout); OutputDebugString(buff); expired = true; } else { ATLTRACE(_T("[Pagetest] - Elapsed test time: %d sec\n"), elapsed); } } else { ATLTRACE(_T("[Pagetest] - Start time not logged yet\n")); } LeaveCriticalSection(&cs); // see if the DOM element we're interested in appeared yet CheckDOM(); // only exit if there isn't an outstanding doc or request if( !keepOpen && ((lastRequest && !currentDoc) || expired || forceDone || errorCode) ) { done = forceDone || errorCode != 0; if( !done ) { // count the number of open wininet requests EnterCriticalSection(&cs); openRequests = 0; POSITION pos = winInetRequestList.GetHeadPosition(); while( pos ) { CWinInetRequest * r = winInetRequestList.GetNext(pos); if( r && r->valid && !r->end ) { ATLTRACE(_T("[Pagetest] (0x%p) %s%s\n"), r->hRequest, r->host, r->object); openRequests++; } } LeaveCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - %d openRequests"), openRequests); // did the DOM element arrive yet (if we're looking for one?) if( (domElement || (domElementId.IsEmpty() && domRequest.IsEmpty())) && requiredRequests.IsEmpty() && !script_waitForJSDone ) { // see if we are done (different logic if we're in abm mode or not) if( abm ) { DWORD elapsed = now > lastActivity && lastActivity ? (DWORD)((now - lastActivity ) / (freq / 1000)) : 0; DWORD elapsedRequest = now > lastRequest && lastRequest ? (DWORD)((now - lastRequest ) / (freq / 1000)) : 0; if ( (!openRequests && elapsed > activityTimeout) || // no open requests and it's been longer than 2 seconds since the last request (!openRequests && elapsedRequest > REQUEST_ACTIVITY_TIMEOUT) || // no open requests and it's been longer than 30 seconds since the last traffic on the wire (openRequests && elapsedRequest > FORCE_ACTIVITY_TIMEOUT) ) // open requests but it's been longer than 60 seconds since the last one (edge case) that touched the wire { done = true; expired = false; OutputDebugString(_T("[Pagetest] ***** Measured as Web 2.0\n")); } } else { if( lastDoc ) // make sure we actually measured a document - shouldn't be possible to not be set but just to be safe { DWORD elapsed = (DWORD)((now - lastDoc) / (freq / 1000)); if( elapsed > DOC_TIMEOUT ) { done = true; expired = false; OutputDebugString(_T("[Pagetest] ***** Measured as Web 1.0\n")); } } } } } else { buff.Format(_T("[Pagetest] - Force exit. Error code = %d (0x%08X)\n"), errorCode, errorCode); OutputDebugString(buff); } } } if ( !keepOpen && (expired || done) ) { CString buff; buff.Format(_T("[Pagetest] ***** Page Done\n") _T("[Pagetest] Document ended: %0.3f sec\n") _T("[Pagetest] Last Activity: %0.3f sec\n") _T("[Pagetest] DOM Element: %0.3f sec\n"), !endDoc ? 0.0 : (double)(endDoc-start) / (double)freq, !lastRequest ? 0.0 : (double)(lastRequest-start) / (double)freq, !domElement ? 0.0 : (double)(domElement-start) / (double)freq); OutputDebugString(buff); // see if we are combining multiple script steps (in which case we need to start again) if( runningScript && script_combineSteps && script_combineSteps != 1 && !script.IsEmpty() ) { if( script_combineSteps > 1 ) script_combineSteps--; // do some basic resetting end = 0; lastRequest = 0; lastActivity = 0; endDoc = 0; ContinueScript(false); } else { GetCPUTime(endCPU, endCPUtotal); // keep track of the end time in case there wasn't a document if( !end || abm ) end = lastRequest; // put some text on the browser window to indicate we're done double sec = (start && end > start) ? (double)(end - start) / (double)freq: 0; if( !expired ) reportSt = TIMER; else reportSt = QUIT_NOEND; RepaintWaterfall(); // kill the background timer if( hTimer ) { DeleteTimerQueueTimer(NULL, hTimer, NULL); hTimer = 0; timeEndPeriod(1); } // get a screen shot of the fully loaded page if( saveEverything ) { FindBrowserWindow(); screenCapture.Capture(hBrowserWnd, CapturedImage::FULLY_LOADED); } // write out any results (this will also kill the timer) FlushResults(); } } } } /*----------------------------------------------------------------------------- See if the browser's readystate has changed -----------------------------------------------------------------------------*/ void CTestState::CheckReadyState(void) { if (!m_spChromeFrame) { // figure out the old state (first non-complete browser window) EnterCriticalSection(&cs); READYSTATE oldState = READYSTATE_COMPLETE; POSITION pos = browsers.GetHeadPosition(); while( pos && oldState == READYSTATE_COMPLETE ) { CBrowserTracker tracker = browsers.GetNext(pos); if( tracker.state != READYSTATE_COMPLETE ) oldState = tracker.state; } // update the state for all browsers in this thread CAtlList<CComPtr<IWebBrowser2>> browsers2; pos = browsers.GetHeadPosition(); while( pos ) { POSITION oldPos = pos; CBrowserTracker tracker = browsers.GetNext(pos); if(tracker.browser && tracker.threadId == GetCurrentThreadId()) tracker.browser->get_ReadyState(&(browsers.GetAt(oldPos).state)); } // see what the new state is READYSTATE newState = READYSTATE_COMPLETE; pos = browsers.GetHeadPosition(); while( pos && newState == READYSTATE_COMPLETE ) { CBrowserTracker tracker = browsers.GetNext(pos); if( tracker.state != READYSTATE_COMPLETE ) newState = tracker.state; } LeaveCriticalSection(&cs); if( newState != oldState ) { currentState = newState; CString state; switch(currentState) { case READYSTATE_UNINITIALIZED: state = "Uninitialized"; break; case READYSTATE_LOADING: state = "Loading"; break; case READYSTATE_LOADED: state = "Loaded"; break; case READYSTATE_INTERACTIVE: state = "Interactive"; break; case READYSTATE_COMPLETE: { state = "Complete"; // force a DocumentComplete in case we never got notified if( active && currentDoc ) DocumentComplete(url); } break; default: state = "Unknown"; break; } CString buff; buff.Format(_T("Browser ReadyState changed to %s\n"), (LPCTSTR)state); StatusUpdate(buff); OutputDebugString(buff); } } } /*----------------------------------------------------------------------------- Check to see if a specific DOM element we're looking for has been loaded yet -----------------------------------------------------------------------------*/ void CTestState::CheckDOM(void) { // don't bother if we already found it if(!domElementId.IsEmpty() && !domElement && startRender) { if( FindDomElementByAttribute(domElementId) ) { QueryPerfCounter(domElement); lastRequest = lastActivity = domElement; CString buff; buff.Format(_T("[Pagetest] * DOM Element ID '%s' appeared\n"), (LPCTSTR)domElementId); OutputDebugString(buff); if( saveEverything ) { FindBrowserWindow(); screenCapture.Capture(hBrowserWnd, CapturedImage::DOM_ELEMENT); } } } } /*----------------------------------------------------------------------------- Check to see if anything was drawn to the screen -----------------------------------------------------------------------------*/ void CTestState::PaintEvent(int x, int y, int width, int height) { if (active) { SetBrowserWindowUpdated(true); CheckWindowPainted(); } } /*----------------------------------------------------------------------------- Check to see if anything was drawn to the screen -----------------------------------------------------------------------------*/ void CTestState::CheckWindowPainted() { if( active && !painted && hBrowserWnd && ::IsWindow(hBrowserWnd) && BrowserWindowUpdated() ) { // grab a screen shot of the window GdiFlush(); screenCapture.Lock(); SetBrowserWindowUpdated(false); __int64 now; QueryPerfCounter(now); const DWORD START_RENDER_MARGIN = 30; // grab a screen shot CapturedImage captured_img(hBrowserWnd,CapturedImage::START_RENDER); captured_img._capture_time.QuadPart = now; CxImage img; if (captured_img.Get(img) && img.GetWidth() > START_RENDER_MARGIN * 2 && img.GetHeight() > START_RENDER_MARGIN * 2) { int bpp = img.GetBpp(); if (bpp >= 15) { int height = img.GetHeight(); int width = img.GetWidth(); // 24-bit gets a fast-path where we can just compare full rows if (bpp <= 24 ) { DWORD row_bytes = 3 * (width - (START_RENDER_MARGIN * 2)); char * white = (char *)malloc(row_bytes); if (white) { memset(white, 0xFFFFFFFF, row_bytes); for (DWORD row = START_RENDER_MARGIN; row < height - START_RENDER_MARGIN && !painted; row++) { char * image_bytes = (char *)img.GetBits(row) + START_RENDER_MARGIN; if (memcmp(image_bytes, white, row_bytes)) painted = true; } free (white); } } else { for (DWORD row = START_RENDER_MARGIN; row < height - START_RENDER_MARGIN && !painted; row++) { for (DWORD x = START_RENDER_MARGIN; x < width - START_RENDER_MARGIN && !painted; x++) { RGBQUAD pixel = img.GetPixelColor(x, row, false); if (pixel.rgbBlue != 255 || pixel.rgbRed != 255 || pixel.rgbGreen != 255) painted = true; } } } } } if (painted) { startRender = now; OutputDebugString(_T("[Pagetest] * Render Start (Painted)")); screenCapture._captured_images.AddTail(captured_img); } else captured_img.Free(); screenCapture.Unlock(); } } /*----------------------------------------------------------------------------- Parse the test options string -----------------------------------------------------------------------------*/ void CTestState::ParseTestOptions() { TCHAR buff[4096]; if( !testOptions.IsEmpty() ) { int pos = 0; do { // commands are separated by & just like query parameters CString token = testOptions.Tokenize(_T("&"), pos); if( token.GetLength() ) { int index = token.Find(_T('=')); if( index > 0 ) { CString command = token.Left(index).Trim(); if( command.GetLength() ) { // any values need to be escaped since it is passed in on the url so un-escape it CString tmp = token.Mid(index + 1); DWORD len; if( AtlUnescapeUrl((LPCTSTR)tmp, buff, &len, _countof(buff)) ) { CString value = buff; value = value.Trim(); // now handle the actual command if( !command.CompareNoCase(_T("ptBlock")) ) { // block the specified request blockRequests.AddTail(value); } if( !command.CompareNoCase(_T("ptAds")) ) { // block aol-specific ad calls if( !value.CompareNoCase(_T("none")) || !value.CompareNoCase(_T("block")) ) { blockRequests.AddTail(_T("adsWrapper.js")); blockRequests.AddTail(_T("adsWrapperAT.js")); blockRequests.AddTail(_T("adsonar.js")); blockRequests.AddTail(_T("sponsored_links1.js")); blockRequests.AddTail(_T("switcher.dmn.aol.com")); } } } } } } }while( pos >= 0 ); } // see if the DOM element was really a DOM request in hiding if( domElementId.GetLength() ) { int pos = 0; CString action = domElementId.Tokenize(_T("="), pos).Trim(); if( pos != -1 ) { CString val = domElementId.Tokenize(_T("="), pos).Trim(); if( val.GetLength() ) { if( !action.CompareNoCase(_T("RequestEnd")) ) { domRequest = val; domRequestType = END; domElementId.Empty(); } else if( !action.CompareNoCase(_T("RequestTTFB")) ) { domRequest = val; domRequestType = TTFB; domElementId.Empty(); } else if( !action.CompareNoCase(_T("RequestStart")) ) { domRequest = val; domRequestType = START; domElementId.Empty(); } } } } } VOID CALLBACK BackgroundTimer(PVOID lpParameter, BOOLEAN TimerOrWaitFired) { if( lpParameter ) ((CTestState *)lpParameter)->BackgroundTimer(); } /*----------------------------------------------------------------------------- Measurement is starting, kick off the background stuff -----------------------------------------------------------------------------*/ void CTestState::StartMeasuring(void) { // create thee background timer to fire every 100ms if( !hTimer && saveEverything && (!runningScript || script_logData) ) { lastBytes = 0; lastCpuIdle = 0; lastCpuKernel = 0; lastCpuUser = 0; lastTime = 0; imageCount = 0; lastImageTime = 0; lastRealTime = 0; SetBrowserWindowUpdated(true); // now find just the browser control FindBrowserWindow(); if( hMainWindow ) { ::SetWindowPos(hMainWindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); ::UpdateWindow(hMainWindow); } timeBeginPeriod(1); CreateTimerQueueTimer(&hTimer, NULL, ::BackgroundTimer, this, 100, 100, WT_EXECUTEDEFAULT); // Force a grab/stats capture now BackgroundTimer(); } } /*----------------------------------------------------------------------------- Do the 100ms periodic checking -----------------------------------------------------------------------------*/ void CTestState::BackgroundTimer(void) { // queue up a message in case we're having timer problems CheckStuff(); FindBrowserWindow(); // timer will only be running while we're active EnterCriticalSection(&csBackground); const DWORD imageIncrements = 20; // allow for X screen shots at each increment __int64 now; QueryPerfCounter(now); if( active ) { CProgressData data; data.sampleTime = now; DWORD ms = 0; if( start && now > start ) ms = (DWORD)((now - start) / msFreq); // round to the closest 100ms data.ms = ((ms + 50) / 100) * 100; // don't re-do everything if we get a burst of timer callbacks if( data.ms != lastTime || !lastTime ) { DWORD msElapsed = 0; if( data.ms > lastTime ) msElapsed = data.ms - lastTime; double elapsed = 0; if( now > lastRealTime && lastRealTime) elapsed = (double)(now - lastRealTime) / (double)freq; lastRealTime = now; // figure out the bandwidth if (elapsed > 0) { double bits = (bwBytesIn - lastBytes) * 8; data.bpsIn = (DWORD)(bits / elapsed); } // calculate CPU utilization FILETIME idle, kernel, user; if( GetSystemTimes( &idle, &kernel, &user) ) { ULARGE_INTEGER k, u, i; k.LowPart = kernel.dwLowDateTime; k.HighPart = kernel.dwHighDateTime; u.LowPart = user.dwLowDateTime; u.HighPart = user.dwHighDateTime; i.LowPart = idle.dwLowDateTime; i.HighPart = idle.dwHighDateTime; if( lastCpuIdle || lastCpuKernel || lastCpuUser ) { __int64 idle = i.QuadPart - lastCpuIdle; __int64 kernel = k.QuadPart - lastCpuKernel; __int64 user = u.QuadPart - lastCpuUser; int cpu_utilization = (int)((((kernel + user) - idle) * 100) / (kernel + user)); data.cpu = max(min(cpu_utilization, 100), 0); } lastCpuIdle = i.QuadPart; lastCpuKernel = k.QuadPart; lastCpuUser = u.QuadPart; } // get the memory use (working set - task-manager style) PROCESS_MEMORY_COUNTERS mem; mem.cb = sizeof(mem); if( GetProcessMemoryInfo(GetCurrentProcess(), &mem, sizeof(mem)) ) data.mem = mem.WorkingSetSize / 1024; // interpolate across multiple time periods if( msElapsed > 100 ) { DWORD chunks = msElapsed / 100; for( DWORD i = 1; i < chunks; i++ ) { CProgressData d; d.ms = lastTime + (i * 100); d.cpu = data.cpu; // CPU time was already spread over the period d.bpsIn = data.bpsIn / chunks; // split bandwidth evenly across the time slices d.mem = data.mem; // just assign them all the same memory use (could interpolate but probably not worth it) progressData.AddTail(d); } data.bpsIn /= chunks; // bandwidth is the only measure in the main chunk that needs to be adjusted } bool grabImage = false; if( !lastImageTime ) { if( captureVideo && hBrowserWnd && IsWindow(hBrowserWnd) ) grabImage = true; } else if( painted && captureVideo && hBrowserWnd && IsWindow(hBrowserWnd) && BrowserWindowUpdated() ) { // see what time increment we are in // we go from 0.1 second to 1 second to 5 second intervals // as we get more and more screen shots DWORD minTime = 100; if( imageCount >= imageIncrements ) minTime = 1000; if( imageCount >= imageIncrements * 2 ) minTime = 5000; if( data.ms > lastImageTime && (data.ms - lastImageTime) >= minTime ) grabImage = true; } if( grabImage ) { ATLTRACE(_T("[Pagetest] - Grabbing video frame : %d ms\n"), data.ms); if( painted ) SetBrowserWindowUpdated(false); screenCapture.Capture(hBrowserWnd, CapturedImage::VIDEO); imageCount++; lastImageTime = data.ms; if( !lastImageTime ) lastImageTime = 1; } progressData.AddTail(data); lastTime = data.ms; } lastBytes = bwBytesIn; } LeaveCriticalSection(&csBackground); } /*----------------------------------------------------------------------------- Delete any cache items with a lifetime less than cacheTTL -----------------------------------------------------------------------------*/ #define RATIO_100NANO_TO_SECOND ((_int64)10000000) void CTestState::ClearShortTermCache(DWORD cacheTTL) { DWORD cacheEntryInfoBufferSizeInitial = 0; DWORD cacheEntryInfoBufferSize = 0; DWORD dwError; LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry; HANDLE hCacheDir; // Determine the size of the first entry, if it exists hCacheDir = FindFirstUrlCacheEntry(NULL,0,&cacheEntryInfoBufferSizeInitial); if (hCacheDir == NULL && GetLastError() == ERROR_NO_MORE_ITEMS) return; // Get the current time in a large integer (seems like a weird way to do it, but that's what MSDN dictates...) SYSTEMTIME curSysTime; GetSystemTime(&curSysTime); FILETIME curFileTime; SystemTimeToFileTime(&curSysTime, &curFileTime); ULONGLONG curTimeSecs = ((((ULONGLONG) curFileTime.dwHighDateTime) << 32) + curFileTime.dwLowDateTime) / RATIO_100NANO_TO_SECOND; // Read the first entry cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cacheEntryInfoBufferSize); hCacheDir = FindFirstUrlCacheEntry(NULL, lpCacheEntry, &cacheEntryInfoBufferSizeInitial); // Iterate the current and next entries BOOL retVal = (hCacheDir != NULL); while(retVal) { cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize; // Find out the current time in secs ULONGLONG cacheItemTimeSecs = ((((ULONGLONG) lpCacheEntry->ExpireTime.dwHighDateTime) << 32) + lpCacheEntry->ExpireTime.dwLowDateTime) / RATIO_100NANO_TO_SECOND; // If the item expires in less than the given limit, delete it if (cacheItemTimeSecs < (curTimeSecs + cacheTTL)) DeleteUrlCacheEntry(lpCacheEntry->lpszSourceUrlName); // Get the next record retVal = FindNextUrlCacheEntry(hCacheDir, lpCacheEntry, &cacheEntryInfoBufferSizeInitial); if (!retVal) { // If we have no more items, break dwError = GetLastError(); if (dwError == ERROR_NO_MORE_ITEMS) { break; } // Otherwise, if the error was insufficient buffer, increase the buffer size if (dwError == ERROR_INSUFFICIENT_BUFFER && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize) { cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; // Re-allocate to a larger size lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, lpCacheEntry, cacheEntryInfoBufferSize); if (lpCacheEntry) retVal = FindNextUrlCacheEntry(hCacheDir, lpCacheEntry, &cacheEntryInfoBufferSizeInitial); } else break; } } HeapFree(GetProcessHeap(),0,lpCacheEntry); // Cleanup the cache dir handle FindCloseUrlCache(hCacheDir); }
32.080808
176
0.582034
LeeLiangze
10d472fae34963d694d665e8e9b952f4e0a3920c
3,062
cc
C++
tests/functional_small/rom/correctness_lspg_steady/preconditioned_hypred/main.cc
nittaya1990/pressio
22fad15ffc00f3e4d880476a5e60b227ac714ef4
[ "BSD-3-Clause" ]
1
2021-09-24T17:06:51.000Z
2021-09-24T17:06:51.000Z
tests/functional_small/rom/correctness_lspg_steady/preconditioned_hypred/main.cc
nittaya1990/pressio
22fad15ffc00f3e4d880476a5e60b227ac714ef4
[ "BSD-3-Clause" ]
2
2021-10-03T20:36:28.000Z
2021-10-17T10:26:06.000Z
tests/functional_small/rom/correctness_lspg_steady/preconditioned_hypred/main.cc
nittaya1990/pressio
22fad15ffc00f3e4d880476a5e60b227ac714ef4
[ "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include "../custom_types_specialized_ops.hpp" #include "../checker.hpp" #include "foms.hpp" #include "../preconditioners.hpp" #include "pressio/rom_lspg.hpp" TEST(rom_lspg, steady_preconitioned_hypred_correctness_eigen) { pressio::log::initialize(pressio::logto::terminal); pressio::log::setVerbosity({pressio::log::level::debug}); using fom_t = TrivialFomSteadyEigen; using fom_state_t = typename fom_t::state_type; using scalar_t = typename fom_t::scalar_type; const int nstencil = 15; const int nSample = 8; fom_t fomSystem(nSample); fom_state_t fomReferenceState(nstencil); fomReferenceState.setZero(); using phi_t = Eigen::Matrix<scalar_t, -1,-1>; phi_t phi(nstencil, 3); int count = 0; for (int i=0; i<nstencil; ++i){ for (int j=0; j<3; ++j){ if (i % 2 == 0){ phi(i,j) = (scalar_t) count++; } else{ phi(i,j) = (scalar_t) -1; } } } auto decoder = pressio::rom::create_time_invariant_linear_decoder<fom_state_t>(phi); Eigen::VectorXd romState(3); romState[0]=0.; romState[1]=1.; romState[2]=2.; PreconditionerSteadyEigen prec; auto problem = pressio::rom::lspg::create_hyperreduced_steady_problem(fomSystem, decoder, romState, fomReferenceState, prec); auto & solvableSystem = problem.system(); FakeNonLinSolverSteady nonLinSolver(nSample); nonLinSolver.solve(solvableSystem, romState); std::cout << romState << std::endl; EXPECT_DOUBLE_EQ(romState[0], 2.); EXPECT_DOUBLE_EQ(romState[1], 3.); EXPECT_DOUBLE_EQ(romState[2], 4.); pressio::log::finalize(); } TEST(rom_lspg, steady_preconitioned_hypred_correctness_custom_types) { pressio::log::initialize(pressio::logto::terminal); pressio::log::setVerbosity({pressio::log::level::debug}); using fom_t = TrivialFomSteadyCustomTypes; using fom_state_t = typename fom_t::state_type; using scalar_t = typename fom_t::scalar_type; const int nstencil = 15; const int nSample = 8; fom_t fomSystem(nSample); fom_state_t fomReferenceState(nstencil); fomReferenceState.fill(0); using phi_t = ::pressiotests::MyCustomMatrix<scalar_t>; phi_t phi(nstencil, 3); int count = 0; for (int i=0; i<nstencil; ++i){ for (int j=0; j<3; ++j){ if (i % 2 == 0){ phi(i,j) = (scalar_t) count++; } else{ phi(i,j) = (scalar_t) -1; } } } auto decoder = pressio::rom::create_time_invariant_linear_decoder<fom_state_t>(phi); Eigen::VectorXd romState(3); romState[0]=0.; romState[1]=1.; romState[2]=2.; PreconditionerSteadyCustomTypes<scalar_t> prec; auto problem = pressio::rom::lspg::create_hyperreduced_steady_problem(fomSystem, decoder, romState, fomReferenceState, prec); auto & solvableSystem = problem.system(); FakeNonLinSolverSteady nonLinSolver(nSample); nonLinSolver.solve(solvableSystem, romState); std::cout << romState << std::endl; EXPECT_DOUBLE_EQ(romState[0], 2.); EXPECT_DOUBLE_EQ(romState[1], 3.); EXPECT_DOUBLE_EQ(romState[2], 4.); pressio::log::finalize(); }
28.351852
127
0.692685
nittaya1990
10d5edc0e2b787ca1d4f86efd5e14ee2726704aa
1,799
cpp
C++
compiler/nnc/driver/main.cpp
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
compiler/nnc/driver/main.cpp
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
compiler/nnc/driver/main.cpp
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <vector> #include "support/CommandLine.h" #include "pass/PassException.h" #include "Driver.h" using namespace nnc; /* * Prints the explanatory string of an exception. If the exception is nested, recurses to print * the explanatory string of the exception it holds. */ static void printException(const std::exception &e, int indent = 0) { std::cerr << std::string(indent, ' ') << e.what() << std::endl; try { std::rethrow_if_nested(e); } catch (const std::exception &e) { printException(e, indent + 2); } } int main(int argc, const char *argv[]) { int exit_code = EXIT_FAILURE; try { // Parse command line cli::CommandLine::getParser()->parseCommandLine(argc, argv); // // run compiler pipeline: // // for_each(all_passes): // run pass // Driver driver; driver.runDriver(); // errors didn't happen exit_code = EXIT_SUCCESS; } catch (const DriverException &e) { printException(e); std::cerr << "use --help for more information" << std::endl; } catch (const PassException &e) { printException(e); } return exit_code; }
23.671053
95
0.673708
periannath
10d8d369bdb03f1424f31663636cf2fb231ddb29
6,945
cpp
C++
src/IECoreGL/ToGLTextureConverter.cpp
goddardl/cortex
323a160fd831569591cde1504f415a638f8b85bc
[ "BSD-3-Clause" ]
null
null
null
src/IECoreGL/ToGLTextureConverter.cpp
goddardl/cortex
323a160fd831569591cde1504f415a638f8b85bc
[ "BSD-3-Clause" ]
null
null
null
src/IECoreGL/ToGLTextureConverter.cpp
goddardl/cortex
323a160fd831569591cde1504f415a638f8b85bc
[ "BSD-3-Clause" ]
1
2020-09-26T01:15:37.000Z
2020-09-26T01:15:37.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2012, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software 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 <cassert> #include "boost/format.hpp" #include "IECore/TypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/CompoundData.h" #include "IECore/PrimitiveVariable.h" #include "IECore/ImagePrimitive.h" #include "IECore/DespatchTypedData.h" #include "IECore/MessageHandler.h" #include "IECoreGL/ToGLTextureConverter.h" #include "IECoreGL/ColorTexture.h" #include "IECoreGL/LuminanceTexture.h" using namespace IECoreGL; IE_CORE_DEFINERUNTIMETYPED( ToGLTextureConverter ); ToGLTextureConverter::ConverterDescription<ToGLTextureConverter> ToGLTextureConverter::g_description; ToGLTextureConverter::ConverterDescription<ToGLTextureConverter> ToGLTextureConverter::g_compoundDataDescription( IECore::CompoundData::staticTypeId(), IECoreGL::Texture::staticTypeId() ); ToGLTextureConverter::ToGLTextureConverter( IECore::ConstObjectPtr toConvert, bool createMissingRGBChannels ) : ToGLConverter( "Converts IECore::ImagePrimitive objects to IECoreGL::Texture objects.", IECore::ObjectTypeId ), m_createMissingRGBChannels( createMissingRGBChannels ) { srcParameter()->setValue( boost::const_pointer_cast<IECore::Object>( toConvert ) ); } ToGLTextureConverter::~ToGLTextureConverter() { } IECore::RunTimeTypedPtr ToGLTextureConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const { TexturePtr t = 0; IECore::ImagePrimitive::ConstPtr image; image = IECore::runTimeCast<const IECore::ImagePrimitive>( src ); if ( ! image ) { IECore::CompoundData::ConstPtr data = IECore::runTimeCast<const IECore::CompoundData>( src ); if ( !data ) { throw IECore::Exception( "Invalid object supplied. ToGLTextureConverter takes an ImagePrimitive or its CompoundData representation." ); } image = imageFromCompoundData( data ); } bool r = image->channelValid( "R" ); bool g = image->channelValid( "G" ); bool b = image->channelValid( "B" ); bool y = image->channelValid( "Y" ); if ( !y && r && g && b ) { t = new ColorTexture( image.get() ); } else if ( y && !r && !g && !b ) { t = new LuminanceTexture( image.get() ); } else { if( m_createMissingRGBChannels ) { image = createMissingChannels( image.get() ); t = new ColorTexture( image.get() ); } else { throw IECore::Exception( "Invalid image format, ToGLTextureConverter supports RGB[A] and Y[A]." ); } } if ( ! t ) { throw IECore::Exception( "Failed to create IECoreGL Texture." ); } return t; } IECore::ImagePrimitivePtr ToGLTextureConverter::createMissingChannels( const IECore::ImagePrimitive *image ) const { IECore::ImagePrimitivePtr newImage = image->copy(); if( newImage->getChannel<float>( "R" ) == 0) { newImage->createChannel<float>( "R" ); } if( newImage->getChannel<float>( "G" ) == 0) { newImage->createChannel<float>( "G" ); } if( newImage->getChannel<float>( "B" ) == 0) { newImage->createChannel<float>( "B" ); } return newImage; } IECore::ImagePrimitivePtr ToGLTextureConverter::imageFromCompoundData( IECore::CompoundData::ConstPtr data ) const { if ( ! data ) { throw IECore::Exception( "No CompoundData supplied." ); } IECore::Box2iDataPtr dataWindow = 0; IECore::CompoundDataMap::const_iterator itData = data->readable().find( "dataWindow" ); if ( itData == data->readable().end() ) { throw IECore::Exception( "Invalid CompoundData supplied. ImagePrimitive representations need a dataWindow (Box2i)." ); } dataWindow = IECore::runTimeCast<IECore::Box2iData>( itData->second ); IECore::Box2iDataPtr screenWindow = 0; itData = data->readable().find( "displayWindow" ); if ( itData == data->readable().end() ) { throw IECore::Exception( "Invalid CompoundData supplied. ImagePrimitive representations need a screenWindow (Box2i)." ); } screenWindow = IECore::runTimeCast<IECore::Box2iData>( itData->second ); IECore::CompoundDataPtr channels = 0; itData = data->readable().find( "channels" ); if ( itData == data->readable().end() ) { throw IECore::Exception( "Invalid CompoundData supplied. ImagePrimitive representations need a CompoundDataMap of channels." ); } channels = IECore::runTimeCast<IECore::CompoundData>( itData->second ); if ( !dataWindow || !screenWindow || !channels ) { throw IECore::Exception( "Invalid CompoundData representation supplied. Some data is of the wrong type" ); } IECore::ImagePrimitivePtr newImage = new IECore::ImagePrimitive( dataWindow->readable(), screenWindow->readable() ); for ( IECore::CompoundDataMap::const_iterator itChannels = channels->readable().begin(); itChannels != channels->readable().end(); itChannels++ ) { IECore::FloatVectorDataPtr channelData = IECore::runTimeCast<IECore::FloatVectorData>( itChannels->second ); if ( ! channelData ) { throw IECore::Exception( "Invalid channel data found in ImagePrimitive representation, only 32bit float data is supported. Please check texture."); } newImage->variables.insert( IECore::PrimitiveVariableMap::value_type( itChannels->first, IECore::PrimitiveVariable( IECore::PrimitiveVariable::Vertex, channelData ) ) ); } return newImage; }
33.878049
188
0.715191
goddardl
10dd4e7e6d0f6ae718e21b3a1b8397eefce814a0
8,859
cpp
C++
esp-at/UnifiedAtEvent.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
2
2020-03-05T12:59:06.000Z
2020-03-11T02:58:53.000Z
esp-at/UnifiedAtEvent.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
null
null
null
esp-at/UnifiedAtEvent.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
null
null
null
#define private public #include"Uart.h" #include"UnifiedAtEvent.h" #include"Utilities.h" #include"UnifiedBackTask.h" #define T_US 1000000.0 #define T_MS 1000.0 #define ESP_BIT_RATE 115200 #define ESP_BYTE_RATE (1.0 * ESP_BIT_RATE / 11) #define MAX_DESIRED 50.0 #define COST(bytes) uint32_t(T_US / ESP_BYTE_RATE * (bytes)) #define ei else if #define es else #define self (*(EspStateBar *)handle) volatile bool isUseRtosMemory = false; void * memoryAlloc(size_t size){ void * ptr; if (isUseRtosMemory == false){ if (ptr = malloc(size)){ return ptr; } } Rtos::malloc(& ptr, size); return ptr; } void memoryFree(void * ptr){ if (isUseRtosMemory == false){ free(ptr); } else{ Rtos::free(ptr); } } void * operator new(size_t size) { return memoryAlloc(size); } void * operator new[](size_t size) { return memoryAlloc(size); } void operator delete(void * ptr) { memoryFree(ptr); } void operator delete[](void * ptr) { memoryFree(ptr); } namespace{ #ifdef USE_ESP32_AT_SERIAL #define PIN_RX auto & com = Serial; #elif defined USE_ESP32_AT_SERIAL2 #define PIN_RX auto & com = Serial2; #elif defined USE_ESP32_AT_SERIAL1 #define PIN_RX auto & com = Serial1; #endif volatile bool ipdMode = false; } #ifdef PIN_RX // void sendSignal(void * serial, char chr){ // if (serial != & com){ // return; // } // // debug("%c", chr); // // static uint64_t word = 0; // // uint64_t want = '+' << 32 | 'I' << 24 | 'P' << 16 | 'D' << 8 | ':'; // // auto flag = (want & word) == want && ipdMode == false; // // word = word << 8 | chr; // // Rtos::giveFromISR(esp.semaWaitRx); // // com.rxBuffer.clear(); // // uint32_t size; // // Rtos::queueSize(esp.rxQueue, & size); // // Rtos::queueSendFromISR(esp.rxQueue, chr); // } int EspStateBar::available(){ return com.available(); } int EspStateBar::read(){ return com.read(); } void EspStateBar::begin(){ com.begin(ESP_BIT_RATE); } void EspStateBar::write(Text value){ com.print(value.c_str()); } void EspStateBar::txBin(uint8_t const * buffer, size_t length){ com.write(buffer, length); } // default: // - wifi multi-connection // - close echo // - show IPD remote ip:port void EspStateBar::reset(){ wifi.reset(); tx("ATE0"); flush(); waitFlag(); tx("AT+CIPMUX=1"); flush(); waitFlag(); tx("AT+CIPDINFO=1"); flush(); waitFlag(); } #else int EspStateBar::available(){ return -1; } int EspStateBar::read(){ return -1; } void EspStateBar::begin(){} void EspStateBar::write(Text value){} void EspStateBar::reset(){} #endif EspStateBar esp; struct TokenEventPair{ typedef std::function<void(EspStateBar &, Text &)> Invoke; const char * token; Invoke invoke; }; std::initializer_list<TokenEventPair> responesMap = { { "ready", [](EspStateBar & esp, Text &){ esp.reset(); esp.whenReset(); } }, { "WIFI CONNECTED", [](EspStateBar & esp, Text &){ esp.wifi.state = WifiConnected; esp.wifi.whenStateChanged(); } }, { "WIFI GOT IP", [](EspStateBar & esp, Text &){ esp.wifi.state = WifiGotIp; esp.wifi.whenStateChanged(); } }, { "WIFI DISCONNECT", [](EspStateBar & esp, Text &){ esp.wifi.state = WifiDisconnect; esp.wifi.whenStateChanged(); } }, { "smartconfig connected wifi", [](EspStateBar & esp, Text &){ esp.smart.state = Success; esp.smart.whenRising(); } }, { "smartconfig connect Fail", [](EspStateBar & esp, Text &) { esp.smart.state = Fail; esp.smart.whenRising(); } }, { "OK", [](EspStateBar & esp, Text &) { if (esp.wait == WaitWifiScan){ esp.wifi.whenScanFinished(); } esp.wait = WaitNothing; esp.flag = Success; Rtos::give(esp.semaWaitCmd); // for waitFlag Rtos::give(esp.semaWaitCmd); // for tx } }, { "ERROR", [](EspStateBar & esp, Text &) { if (esp.wait == WaitWifiScan){ esp.wifi.whenScanFailed(); } esp.wait = WaitNothing; esp.flag = Fail; Rtos::give(esp.semaWaitCmd); // for waitFlag Rtos::give(esp.semaWaitCmd); // for tx } }, { "+IPD", [](EspStateBar & esp, Text & resp){ int32_t id; Ipd ipd; // +5 to skip "+IPD," esp.rx(resp.c_str() + 5, & id, & ipd.length, & ipd.ip, & ipd.port); ipd.data = std::shared_ptr<uint8_t>(new uint8_t[ipd.length]); ipd.i = 0; for (int32_t i = 0; i < ipd.length; i++){ if (esp.available()){ ipd.data.get()[i] = esp.read(); } es{ Rtos::delayus(COST(ipd.length - i)); } } ipdMode = false; esp.wifi.packet[id].push(ipd); esp.wifi.packId = id; esp.wifi.whenReceivePacket(); } }, }; Text EspStateBar::readUntil(char * token){ std::vector<char> buf; char c; while(true){ while (available() <= 0){ Rtos::delayms(1); } c = read(); buf.push_back(c); // debug("%c", c); if (strchr(token, c) != nullptr){ buf.push_back('\0'); return Text(& buf.front()); } } } void EspStateBar::eventHandler(){ while (true) { Text && resp = readUntil(':', '\n'); if (resp.length() == 0){ continue; } // first for (auto & event : responesMap) { if (resp.startsWith(event.token)) { event.invoke(this[0], resp); break; } } // second analysis analysis.invoke(resp); } } Result EspStateBar::waitFlag(uint32_t ms) { Rtos::take(semaWaitCmd, Rtos::msToTicks(ms)); return flag; } // setup and loop code block extern void body(); // FREE RTOS IDLE function extern "C" void vApplicationIdleHook(){} // ESP-LIB function extern bool __attribute__((weak)) _start_network_event_task(){} void fore(void * handle) { _start_network_event_task(); self.begin(); self.reset(); body(); } void back(void * handle){ self.eventHandler(); } void espAtShell(){ esp.run(); while(1); } void EspStateBar::run(){ isUseRtosMemory = true; Rtos::createSemaphore(& semaWaitCmd, 2 /*max*/, 1 /*for send first cmd.*/); Rtos::createThread(& taskBack, "ESP-BG", back, this, 1024, 1 /*priority*/); Rtos::createThread(& taskFore, "ESP-FG", fore, this, 2048, 1); Rtos::scheduler(); } //void atWifiScanSubfunction(Text current){ // auto & list = esp.wifi.apList; // list.clear(); // // auto lastIndexOf = [](const char * line, char chr, size_t times){ // for (int i = strlen(line); i-- > 0; ){ // if (line[i] != chr){ // continue; // } // if (--times == 0){ // return i; // } // } // return -1; // }; // // while (current.startsWith("+CWLAP:")){ // // char line[] = "+CWLAP:(3,\"POT\",-AL00a\",-53,\"12:34:56:78:9a:bc\",1)"; // char * line = (char *)current.c_str(); // char * p = nullptr; // char * t; // int32_t mac[6]; //need 32bit when use sscanf // int32_t ecn; // int32_t rssi; // int32_t channel; // // p = line + lastIndexOf(line, ',', 3); // // sscanf(line, "+CWLAP:" "(%d,", & ecn); // sscanf(p + 1, "%d,\"%x:%x:%x:%x:%x:%x\",%d", // & rssi, // & mac[0], // & mac[1], // & mac[2], // & mac[3], // & mac[4], // & mac[5], // & channel // ); // // //replace '\"' to '\0' // p[0] = ','; // p[-1] = '\0'; // // WifiApItem info; // info.ecn = ecn; // info.ssid = strchr(line, ',') + 2; //skip ',' '\"' // info.rssi = rssi; // copy<uint8_t, int32_t>(info.bssid, mac, 6); // info.channel = channel; // list.push_back(info); // current = readLine(); // } // // if (esp.wifi.whenFinishScan){ // esp.wifi.whenFinishScan(); // } //} //
25.604046
88
0.493397
PowerfulCat
10e26290e120d2346f7b9a49fed586952788fc27
26,485
cc
C++
be/src/exprs/scalar-fn-call.cc
AtScaleInc/Impala
1073a9108220faffe61c3bc9dff7a953adde12df
[ "Apache-2.0" ]
null
null
null
be/src/exprs/scalar-fn-call.cc
AtScaleInc/Impala
1073a9108220faffe61c3bc9dff7a953adde12df
[ "Apache-2.0" ]
null
null
null
be/src/exprs/scalar-fn-call.cc
AtScaleInc/Impala
1073a9108220faffe61c3bc9dff7a953adde12df
[ "Apache-2.0" ]
null
null
null
// Copyright 2012 Cloudera 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 "exprs/scalar-fn-call.h" #include <vector> #include <llvm/IR/Attributes.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include "codegen/codegen-anyval.h" #include "codegen/llvm-codegen.h" #include "exprs/anyval-util.h" #include "exprs/expr-context.h" #include "runtime/hdfs-fs-cache.h" #include "runtime/lib-cache.h" #include "runtime/runtime-state.h" #include "runtime/types.h" #include "udf/udf-internal.h" #include "util/debug-util.h" #include "util/dynamic-util.h" #include "util/symbols-util.h" using namespace impala; using namespace impala_udf; using namespace std; ScalarFnCall::ScalarFnCall(const TExprNode& node) : Expr(node), vararg_start_idx_(node.__isset.vararg_start_idx ? node.vararg_start_idx : -1), scalar_fn_wrapper_(NULL), prepare_fn_(NULL), close_fn_(NULL), scalar_fn_(NULL) { DCHECK_NE(fn_.binary_type, TFunctionBinaryType::HIVE); } Status ScalarFnCall::Prepare(RuntimeState* state, const RowDescriptor& desc, ExprContext* context) { RETURN_IF_ERROR(Expr::Prepare(state, desc, context)); if (fn_.scalar_fn.symbol.empty()) { // This path is intended to only be used during development to test FE // code before the BE has implemented the function. // Having the failure in the BE (rather than during analysis) allows for // better FE testing. DCHECK_EQ(fn_.binary_type, TFunctionBinaryType::BUILTIN); stringstream ss; ss << "Function " << fn_.name.function_name << " is not implemented."; return Status(ss.str()); } FunctionContext::TypeDesc return_type = AnyValUtil::ColumnTypeToTypeDesc(type_); vector<FunctionContext::TypeDesc> arg_types; bool char_arg = false; for (int i = 0; i < children_.size(); ++i) { arg_types.push_back(AnyValUtil::ColumnTypeToTypeDesc(children_[i]->type_)); char_arg = char_arg || (children_[i]->type_.type == TYPE_CHAR); } // Compute buffer size for varargs int varargs_buffer_size = 0; if (vararg_start_idx_ != -1) { DCHECK_GT(GetNumChildren(), vararg_start_idx_); for (int i = vararg_start_idx_; i < GetNumChildren(); ++i) { varargs_buffer_size += AnyValUtil::AnyValSize(children_[i]->type()); } } context_index_ = context->Register(state, return_type, arg_types, varargs_buffer_size); // If codegen is disabled and we're calling a non-variadic builtin with <= 3 arguments, // we can use the interpreted path and call the builtin without codegen. // TODO: no need to restrict this to builtins. if (char_arg || (state->codegen() == NULL && vararg_start_idx_ == -1 && children_.size() <= 3 && fn_.binary_type == TFunctionBinaryType::BUILTIN)) { DCHECK(vararg_start_idx_ == -1 && children_.size() <= 3 && fn_.binary_type == TFunctionBinaryType::BUILTIN); Status status = LibCache::instance()->GetSoFunctionPtr( fn_.hdfs_location, fn_.scalar_fn.symbol, &scalar_fn_, &cache_entry_); if (!status.ok()) { // Builtins symbols should exist unless there is a version mismatch. stringstream ss; ss << "Builtin '" << fn_.name.function_name << "' with symbol '" << fn_.scalar_fn.symbol << "' does not exist. " << "Verify that all your impalads are the same version."; status.AddErrorMsg(ss.str()); return status; } } else { // If we got here, either codegen is enabled or we need codegen to run this function. // TODO: reintroduce disable_codegen? We're doing extra work here if the user doesn't // call GetCodegendComputeFn() if (state->codegen() == NULL) RETURN_IF_ERROR(state->CreateCodegen()); if (fn_.binary_type == TFunctionBinaryType::IR) { string local_path; RETURN_IF_ERROR(LibCache::instance()->GetLocalLibPath( fn_.hdfs_location, LibCache::TYPE_IR, &local_path)); // Link the UDF module into this query's main module (essentially copy the UDF // module into the main module) so the UDF's functions are available in the main // module. RETURN_IF_ERROR(state->codegen()->LinkModule(local_path)); } llvm::Function* ir_udf_wrapper; RETURN_IF_ERROR(GetCodegendComputeFn(state, &ir_udf_wrapper)); DCHECK(state->codegen() != NULL); // TODO: don't do this for child exprs state->codegen()->AddFunctionToJit(ir_udf_wrapper, &scalar_fn_wrapper_); } if (fn_.scalar_fn.__isset.prepare_fn_symbol) { RETURN_IF_ERROR(GetFunction(state, fn_.scalar_fn.prepare_fn_symbol, reinterpret_cast<void**>(&prepare_fn_))); } if (fn_.scalar_fn.__isset.close_fn_symbol) { RETURN_IF_ERROR(GetFunction(state, fn_.scalar_fn.close_fn_symbol, reinterpret_cast<void**>(&close_fn_))); } return Status::OK; } Status ScalarFnCall::Open(RuntimeState* state, ExprContext* ctx, FunctionContext::FunctionStateScope scope) { // Opens and inits children RETURN_IF_ERROR(Expr::Open(state, ctx, scope)); FunctionContext* fn_ctx = ctx->fn_context(context_index_); if (scalar_fn_ != NULL) { // We're in the interpreted path (i.e. no JIT). Populate our FunctionContext's // staging_input_vals, which will be reused across calls to scalar_fn_. DCHECK(scalar_fn_wrapper_ == NULL); ObjectPool* obj_pool = state->obj_pool(); vector<AnyVal*>* input_vals = fn_ctx->impl()->staging_input_vals(); for (int i = 0; i < children_.size(); ++i) { input_vals->push_back(CreateAnyVal(obj_pool, children_[i]->type())); } } // Only evaluate constant arguments once per fragment if (scope == FunctionContext::FRAGMENT_LOCAL) { vector<AnyVal*> constant_args; for (int i = 0; i < children_.size(); ++i) { constant_args.push_back(children_[i]->GetConstVal(ctx)); } fn_ctx->impl()->SetConstantArgs(constant_args); } if (prepare_fn_ != NULL) { if (scope == FunctionContext::FRAGMENT_LOCAL) { prepare_fn_(fn_ctx, FunctionContext::FRAGMENT_LOCAL); if (fn_ctx->has_error()) return Status(fn_ctx->error_msg()); } prepare_fn_(fn_ctx, FunctionContext::THREAD_LOCAL); if (fn_ctx->has_error()) return Status(fn_ctx->error_msg()); } // If we're calling MathFunctions::RoundUpTo(), we need to set output_scale_, which // determines how many decimal places are printed. // TODO: revisit this. We should be able to do this if the scale argument is // non-constant. if (fn_.name.function_name == "round" && type_.type == TYPE_DOUBLE) { DCHECK_EQ(children_.size(), 2); if (children_[1]->IsConstant()) { IntVal scale_arg = children_[1]->GetIntVal(ctx, NULL); output_scale_ = scale_arg.val; } } return Status::OK; } void ScalarFnCall::Close(RuntimeState* state, ExprContext* context, FunctionContext::FunctionStateScope scope) { if (context_index_ != -1 && close_fn_ != NULL) { FunctionContext* fn_ctx = context->fn_context(context_index_); close_fn_(fn_ctx, FunctionContext::THREAD_LOCAL); if (scope == FunctionContext::FRAGMENT_LOCAL) { close_fn_(fn_ctx, FunctionContext::FRAGMENT_LOCAL); } } Expr::Close(state, context, scope); } // Dynamically loads the pre-compiled UDF and codegens a function that calls each child's // codegen'd function, then passes those values to the UDF and returns the result. // Example generated IR for a UDF with signature // create function Udf(double, int...) returns double // select Udf(1.0, 2, 3, 4, 5) // define { i8, double } @UdfWrapper(i8* %context, %"class.impala::TupleRow"* %row) { // entry: // %arg_val = call { i8, double } // @ExprWrapper(i8* %context, %"class.impala::TupleRow"* %row) // %arg_ptr = alloca { i8, double } // store { i8, double } %arg_val, { i8, double }* %arg_ptr // %arg_val1 = call i64 @ExprWrapper1(i8* %context, %"class.impala::TupleRow"* %row) // store i64 %arg_val1, i64* inttoptr (i64 89111072 to i64*) // %arg_val2 = call i64 @ExprWrapper2(i8* %context, %"class.impala::TupleRow"* %row) // store i64 %arg_val2, i64* inttoptr (i64 89111080 to i64*) // %arg_val3 = call i64 @ExprWrapper3(i8* %context, %"class.impala::TupleRow"* %row) // store i64 %arg_val3, i64* inttoptr (i64 89111088 to i64*) // %arg_val4 = call i64 @ExprWrapper4(i8* %context, %"class.impala::TupleRow"* %row) // store i64 %arg_val4, i64* inttoptr (i64 89111096 to i64*) // %result = call { i8, double } // @_Z14VarSumMultiplyPN10impala_udf15FunctionContextERKNS_9DoubleValEiPKNS_6IntValE( // %"class.impala_udf::FunctionContext"* inttoptr // (i64 37522464 to %"class.impala_udf::FunctionContext"*), // {i8, double }* %arg_ptr, // i32 4, // i64* inttoptr (i64 89111072 to i64*)) // ret { i8, double } %result Status ScalarFnCall::GetCodegendComputeFn(RuntimeState* state, llvm::Function** fn) { if (ir_compute_fn_ != NULL) { *fn = ir_compute_fn_; return Status::OK; } LlvmCodeGen* codegen = state->codegen(); DCHECK(codegen != NULL); llvm::Function* udf; RETURN_IF_ERROR(GetUdf(state, &udf)); // Create wrapper that computes args and calls UDF stringstream fn_name; fn_name << SymbolsUtil::DemangleNameOnly(udf->getName().str()) << "Wrapper"; llvm::Value* args[2]; *fn = CreateIrFunctionPrototype(codegen, fn_name.str(), &args); llvm::Value* expr_ctx = args[0]; llvm::Value* row = args[1]; llvm::BasicBlock* block = llvm::BasicBlock::Create(codegen->context(), "entry", *fn); LlvmCodeGen::LlvmBuilder builder(block); // Populate UDF arguments vector<llvm::Value*> udf_args; // First argument is always FunctionContext*. // Index into our registered offset in the ExprContext. llvm::Value* expr_ctx_gep = builder.CreateStructGEP(expr_ctx, 1, "expr_ctx_gep"); llvm::Value* fn_ctxs_base = builder.CreateLoad(expr_ctx_gep, "fn_ctxs_base"); // Use GEP to add our index to the base pointer llvm::Value* fn_ctx_ptr = builder.CreateConstGEP1_32(fn_ctxs_base, context_index_, "fn_ctx_ptr"); llvm::Value* fn_ctx = builder.CreateLoad(fn_ctx_ptr, "fn_ctx"); udf_args.push_back(fn_ctx); // Get IR i8* pointer to varargs buffer from FunctionContext* argument // (if there are varargs) llvm::Value* varargs_buffer = NULL; if (vararg_start_idx_ != -1) { // FunctionContextImpl is first field of FunctionContext // fn_ctx_impl_ptr has type FunctionContextImpl** llvm::Value* fn_ctx_impl_ptr = builder.CreateStructGEP(fn_ctx, 0, "fn_ctx_impl_ptr"); llvm::Value* fn_ctx_impl = builder.CreateLoad(fn_ctx_impl_ptr, "fn_ctx_impl"); // varargs_buffer is first field of FunctionContextImpl // varargs_buffer_ptr has type i8** llvm::Value* varargs_buffer_ptr = builder.CreateStructGEP(fn_ctx_impl, 0, "varargs_buffer"); varargs_buffer = builder.CreateLoad(varargs_buffer_ptr); } // Tracks where to write the next vararg to int varargs_buffer_offset = 0; // Call children to populate remaining arguments for (int i = 0; i < GetNumChildren(); ++i) { llvm::Function* child_fn = NULL; vector<llvm::Value*> child_fn_args; if (state->codegen_enabled()) { // Set 'child_fn' to the codegen'd function, sets child_fn = NULL if codegen fails children_[i]->GetCodegendComputeFn(state, &child_fn); } if (child_fn == NULL) { // Set 'child_fn' to the interpreted function child_fn = GetStaticGetValWrapper(children_[i]->type(), codegen); // First argument to interpreted function is children_[i] llvm::Type* expr_ptr_type = codegen->GetPtrType(Expr::LLVM_CLASS_NAME); child_fn_args.push_back(codegen->CastPtrToLlvmPtr(expr_ptr_type, children_[i])); } child_fn_args.push_back(expr_ctx); child_fn_args.push_back(row); // Call 'child_fn', adding the result to either 'udf_args' or 'varargs_input_' DCHECK(child_fn != NULL); llvm::Type* arg_type = CodegenAnyVal::GetUnloweredType(codegen, children_[i]->type()); llvm::Value* arg_val_ptr; if (vararg_start_idx_ == -1 || i < vararg_start_idx_) { // Either no varargs or arguments before varargs begin. Allocate space to store // 'child_fn's result so we can pass the pointer to the UDF. arg_val_ptr = builder.CreateAlloca(arg_type, 0, "arg_val_ptr"); if (children_[i]->type().type == TYPE_DECIMAL) { // UDFs may manipulate DecimalVal arguments via SIMD instructions such as 'movaps' // that require 16-byte memory alignment. LLVM uses 8-byte alignment by default, // so explicitly set the alignment for DecimalVals. llvm::cast<llvm::AllocaInst>(arg_val_ptr)->setAlignment(16); } udf_args.push_back(arg_val_ptr); } else { // Store the result of 'child_fn' in varargs_buffer + varargs_buffer_offset arg_val_ptr = builder.CreateConstGEP1_32(varargs_buffer, varargs_buffer_offset, "arg_val_ptr"); varargs_buffer_offset += AnyValUtil::AnyValSize(children_[i]->type()); // Cast arg_val_ptr from i8* to AnyVal pointer type arg_val_ptr = builder.CreateBitCast(arg_val_ptr, arg_type->getPointerTo(), "arg_val_ptr"); } DCHECK_EQ(arg_val_ptr->getType(), arg_type->getPointerTo()); // The result of the call must be stored in a lowered AnyVal llvm::Value* lowered_arg_val_ptr = builder.CreateBitCast( arg_val_ptr, CodegenAnyVal::GetLoweredPtrType(codegen, children_[i]->type()), "lowered_arg_val_ptr"); CodegenAnyVal::CreateCall( codegen, &builder, child_fn, child_fn_args, "arg_val", lowered_arg_val_ptr); } if (vararg_start_idx_ != -1) { // We've added the FunctionContext argument plus any non-variadic arguments DCHECK_EQ(udf_args.size(), vararg_start_idx_ + 1); DCHECK_GE(GetNumChildren(), 1); // Add the number of varargs udf_args.push_back(codegen->GetIntConstant( TYPE_INT, GetNumChildren() - vararg_start_idx_)); // Add all the accumulated vararg inputs as one input argument. llvm::PointerType* vararg_type = codegen->GetPtrType( CodegenAnyVal::GetUnloweredType(codegen, children_.back()->type())); udf_args.push_back(builder.CreateBitCast(varargs_buffer, vararg_type, "varargs")); } // Call UDF llvm::Value* result_val = CodegenAnyVal::CreateCall(codegen, &builder, udf, udf_args, "result"); builder.CreateRet(result_val); *fn = codegen->FinalizeFunction(*fn); DCHECK(*fn != NULL); ir_compute_fn_ = *fn; return Status::OK; } Status ScalarFnCall::GetUdf(RuntimeState* state, llvm::Function** udf) { LlvmCodeGen* codegen = state->codegen(); DCHECK(codegen != NULL); // from_utc_timestamp and to_utc_timestamp have inline ASM that cannot be JIT'd. Always // use the statically compiled versions so the xcompiled versions are not included in // the final module to be JIT'd. // TODO: fix this if (fn_.binary_type == TFunctionBinaryType::NATIVE || (fn_.binary_type == TFunctionBinaryType::BUILTIN && (!state->codegen_enabled() || fn_.name.function_name == "from_utc_timestamp" || fn_.name.function_name == "to_utc_timestamp"))) { // In this path, we are code that has been statically compiled to assembly. // This can either be a UDF implemented in a .so or a builtin using the UDF // interface with the code in impalad. void* fn_ptr; Status status = LibCache::instance()->GetSoFunctionPtr( fn_.hdfs_location, fn_.scalar_fn.symbol, &fn_ptr, &cache_entry_); if (!status.ok() && fn_.binary_type == TFunctionBinaryType::BUILTIN) { // Builtins symbols should exist unless there is a version mismatch. stringstream ss; ss << "Builtin '" << fn_.name.function_name << "' with symbol '" << fn_.scalar_fn.symbol << "' does not exist. " << "Verify that all your impalads are the same version."; status.AddErrorMsg(ss.str()); } RETURN_IF_ERROR(status); DCHECK(fn_ptr != NULL); // Convert UDF function pointer to llvm::Function* // First generate the llvm::FunctionType* corresponding to the UDF. llvm::Type* return_type = CodegenAnyVal::GetLoweredType(codegen, type()); vector<llvm::Type*> arg_types; if (type().type == TYPE_DECIMAL) { // Per the x64 ABI, DecimalVals are returned via a DecmialVal* output argument return_type = codegen->void_type(); arg_types.push_back( codegen->GetPtrType(CodegenAnyVal::GetUnloweredType(codegen, type()))); } arg_types.push_back(codegen->GetPtrType("class.impala_udf::FunctionContext")); int num_fixed_args = vararg_start_idx_ >= 0 ? vararg_start_idx_ : children_.size(); for (int i = 0; i < num_fixed_args; ++i) { llvm::Type* arg_type = codegen->GetPtrType( CodegenAnyVal::GetUnloweredType(codegen, children_[i]->type())); arg_types.push_back(arg_type); } if (vararg_start_idx_ >= 0) { llvm::Type* vararg_type = CodegenAnyVal::GetUnloweredPtrType( codegen, children_[vararg_start_idx_]->type()); arg_types.push_back(codegen->GetType(TYPE_INT)); arg_types.push_back(vararg_type); } llvm::FunctionType* udf_type = llvm::FunctionType::get(return_type, arg_types, false); // Create a llvm::Function* with the generated type. This is only a function // declaration, not a definition, since we do not create any basic blocks or // instructions in it. *udf = llvm::Function::Create( udf_type, llvm::GlobalValue::ExternalLinkage, fn_.scalar_fn.symbol, codegen->module()); // Associate the dynamically loaded function pointer with the Function* we // defined. This tells LLVM where the compiled function definition is located in // memory. codegen->execution_engine()->addGlobalMapping(*udf, fn_ptr); } else if (fn_.binary_type == TFunctionBinaryType::BUILTIN) { // In this path, we're running a builtin with the UDF interface. The IR is // in the llvm module. DCHECK(state->codegen_enabled()); *udf = codegen->module()->getFunction(fn_.scalar_fn.symbol); if (*udf == NULL) { // Builtins symbols should exist unless there is a version mismatch. stringstream ss; ss << "Builtin '" << fn_.name.function_name << "' with symbol '" << fn_.scalar_fn.symbol << "' does not exist. " << "Verify that all your impalads are the same version."; return Status(ss.str()); } } else { // We're running a IR UDF. DCHECK_EQ(fn_.binary_type, TFunctionBinaryType::IR); *udf = codegen->module()->getFunction(fn_.scalar_fn.symbol); if (*udf == NULL) { stringstream ss; ss << "Unable to locate function " << fn_.scalar_fn.symbol << " from LLVM module " << fn_.hdfs_location; return Status(ss.str()); } } (*udf)->addFnAttr(llvm::Attribute::AlwaysInline); return Status::OK; } Status ScalarFnCall::GetFunction(RuntimeState* state, const string& symbol, void** fn) { if (fn_.binary_type == TFunctionBinaryType::NATIVE || fn_.binary_type == TFunctionBinaryType::BUILTIN) { return LibCache::instance()->GetSoFunctionPtr(fn_.hdfs_location, symbol, fn, &cache_entry_); } else { DCHECK_EQ(fn_.binary_type, TFunctionBinaryType::IR); DCHECK(state->codegen() != NULL); llvm::Function* ir_fn = state->codegen()->module()->getFunction(symbol); if (ir_fn == NULL) { stringstream ss; ss << "Unable to locate function " << symbol << " from LLVM module " << fn_.hdfs_location; return Status(ss.str()); } state->codegen()->AddFunctionToJit(ir_fn, fn); return Status::OK; } } void ScalarFnCall::EvaluateChildren(ExprContext* context, TupleRow* row, vector<AnyVal*>* input_vals) { DCHECK_EQ(input_vals->size(), children_.size()); for (int i = 0; i < input_vals->size(); ++i) { void* src_slot = context->GetValue(children_[i], row); AnyValUtil::SetAnyVal(src_slot, children_[i]->type(), (*input_vals)[i]); } } typedef BooleanVal (*BooleanWrapper)(ExprContext*, TupleRow*); typedef TinyIntVal (*TinyIntWrapper)(ExprContext*, TupleRow*); typedef SmallIntVal (*SmallIntWrapper)(ExprContext*, TupleRow*); typedef IntVal (*IntWrapper)(ExprContext*, TupleRow*); typedef BigIntVal (*BigIntWrapper)(ExprContext*, TupleRow*); typedef FloatVal (*FloatWrapper)(ExprContext*, TupleRow*); typedef DoubleVal (*DoubleWrapper)(ExprContext*, TupleRow*); typedef StringVal (*StringWrapper)(ExprContext*, TupleRow*); typedef TimestampVal (*TimestampWrapper)(ExprContext*, TupleRow*); typedef DecimalVal (*DecimalWrapper)(ExprContext*, TupleRow*); #define INTERPRET_SCALAR_FN(RETURN_TYPE) \ RETURN_TYPE ScalarFnCall::InterpretEval##RETURN_TYPE(\ ExprContext* context, TupleRow* row) {\ DCHECK(scalar_fn_ != NULL);\ FunctionContext* fn_ctx = context->fn_context(context_index_);\ vector<AnyVal*>* input_vals = fn_ctx->impl()->staging_input_vals();\ EvaluateChildren(context, row, input_vals); \ switch (children_.size()) {\ case 0:\ typedef RETURN_TYPE (*ScalarFn0)(FunctionContext*); \ return reinterpret_cast<ScalarFn0>(scalar_fn_)(fn_ctx);\ case 1:\ typedef RETURN_TYPE (*ScalarFn1)(FunctionContext*, const AnyVal& a1);\ return reinterpret_cast<ScalarFn1>(scalar_fn_)(fn_ctx,\ *(*input_vals)[0]);\ case 2:\ typedef RETURN_TYPE (*ScalarFn2)(FunctionContext*, const AnyVal& a1,\ const AnyVal& a2);\ return reinterpret_cast<ScalarFn2>(scalar_fn_)(fn_ctx,\ *(*input_vals)[0], *(*input_vals)[1]);\ case 3:\ typedef RETURN_TYPE (*ScalarFn3)(FunctionContext*, const AnyVal& a1,\ const AnyVal& a2, const AnyVal& a3);\ return reinterpret_cast<ScalarFn3>(scalar_fn_)(fn_ctx,\ *(*input_vals)[0], *(*input_vals)[1], *(*input_vals)[2]);\ default:\ DCHECK(false) << "Interpreted path not implemented. We should have "\ << "codegen'd the wrapper";\ }\ return RETURN_TYPE::null();\ } INTERPRET_SCALAR_FN(BooleanVal); INTERPRET_SCALAR_FN(TinyIntVal); INTERPRET_SCALAR_FN(SmallIntVal); INTERPRET_SCALAR_FN(IntVal); INTERPRET_SCALAR_FN(BigIntVal); INTERPRET_SCALAR_FN(FloatVal); INTERPRET_SCALAR_FN(DoubleVal); INTERPRET_SCALAR_FN(StringVal); INTERPRET_SCALAR_FN(TimestampVal); INTERPRET_SCALAR_FN(DecimalVal); // TODO: macroify this too? BooleanVal ScalarFnCall::GetBooleanVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_BOOLEAN); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalBooleanVal(context, row); BooleanWrapper fn = reinterpret_cast<BooleanWrapper>(scalar_fn_wrapper_); return fn(context, row); } TinyIntVal ScalarFnCall::GetTinyIntVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_TINYINT); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalTinyIntVal(context, row); TinyIntWrapper fn = reinterpret_cast<TinyIntWrapper>(scalar_fn_wrapper_); return fn(context, row); } SmallIntVal ScalarFnCall::GetSmallIntVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_SMALLINT); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalSmallIntVal(context, row); SmallIntWrapper fn = reinterpret_cast<SmallIntWrapper>(scalar_fn_wrapper_); return fn(context, row); } IntVal ScalarFnCall::GetIntVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_INT); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalIntVal(context, row); IntWrapper fn = reinterpret_cast<IntWrapper>(scalar_fn_wrapper_); return fn(context, row); } BigIntVal ScalarFnCall::GetBigIntVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_BIGINT); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalBigIntVal(context, row); BigIntWrapper fn = reinterpret_cast<BigIntWrapper>(scalar_fn_wrapper_); return fn(context, row); } FloatVal ScalarFnCall::GetFloatVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_FLOAT); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalFloatVal(context, row); FloatWrapper fn = reinterpret_cast<FloatWrapper>(scalar_fn_wrapper_); return fn(context, row); } DoubleVal ScalarFnCall::GetDoubleVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_DOUBLE); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalDoubleVal(context, row); DoubleWrapper fn = reinterpret_cast<DoubleWrapper>(scalar_fn_wrapper_); return fn(context, row); } StringVal ScalarFnCall::GetStringVal(ExprContext* context, TupleRow* row) { DCHECK(type_.IsStringType()); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalStringVal(context, row); StringWrapper fn = reinterpret_cast<StringWrapper>(scalar_fn_wrapper_); return fn(context, row); } TimestampVal ScalarFnCall::GetTimestampVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_TIMESTAMP); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalTimestampVal(context, row); TimestampWrapper fn = reinterpret_cast<TimestampWrapper>(scalar_fn_wrapper_); return fn(context, row); } DecimalVal ScalarFnCall::GetDecimalVal(ExprContext* context, TupleRow* row) { DCHECK_EQ(type_.type, TYPE_DECIMAL); DCHECK(context != NULL); if (scalar_fn_wrapper_ == NULL) return InterpretEvalDecimalVal(context, row); DecimalWrapper fn = reinterpret_cast<DecimalWrapper>(scalar_fn_wrapper_); return fn(context, row); } string ScalarFnCall::DebugString() const { stringstream out; out << "ScalarFnCall(udf_type=" << fn_.binary_type << " location=" << fn_.hdfs_location << " symbol_name=" << fn_.scalar_fn.symbol << Expr::DebugString() << ")"; return out.str(); }
42.786753
91
0.696621
AtScaleInc
10e40f27da46f99c1f3e04c0934a0e76a231753c
10,856
cc
C++
src/nfc/tags/tags_int.cc
stnfc/android-system-nfc
ee659f69beed15b31bc08a7283fb9a403430c1a9
[ "Apache-2.0" ]
null
null
null
src/nfc/tags/tags_int.cc
stnfc/android-system-nfc
ee659f69beed15b31bc08a7283fb9a403430c1a9
[ "Apache-2.0" ]
null
null
null
src/nfc/tags/tags_int.cc
stnfc/android-system-nfc
ee659f69beed15b31bc08a7283fb9a403430c1a9
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * Copyright (C) 2010-2014 Broadcom Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /****************************************************************************** * * This file contains the common data types shared by Reader/Writer mode * and Card Emulation. * ******************************************************************************/ #include "bt_types.h" #include "nfc_target.h" #include "rw_api.h" #include "rw_int.h" #define T1T_MAX_NUM_OPCODES 9 #define T1T_STATIC_OPCODES 5 #define T1T_MAX_TAG_MODELS 2 const tT1T_CMD_RSP_INFO t1t_cmd_rsp_infos[] = { /* Note: the order of these commands can not be changed. * If new events are added, add them after T1T_CMD_WRITE_NE8 */ /* opcode cmd_len, uid_offset, rsp_len */ {T1T_CMD_RID, 7, 3, 6}, {T1T_CMD_RALL, 7, 3, 122}, {T1T_CMD_READ, 7, 3, 2}, {T1T_CMD_WRITE_E, 7, 3, 2}, {T1T_CMD_WRITE_NE, 7, 3, 2}, {T1T_CMD_RSEG, 14, 10, 129}, {T1T_CMD_READ8, 14, 10, 9}, {T1T_CMD_WRITE_E8, 14, 10, 9}, {T1T_CMD_WRITE_NE8, 14, 10, 9}}; const tT1T_INIT_TAG t1t_init_content[] = { /* Tag Name CC3, is dynamic, ltv[0] ltv[1] ltv[2] mtv[0] mtv[1] mtv[2]*/ {RW_T1T_IS_TOPAZ96, 0x0E, FALSE, {0, 0, 0}, {0, 0, 0}}, {RW_T1T_IS_TOPAZ512, 0x3F, TRUE, {0xF2, 0x30, 0x33}, {0xF0, 0x02, 0x03}}}; #define T2T_MAX_NUM_OPCODES 3 #define T2T_MAX_TAG_MODELS 7 const tT2T_CMD_RSP_INFO t2t_cmd_rsp_infos[] = { /* Note: the order of these commands can not be changed. * If new events are added, add them after T2T_CMD_SEC_SEL */ /* opcode cmd_len, rsp_len, nack_rsp_len */ {T2T_CMD_READ, 2, 16, 1}, {T2T_CMD_WRITE, 6, 1, 1}, {T2T_CMD_SEC_SEL, 2, 1, 1}}; const tT2T_INIT_TAG t2t_init_content[] = { /* Tag Name is_multi_v Ver Block Ver No Vbitmask to_calc_cc CC3 OTP BLPB */ {TAG_MIFARE_MID, true, T2T_MIFARE_VERSION_BLOCK, T2T_MIFARE_ULTRALIGHT_VER_NO, 0xFFFF, false, 0x06, false, T2T_DEFAULT_LOCK_BLPB}, {TAG_MIFARE_MID, true, T2T_MIFARE_VERSION_BLOCK, T2T_MIFARE_ULTRALIGHT_FAMILY_VER_NO, 0xFFFF, true, 0x00, false, T2T_DEFAULT_LOCK_BLPB}, {TAG_KOVIO_MID, false, 0x00, 0x00, 0x0000, false, 0x1D, true, 0x04}, {TAG_INFINEON_MID, true, T2T_INFINEON_VERSION_BLOCK, T2T_INFINEON_MYD_MOVE_LEAN, 0xFFF0, false, 0x06, false, T2T_DEFAULT_LOCK_BLPB}, {TAG_INFINEON_MID, true, T2T_INFINEON_VERSION_BLOCK, T2T_INFINEON_MYD_MOVE, 0xFFF0, false, 0x10, false, T2T_DEFAULT_LOCK_BLPB}, {TAG_BRCM_MID, true, T2T_BRCM_VERSION_BLOCK, T2T_BRCM_STATIC_MEM, 0xFFFF, false, 0x06, false, T2T_DEFAULT_LOCK_BLPB}, {TAG_BRCM_MID, true, T2T_BRCM_VERSION_BLOCK, T2T_BRCM_DYNAMIC_MEM, 0xFFFF, false, 0x3C, false, T2T_DEFAULT_LOCK_BLPB} }; const uint8_t t4t_v10_ndef_tag_aid[T4T_V10_NDEF_TAG_AID_LEN] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x00}; const uint8_t t4t_v20_ndef_tag_aid[T4T_V20_NDEF_TAG_AID_LEN] = { 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01}; const char* const t1t_cmd_str[] = { "T1T_RID", "T1T_RALL", "T1T_READ", "T1T_WRITE_E", "T1T_WRITE_NE", "T1T_RSEG", "T1T_READ8", "T1T_WRITE_E8", "T1T_WRITE_NE8"}; const char* const t2t_cmd_str[] = {"T2T_CMD_READ", "T2T_CMD_WRITE", "T2T_CMD_SEC_SEL"}; static unsigned int tags_ones32(unsigned int x); /******************************************************************************* ** ** Function t1t_cmd_to_rsp_info ** ** Description This function maps the given opcode to tT1T_CMD_RSP_INFO. ** ** Returns tNFC_STATUS ** *******************************************************************************/ const tT1T_CMD_RSP_INFO* t1t_cmd_to_rsp_info(uint8_t opcode) { const tT1T_CMD_RSP_INFO *p_ret = nullptr, *p; int xx; for (xx = 0, p = &t1t_cmd_rsp_infos[0]; xx < T1T_MAX_NUM_OPCODES; xx++, p++) { if (opcode == p->opcode) { if ((xx < T1T_STATIC_OPCODES) || (rw_cb.tcb.t1t.hr[0] != T1T_STATIC_HR0)) p_ret = p; break; } } return p_ret; } /******************************************************************************* ** ** Function t1t_tag_init_data ** ** Description This function maps the given opcode to tT1T_INIT_TAG. ** ** Returns tNFC_STATUS ** *******************************************************************************/ const tT1T_INIT_TAG* t1t_tag_init_data(uint8_t tag_model) { const tT1T_INIT_TAG *p_ret = nullptr, *p; int xx; for (xx = 0, p = &t1t_init_content[0]; xx < T1T_MAX_TAG_MODELS; xx++, p++) { if (tag_model == p->tag_model) { p_ret = p; break; } } return p_ret; } /******************************************************************************* ** ** Function t2t_tag_init_data ** ** Description This function maps the given manufacturer id and version to ** tT2T_INIT_TAG. ** ** Returns tNFC_STATUS ** *******************************************************************************/ const tT2T_INIT_TAG* t2t_tag_init_data(uint8_t manufacturer_id, bool b_valid_ver, uint16_t version_no) { const tT2T_INIT_TAG *p_ret = nullptr, *p; int xx; for (xx = 0, p = &t2t_init_content[0]; xx < T2T_MAX_TAG_MODELS; xx++, p++) { if (manufacturer_id == p->manufacturer_id) { if ((!p->b_multi_version) || (!b_valid_ver) || (p->version_no == (version_no & p->version_bmask))) { p_ret = p; break; } } } return p_ret; } /******************************************************************************* ** ** Function t2t_cmd_to_rsp_info ** ** Description This function maps the given opcode to tT2T_CMD_RSP_INFO. ** ** Returns tNFC_STATUS ** *******************************************************************************/ const tT2T_CMD_RSP_INFO* t2t_cmd_to_rsp_info(uint8_t opcode) { const tT2T_CMD_RSP_INFO *p_ret = nullptr, *p; int xx; for (xx = 0, p = &t2t_cmd_rsp_infos[0]; xx < T2T_MAX_NUM_OPCODES; xx++, p++) { if (opcode == p->opcode) { p_ret = p; break; } } return p_ret; } /******************************************************************************* ** ** Function t1t_info_to_evt ** ** Description This function maps the given tT1T_CMD_RSP_INFO to RW/CE ** event code ** ** Returns RW/CE event code ** *******************************************************************************/ uint8_t t1t_info_to_evt(const tT1T_CMD_RSP_INFO* p_info) { return ((uint8_t)(p_info - t1t_cmd_rsp_infos) + RW_T1T_FIRST_EVT); } /******************************************************************************* ** ** Function t2t_info_to_evt ** ** Description This function maps the given tT2T_CMD_RSP_INFO to RW/CE ** event code ** ** Returns RW/CE event code ** *******************************************************************************/ uint8_t t2t_info_to_evt(const tT2T_CMD_RSP_INFO* p_info) { return ((uint8_t)(p_info - t2t_cmd_rsp_infos) + RW_T2T_FIRST_EVT); } /******************************************************************************* ** ** Function t1t_info_to_str ** ** Description This function maps the given tT1T_CMD_RSP_INFO to T1T cmd ** str ** ** Returns T1T cmd str ** *******************************************************************************/ const char* t1t_info_to_str(const tT1T_CMD_RSP_INFO* p_info) { int ind = (int)(p_info - t1t_cmd_rsp_infos); if (ind < T1T_MAX_NUM_OPCODES) return (const char*)t1t_cmd_str[ind]; else return ""; } /******************************************************************************* ** ** Function t2t_info_to_str ** ** Description This function maps the given tT2T_CMD_RSP_INFO to T2T cmd ** str ** ** Returns T2T cmd str ** *******************************************************************************/ const char* t2t_info_to_str(const tT2T_CMD_RSP_INFO* p_info) { int ind = (int)(p_info - t2t_cmd_rsp_infos); if (ind < T2T_MAX_NUM_OPCODES) return (const char*)t2t_cmd_str[ind]; else return ""; } /******************************************************************************* ** ** Function tags_pow ** ** Description This function calculates x(base) power of y. ** ** Returns int ** *******************************************************************************/ int tags_pow(int x, int y) { int i, ret = 1; for (i = 0; i < y; i++) { ret *= x; } return ret; } /******************************************************************************* ** ** Function ones32 ** ** Description This function returns number of bits set in an unsigned ** integer variable ** ** Returns int ** *******************************************************************************/ static unsigned int tags_ones32(unsigned int x) { /* 32-bit recursive reduction using SWAR... but first step is mapping 2-bit values into sum of 2 1-bit values in sneaky way */ x -= ((x >> 1) & 0x55555555); x = (((x >> 2) & 0x33333333) + (x & 0x33333333)); x = (((x >> 4) + x) & 0x0f0f0f0f); x += (x >> 8); x += (x >> 16); return (x & 0x0000003f); } /******************************************************************************* ** ** Function tags_log2 ** ** Description This function calculates log to the base 2. ** ** Returns int ** *******************************************************************************/ unsigned int tags_log2(unsigned int x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return (tags_ones32(x) - 1); }
34.138365
81
0.494749
stnfc
10eaed4fcb6f417e0d2208c7552c84365d5f32a0
6,111
hpp
C++
extension/parquet/include/thrift_tools.hpp
hannes/duckdb
4a24d71edecc7c0018eb3860d2e104cfe90462b6
[ "MIT" ]
null
null
null
extension/parquet/include/thrift_tools.hpp
hannes/duckdb
4a24d71edecc7c0018eb3860d2e104cfe90462b6
[ "MIT" ]
null
null
null
extension/parquet/include/thrift_tools.hpp
hannes/duckdb
4a24d71edecc7c0018eb3860d2e104cfe90462b6
[ "MIT" ]
null
null
null
#pragma once #include <list> #include "thrift/protocol/TCompactProtocol.h" #include "thrift/transport/TBufferTransports.h" #include "duckdb.hpp" #ifndef DUCKDB_AMALGAMATION #include "duckdb/common/file_system.hpp" #include "duckdb/common/allocator.hpp" #endif namespace duckdb { // A ReadHead for prefetching data in a specific range struct ReadHead { ReadHead(idx_t location, uint64_t size) : location(location), size(size) {}; // Hint info idx_t location; uint64_t size; // Current info unique_ptr<AllocatedData> data; bool data_isset = false; idx_t GetEnd() const { return size + location; } void Allocate(Allocator &allocator) { data = allocator.Allocate(size); } }; // Comparator for ReadHeads that are either overlapping, adjacent, or within ALLOW_GAP bytes from each other struct ReadHeadComparator { static constexpr uint64_t ALLOW_GAP = 1 << 14; // 16 KiB bool operator()(const ReadHead *a, const ReadHead *b) const { auto a_start = a->location; auto a_end = a->location + a->size; auto b_start = b->location; if (a_end <= NumericLimits<idx_t>::Maximum() - ALLOW_GAP) { a_end += ALLOW_GAP; } return a_start < b_start && a_end < b_start; } }; // Two-step read ahead buffer // 1: register all ranges that will be read, merging ranges that are consecutive // 2: prefetch all registered ranges struct ReadAheadBuffer { ReadAheadBuffer(Allocator &allocator, FileHandle &handle, FileOpener &opener) : allocator(allocator), handle(handle), file_opener(opener) { } // The list of read heads std::list<ReadHead> read_heads; // Set for merging consecutive ranges std::set<ReadHead *, ReadHeadComparator> merge_set; Allocator &allocator; FileHandle &handle; FileOpener &file_opener; idx_t total_size = 0; // Add a read head to the prefetching list void AddReadHead(idx_t pos, uint64_t len, bool merge_buffers = true) { // Attempt to merge with existing if (merge_buffers) { ReadHead new_read_head {pos, len}; auto lookup_set = merge_set.find(&new_read_head); if (lookup_set != merge_set.end()) { auto existing_head = *lookup_set; auto new_start = MinValue<idx_t>(existing_head->location, new_read_head.location); auto new_length = MaxValue<idx_t>(existing_head->GetEnd(), new_read_head.GetEnd()) - new_start; existing_head->location = new_start; existing_head->size = new_length; return; } } read_heads.emplace_front(ReadHead(pos, len)); total_size += len; auto &read_head = read_heads.front(); if (merge_buffers) { merge_set.insert(&read_head); } if (read_head.GetEnd() > handle.GetFileSize()) { throw std::runtime_error("Prefetch registered for bytes outside file"); } } // Returns the relevant read head ReadHead *GetReadHead(idx_t pos) { for (auto &read_head : read_heads) { if (pos >= read_head.location && pos < read_head.GetEnd()) { return &read_head; } } return nullptr; } // Prefetch all read heads void Prefetch() { for (auto &read_head : read_heads) { read_head.Allocate(allocator); if (read_head.GetEnd() > handle.GetFileSize()) { throw std::runtime_error("Prefetch registered requested for bytes outside file"); } handle.Read(read_head.data->get(), read_head.size, read_head.location); read_head.data_isset = true; } } }; class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTransport<ThriftFileTransport> { public: static constexpr uint64_t PREFETCH_FALLBACK_BUFFERSIZE = 1000000; ThriftFileTransport(Allocator &allocator, FileHandle &handle_p, FileOpener &opener, bool prefetch_mode_p) : handle(handle_p), location(0), allocator(allocator), ra_buffer(ReadAheadBuffer(allocator, handle_p, opener)), prefetch_mode(prefetch_mode_p) { } uint32_t read(uint8_t *buf, uint32_t len) { auto prefetch_buffer = ra_buffer.GetReadHead(location); if (prefetch_buffer != nullptr && location - prefetch_buffer->location + len <= prefetch_buffer->size) { D_ASSERT(location - prefetch_buffer->location + len <= prefetch_buffer->size); if (!prefetch_buffer->data_isset) { prefetch_buffer->Allocate(allocator); handle.Read(prefetch_buffer->data->get(), prefetch_buffer->size, prefetch_buffer->location); prefetch_buffer->data_isset = true; } memcpy(buf, prefetch_buffer->data->get() + location - prefetch_buffer->location, len); } else { if (prefetch_mode && len < PREFETCH_FALLBACK_BUFFERSIZE && len > 0) { Prefetch(location, MinValue<uint64_t>(PREFETCH_FALLBACK_BUFFERSIZE, handle.GetFileSize() - location)); auto prefetch_buffer_fallback = ra_buffer.GetReadHead(location); D_ASSERT(location - prefetch_buffer_fallback->location + len <= prefetch_buffer_fallback->size); memcpy(buf, prefetch_buffer_fallback->data->get() + location - prefetch_buffer_fallback->location, len); } else { handle.Read(buf, len, location); } } location += len; return len; } // Prefetch a single buffer void Prefetch(idx_t pos, uint64_t len) { RegisterPrefetch(pos, len, false); FinalizeRegistration(); PrefetchRegistered(); } // Register a buffer for prefixing void RegisterPrefetch(idx_t pos, uint64_t len, bool can_merge = true) { ra_buffer.AddReadHead(pos, len, can_merge); } // Prevents any further merges, should be called before PrefetchRegistered void FinalizeRegistration() { ra_buffer.merge_set.clear(); } // Prefetch all previously registered ranges void PrefetchRegistered() { ra_buffer.Prefetch(); } void ClearPrefetch() { ra_buffer.read_heads.clear(); ra_buffer.merge_set.clear(); } void SetLocation(idx_t location_p) { location = location_p; } idx_t GetLocation() { return location; } idx_t GetSize() { return handle.file_system.GetFileSize(handle); } private: FileHandle &handle; idx_t location; Allocator &allocator; // Multi-buffer prefetch ReadAheadBuffer ra_buffer; // Whether the prefetch mode is enabled. In this mode the DirectIO flag of the handle will be set and the parquet // reader will manage the read buffering. bool prefetch_mode; }; } // namespace duckdb
29.1
116
0.727377
hannes
10eff848446dd52b65ad267dfb5b9e40a5bd8131
16,275
hpp
C++
packages/utility/archive/src/Utility_HDF5OArchiveImpl_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/archive/src/Utility_HDF5OArchiveImpl_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/archive/src/Utility_HDF5OArchiveImpl_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_HDF5OArchiveImpl_def.hpp //! \author Alex Robinson //! \brief HDF5 output archive implementation class definition //! //---------------------------------------------------------------------------// #ifndef UTILITY_HDF5_OARCHIVE_IMPL_DEF_HPP #define UTILITY_HDF5_OARCHIVE_IMPL_DEF_HPP // Std Lib Includes #include <sstream> // FRENSIE Includes #include "Utility_TypeNameTraits.hpp" #include "Utility_LoggingMacros.hpp" #include "Utility_DesignByContract.hpp" namespace Utility{ // Constructor template<typename Archive> HDF5OArchiveImpl<Archive>::HDF5OArchiveImpl( const std::string& hdf5_filename, unsigned flags ) : boost::archive::detail::common_oarchive<Archive>( flags ), HDF5CommonArchive( hdf5_filename, ((flags & HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE) ? HDF5File::OVERWRITE : HDF5File::READ_WRITE ) ), d_object_count( 0 ), d_group_count( 0 ), d_group_stack(), d_next_object_is_attribute( false ) { this->init( flags ); } // Initialize the archive template<typename Archive> void HDF5OArchiveImpl<Archive>::init( unsigned flags ) { // Add a header to the archive if( !(flags & boost::archive::no_header ) ) { try{ this->writeToGroupAttribute( this->getPropertiesDir(), this->getSignatureAttributeName(), std::string(boost::archive::BOOST_ARCHIVE_SIGNATURE()) ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "The archive signature could not be " "set in hdf5 archive " << this->getFilename() << "!" ); try{ this->writeToGroupAttribute<unsigned>( this->getPropertiesDir(), this->getVersionAttributeName(), boost::archive::BOOST_ARCHIVE_VERSION() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "The archive version could not be set " "in hdf5 archive " << this->getFilename() << "!" ); } // Create the group that will contain all serialized data this->createGroup( this->getDataDir() ); // Create the group that will contain links to tracked objects this->createGroup( this->getTrackedObjectsDir() ); // Create the group that will contain the hierarchical information // associated with the serialized objects this->createGroup( this->getTreeDir() ); } // Save opaque object template<typename Archive> inline void HDF5OArchiveImpl<Archive>::save_binary( const void* address, std::size_t count ) { this->saveImpl( address, count ); } #ifdef BOOST_SERIALIZATION_ARRAY_WRAPPER_AVAILABLE // Save an array template<typename Archive> template<typename ValueType> inline void HDF5OArchiveImpl<Archive>::save_array( const boost::serialization::array_wrapper<ValueType>& a, unsigned int ) { this->saveImpl( a.address(), a.count() ); } #endif // Start a save template<typename Archive> void HDF5OArchiveImpl<Archive>::save_start( const char* name ) { // if( name ) // { // FRENSIE_LOG_TAGGED_NOTIFICATION( name, "started" ); // } this->startHDF5Group( name ); } // Finish a save template<typename Archive> void HDF5OArchiveImpl<Archive>::save_end( const char* name ) { // if( name ) // { // FRENSIE_LOG_TAGGED_NOTIFICATION( name, "finished" ); // } this->endHDF5Group(); } // Intercept any type that is not a name-value pair or an attribute here /*! \details This method should never be called as it will cause a compilation * error (by design). To avoid this method, only serialize your types using * the boost::serialization::nvp wrapper. */ template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::save_override( const T& t, int ) { testStaticPrecondition((boost::serialization::is_wrapper<T>::type::value)); // This should never be called #ifdef USE_OLD_BOOST_ARCHIVE_OVERRIDE this->CommonOArchive::save_override( t, 0 ); #else this->CommonOArchive::save_override( t ); #endif } // Save a type that is wrapped in a boost::serialization::nvp template<typename Archive> template<typename T> inline void HDF5OArchiveImpl<Archive>::save_override( const boost::serialization::nvp<T>& t, int ) { this->save_start( t.name() ); this->saveIntercept(t.const_value(), typename std::conditional<IsTuple<T>::value && Utility::HDF5TypeTraits<T>::IsSpecialized::value,std::true_type,std::false_type>::type()); this->save_end( t.name() ); } // Save a boost::archive::object_id_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::object_id_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "object id type: " ); unsigned object_id = t; this->writeToCurrentGroupAttribute( "object_id", &object_id, 1 ); this->linkTrackedObject( object_id ); d_next_object_is_attribute = true; this->save( object_id ); } // Save a boost::archive::object_reference_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::object_reference_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "object reference type: " ); unsigned object_reference = t; this->writeToCurrentGroupAttribute( "object_reference", &object_reference, 1 ); this->linkTrackedObjectReference( object_reference ); d_next_object_is_attribute = true; this->save( object_reference ); } // Save a boost::archive::version_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::version_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "version type: " ); unsigned version = t; this->writeToCurrentGroupAttribute( "version", &version, 1 ); d_next_object_is_attribute = true; this->save( version ); } // Save a boost::archive::class_id_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_id_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "class id type: " ); size_t class_id = t; this->writeToCurrentGroupAttribute( "class_id", &class_id, 1 ); d_next_object_is_attribute = true; this->save( class_id ); } // Save a boost::archive::class_id_optional_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_id_optional_type& t, int ) { // Ignore the writing of this type - it is not needed by this archive type // Note: this implementation of this method is similar to the implementation // of the equivalent method for other archive types. #if 0 size_t class_id_optional = t; this->writeToCurrentGroupAttribute( "class_id_optional", &class_id_optional, 1 ); d_next_object_is_attribute = true; this->save( class_id_optional ); #endif } // Save a boost::archive::class_id_reference_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_id_reference_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "class id reference type: " ); size_t class_id_reference = t; this->writeToCurrentGroupAttribute( "class_id_reference", &class_id_reference, 1 ); d_next_object_is_attribute = true; this->save( class_id_reference ); } // Save a boost::archive::class_name_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_name_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "class name type: " ); const std::string class_name( t ); this->writeToCurrentGroupAttribute( "class_name", &class_name, 1 ); d_next_object_is_attribute = true; this->save( class_name ); } // Save a boost::archive::tracking_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::tracking_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "tracking type: " ); this->writeToCurrentGroupAttribute( "class_tracking", &t.t, 1 ); d_next_object_is_attribute = true; this->save( t.t ); } // Save any type with a Utility::HDF5TypeTraits specialization template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::save( const T& t ) { this->saveImpl( &t, 1 ); } // Save a wide string template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const wchar_t& t ) { THROW_HDF5_ARCHIVE_EXCEPTION( "Wide chars are not currently supported!" ); } // Save a wide string template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const std::wstring& t ) { THROW_HDF5_ARCHIVE_EXCEPTION( "Wide strings are not currently supported!" ); } // Save a boost::serialization::collection_size_type template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const boost::serialization::collection_size_type& t ) { size_t collection_size = t; this->save( collection_size ); } // Save a boost::serialization::item_version_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const boost::serialization::item_version_type& t ) { unsigned version = t; this->save( version ); } // Write to current group attribute template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::writeToCurrentGroupAttribute( const std::string& attribute_name, const T* const data, const size_t size ) { std::ostringstream full_attribute_name; full_attribute_name << attribute_name << "_d" << d_object_count; try{ this->writeToGroupAttribute( this->getTreeObjectPath(), full_attribute_name.str(), data, size ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not write data to group attribute " << this->getTreeObjectPath() << ":" << full_attribute_name.str() << "!" ); } // Intercept a type that is about to be saved template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveIntercept( const T& t, std::true_type is_fast_serializable_tuple ) { this->save(t); } // Intercept a type that is about to be saved template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveIntercept( const T& t, std::false_type is_fast_serializable_tuple ) { #if USE_OLD_BOOST_ARCHIVE_OVERRIDE this->CommonOArchive::save_override( t, 0 ); #else this->CommonOArchive::save_override( t ); #endif } // Save implementation template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveImpl( const T* data, size_t count ) { try{ this->saveImpl( this->getObjectDataPath( d_object_count ), data, count ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not save data for primitive " "object " << d_object_count << " of type " << Utility::typeName<T>() << "!" ); } // Save implementation (object data set path already determined) template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveImpl( const std::string& object_data_set_path, const T* data, size_t count ) { //FRENSIE_LOG_NOTIFICATION( object_data_set_path << " (" << Utility::typeName<T>() << ")" ); this->writeToDataSet( object_data_set_path, data, count ); this->linkDataAndUpdateObjectCount(); } // Save container implementation template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveContainerImpl( const T& container ) { std::string object_data_set_path = this->getObjectDataPath( d_object_count ); try{ this->saveImpl( object_data_set_path, container.data(), container.size() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not save data for container " "object " << d_object_count << " of type " << Utility::typeName<T>() << "!" ); } // Start an hdf5 group template<typename Archive> void HDF5OArchiveImpl<Archive>::startHDF5Group( const char* group_name ) { std::ostringstream full_group_name; if( group_name == NULL ) full_group_name << "_g" << d_group_count; else full_group_name << group_name << "_g" << d_group_count; d_group_stack.push_back( full_group_name.str() ); this->createGroup( this->getTreeObjectPath() ); ++d_group_count; } // End an hdf5 group template<typename Archive> void HDF5OArchiveImpl<Archive>::endHDF5Group() { d_group_stack.pop_back(); } // Get the tree object path template<typename Archive> std::string HDF5OArchiveImpl<Archive>::getTreeObjectPath() const { std::ostringstream oss; oss << this->getTreeDir(); GroupStack::const_iterator it = d_group_stack.begin(); GroupStack::const_iterator end = d_group_stack.end(); while( it != end ) { oss << "/" << *it; ++it; } return oss.str(); } // Link the data object template<typename Archive> void HDF5OArchiveImpl<Archive>::linkDataObject() { if( !d_next_object_is_attribute ) { std::ostringstream link_path; link_path << this->getTreeObjectPath() << "/<data>_d" << d_object_count; const std::string object_path = this->getObjectDataPath( d_object_count ); try{ this->createHardLink( object_path, link_path.str() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not create a link with path " << link_path.str() << " to data object " << d_object_count << " at " << object_path << "!" ); } d_next_object_is_attribute = false; } // Link the tracked object template<typename Archive> void HDF5OArchiveImpl<Archive>::linkTrackedObject( unsigned object ) { const std::string link_path = this->getTrackedObjectsPath( object ); const std::string object_path = this->getTreeObjectPath(); try{ this->createSoftLink( object_path, link_path ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not create a link with path " << link_path << " to data object " << object << " at " << object_path << "!" ); } // Link the tracked object reference template<typename Archive> void HDF5OArchiveImpl<Archive>::linkTrackedObjectReference( unsigned object_reference ) { std::ostringstream link_path; link_path << this->getTreeObjectPath() << "/<reference>_o" << object_reference; const std::string object_path = this->getTrackedObjectsPath( object_reference ); try{ this->createSoftLink( object_path, link_path.str() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not create a link with path " << link_path.str() << " to data object " << object_reference << " at " << object_path << "!" ); } // Link the data and update the object count template<typename Archive> void HDF5OArchiveImpl<Archive>::linkDataAndUpdateObjectCount() { this->linkDataObject(); ++d_object_count; } } // end Utility namespace #endif // end UTILITY_HDF5_OARCHIVE_IMPL_DEF_HPP //---------------------------------------------------------------------------// // end Utility_HDF5OArchiveImpl_def.hpp //---------------------------------------------------------------------------//
31.97446
176
0.642949
bam241
10f15782ea2570fc6051f928fb71ea4138daae6e
3,921
cpp
C++
src/c3d/flats.cpp
tingelst/pyversor
b5545619bb1b4089803251098c4038d3ef16aac3
[ "BSD-3-Clause" ]
13
2017-11-02T19:44:08.000Z
2021-02-07T21:04:03.000Z
src/c3d/flats.cpp
tingelst/pyversor
b5545619bb1b4089803251098c4038d3ef16aac3
[ "BSD-3-Clause" ]
5
2017-10-26T07:56:24.000Z
2017-11-08T15:36:27.000Z
src/c3d/flats.cpp
tingelst/pyversor
b5545619bb1b4089803251098c4038d3ef16aac3
[ "BSD-3-Clause" ]
3
2017-09-27T12:23:11.000Z
2020-05-24T19:13:49.000Z
// Copyright (c) 2015, Lars Tingelstad // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of pyversor 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 HOLDER 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 <pyversor/c3d/flats.h> namespace pyversor { namespace c3d { void def_flats(py::module &m) { auto flats = m.def_submodule("flats"); def_flat_point(flats); def_dual_line(flats); def_line(flats); def_dual_plane(flats); def_plane(flats); } void def_flat_point(py::module &m) { auto flp = def_multivector<c3d::flat_point_t>(m, "FlatPoint"); flp.def(py::init<double, double, double, double>()); flp.def(py::init([](const c3d::point_t &p) { return new c3d::flat_point_t(p.null() ^ c3d::infinity_t(1.0)); })); flp.def("spinv", [](const c3d::flat_point_t &p, const c3d::motor_t &m) { return c3d::flat_point_t(m * p * !m); }); def_sandwich_product<c3d::flat_point_t, c3d::motor_t>(flp); // def_geometric_product<c3d::flat_point_t, c3d::flat_point_t>(flp); } void def_dual_line(py::module &m) { auto dll = def_multivector<c3d::dual_line_t>(m, "DualLine"); dll.def(py::init<double, double, double, double, double, double>()); def_geometric_product<c3d::dual_line_t, c3d::dual_line_t>(dll); def_geometric_product<c3d::dual_line_t, c3d::motor_t>(dll); def_addition<c3d::dual_line_t, c3d::motor_t>(dll); def_sandwich_product<c3d::dual_line_t, c3d::motor_t>(dll); } void def_line(py::module &m) { auto lin = def_multivector<c3d::line_t>(m, "Line"); lin.def(py::init<double, double, double, double, double, double>()); lin.def(py::init([](const c3d::point_t &p, const c3d::point_t &q) { return new c3d::line_t(p.null() ^ q.null() ^ c3d::infinity_t(1.0)); })); def_geometric_product<c3d::line_t, c3d::line_t>(lin); def_sandwich_product<c3d::line_t, c3d::motor_t>(lin); } void def_dual_plane(py::module &m) { auto dlp = def_multivector<c3d::dual_plane_t>(m, "DualPlane"); dlp.def(py::init<double, double, double, double>()); def_geometric_product<c3d::dual_plane_t, c3d::dual_plane_t, motor_t>(dlp); } void def_plane(py::module &m) { auto pln = def_multivector<c3d::plane_t>(m, "Plane"); pln.def(py::init( [](const c3d::point_t &p, const c3d::point_t &q, const c3d::point_t &r) { return new c3d::plane_t(p.null() ^ q.null() ^ r.null() ^ c3d::infinity_t(1.0)); })); pln.def(py::init<double, double, double, double>()); def_geometric_product<c3d::plane_t, c3d::plane_t, motor_t>(pln); } } // namespace c3d } // namespace pyversor
40.42268
80
0.709258
tingelst
10f1a471a36c3904f10641621de29965b79e4415
553
cpp
C++
source/RTTR.cpp
xzrunner/js
4d1387c8561884c585dd86e4e0f21885eeada1ec
[ "MIT" ]
null
null
null
source/RTTR.cpp
xzrunner/js
4d1387c8561884c585dd86e4e0f21885eeada1ec
[ "MIT" ]
null
null
null
source/RTTR.cpp
xzrunner/js
4d1387c8561884c585dd86e4e0f21885eeada1ec
[ "MIT" ]
null
null
null
#include "js/RTTR.h" namespace detail { extern std::string rttr_to_rapidjson(rttr::instance obj, const std::string& dir_path); extern bool rttr_from_rapidjson(const std::string& json, const std::string& dir_path, rttr::instance obj); } namespace js { std::string RTTR::ToRapidJson(rttr::instance obj, const std::string& dir_path) { return detail::rttr_to_rapidjson(obj, dir_path); } bool RTTR::FromRapidJson(const std::string& json, const std::string& dir_path, rttr::instance obj) { return detail::rttr_from_rapidjson(json, dir_path, obj); } }
23.041667
106
0.75226
xzrunner
10f40c81e8745dbd133d965258c2b4484ef30fc1
2,630
cpp
C++
src/tools/loop_stats/src/LoopStats_InductionVariables.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
null
null
null
src/tools/loop_stats/src/LoopStats_InductionVariables.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
null
null
null
src/tools/loop_stats/src/LoopStats_InductionVariables.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
null
null
null
/* * Copyright 2019 - 2020 Angelo Matni, Simone Campanoni * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "LoopStats.hpp" using namespace llvm; using namespace llvm::noelle; void LoopStats::collectStatsOnNoelleIVs (Hot *profiles, LoopDependenceInfo &LDI, Stats *statsForLoop) { auto loopStructure = LDI.getLoopStructure(); auto ivManager = LDI.getInductionVariableManager(); auto ivs = ivManager->getInductionVariables(*loopStructure); statsForLoop->numberOfIVs = ivs.size(); for (auto iv : ivs) { auto phiNode = iv->getLoopEntryPHI(); statsForLoop->numberOfDynamicIVs += profiles->getTotalInstructions(phiNode); } auto GIV = ivManager->getLoopGoverningIVAttribution(*loopStructure); if (GIV != nullptr){ statsForLoop->isGovernedByIV = 1; statsForLoop->numberOfDynamicGovernedIVs = profiles->getTotalInstructions(GIV->getHeaderCmpInst()); } return ; } void LoopStats::collectStatsOnLLVMIVs (Hot *profiles, ScalarEvolution &SE, Loop &llvmLoop, Stats *statsForLoop) { /* * Note: LLVM does not provide a way to collect all instructions used in computing IVs */ for (auto &phi : llvmLoop.getHeader()->phis()) { bool llvmLoopValidForInductionAnalysis = phi.getBasicBlockIndex(llvmLoop.getLoopPreheader()) >= 0; if (llvmLoopValidForInductionAnalysis && llvmLoop.isAuxiliaryInductionVariable(phi, SE)) { statsForLoop->numberOfIVs++; } statsForLoop->numberOfDynamicIVs = profiles->getTotalInstructions(&phi); } auto governingIV = llvmLoop.getInductionVariable(SE); if (governingIV != nullptr){ statsForLoop->isGovernedByIV = 1; } return ; }
46.964286
435
0.759696
SusanTan
10f460bc04429615e6004d0f6d8cb1abab0a3164
1,909
cpp
C++
server/TestServer/database.cpp
Gmadges/major-project
747495616b320c46918589abdc753f106ba36f0b
[ "MIT" ]
null
null
null
server/TestServer/database.cpp
Gmadges/major-project
747495616b320c46918589abdc753f106ba36f0b
[ "MIT" ]
null
null
null
server/TestServer/database.cpp
Gmadges/major-project
747495616b320c46918589abdc753f106ba36f0b
[ "MIT" ]
null
null
null
#include "database.h" #include <fstream> Database::Database() { std::ifstream dbfile("database.json"); if (dbfile.is_open()) { dbfile >> db; } } Database::~Database() { } bool Database::putMesh(json& _mesh) { // lock std::lock_guard<std::mutex> lock(mut); if (_mesh.count("id") > 0) { std::string id = _mesh["id"]; std::cout << "storing: " << id << std::endl; _mesh["db_time"] = std::time(nullptr); json object; object["mesh"] = _mesh; object["edits"] = std::vector<json>(); db[id] = object; storeDBToFile(); return true; } return false; } json Database::getMesh(std::string& _id) { if (db.count(_id) > 0) { if (db[_id].count("mesh") > 0) { return db[_id]["mesh"]; } } return json(); } json Database::getMeshWithEdits(std::string& _id) { if (db.count(_id) > 0) { return db[_id]; } return json(); } std::vector<json> Database::getMeshEdits(std::string& _id) { try { if (db.count(_id) > 0) { if (db[_id].count("edits") > 0) { return db[_id]["edits"].get<std::vector<json>>(); } } } catch (std::exception& e) { std::cout << e.what(); } return std::vector<json>(); } bool Database::putMeshWithEdits(json& _object) { // lock std::lock_guard<std::mutex> lock(mut); if (_object["mesh"].count("id") > 0) { std::string id = _object["mesh"]["id"]; std::cout << "storing: " << id << std::endl; // lets timestamp the last entry to the db _object["edits"].back()["db_time"] = std::time(nullptr); db[id] = _object; storeDBToFile(); return true; } return false; } json Database::getAllMeshes() { return db; } void Database::storeDBToFile() { std::ofstream outputFile("database.json"); outputFile << std::setw(4) << db << std::endl; outputFile.close(); } bool Database::deleteMesh(std::string& id) { if (db.count(id) > 0) { db.erase(id); storeDBToFile(); return true; } return false; }
14.684615
58
0.598219
Gmadges
10f491ead11c97c3bec0a5dbf3c1c72f4db6b4bb
763
cpp
C++
Source/Core/TornadoEngine/Components/Logic/ObjectInstanceEndHandlerBuilderSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
27
2015-01-08T08:26:29.000Z
2019-02-10T03:18:05.000Z
Source/Core/TornadoEngine/Components/Logic/ObjectInstanceEndHandlerBuilderSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
1
2017-04-05T02:02:14.000Z
2017-04-05T02:02:14.000Z
Source/Core/TornadoEngine/Components/Logic/ObjectInstanceEndHandlerBuilderSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
17
2015-01-18T02:50:01.000Z
2019-02-08T21:00:53.000Z
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information LICENSE.md. */ #include "ObjectInstanceEndHandlerBuilderSystem.h" #include "Modules.h" #include "LogicModule.h" #include "HandlerCallCollector.h" using namespace nsLogicWrapper; void TObjectInstanceEndHandlerBuilderSystem::Reactive(nsECSFramework::TEntityID eid, const nsLogicWrapper::TObjectInstanceEndHandlerComponent* pC) { auto handler = pC->handler; if (handler == nullptr) { return; } auto handlerCallCollector = nsTornadoEngine::Modules()->HandlerCalls(); handlerCallCollector->Add([handler, eid]() { handler->Handle(eid); }); }
26.310345
147
0.711664
RamilGauss
10f5def95557eea3f8b793b27399968598c2b537
5,503
cpp
C++
TommyGun/Plugins/CodeEditor/PaletteParser/fPaletteParserOptions.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/Plugins/CodeEditor/PaletteParser/fPaletteParserOptions.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/Plugins/CodeEditor/PaletteParser/fPaletteParserOptions.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
#pragma link "KSpinEdit" /*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include "pch.h" #pragma hdrstop //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" #pragma link "KXmlInfo" //--------------------------------------------------------------------------- using namespace Scorpio; using namespace PaletteParser; //--------------------------------------------------------------------------- TfrmPaletteParserOptions *frmPaletteParserOptions = NULL; //--------------------------------------------------------------------------- __fastcall TfrmPaletteParserOptions::TfrmPaletteParserOptions(TComponent* Owner) : TForm(Owner) , m_pPlugin(NULL) { } //--------------------------------------------------------------------------- HRESULT __fastcall TfrmPaletteParserOptions::Initialize(ZXPlugin* pPlugin) { RL_HRESULT(S_OK); m_pPlugin = pPlugin; String Prefix; regScorpio->Read("PaletteParser", "Prefix", Prefix); int iState = 0; if (regScorpio->Read("PaletteParser", "NumberBase", iState)) { switch(iState) { case 1: radZXPaletteParserHexidecimal->Checked = true; break; case 2: radZXPaletteParserBinary->Checked = true; break; case 0: default: radZXPaletteParserDecimal->Checked = true; } } if (Prefix.Trim() != "") { edtNumericalPrefix->Text = Prefix; } return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall TfrmPaletteParserOptions::Release(void) { RL_HRESULT(S_OK); return hResult; } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radZXPaletteParserDecimalClick(TObject *Sender) { edtNumericalPrefix->Text = ""; regScorpio->Write("PaletteParser", "NumberBase", 0); } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radZXPaletteParserHexidecimalClick(TObject *Sender) { edtNumericalPrefix->Text = "$"; regScorpio->Write("PaletteParser", "NumberBase", 1); } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radZXPaletteParserBinaryClick(TObject *Sender) { edtNumericalPrefix->Text = "%"; regScorpio->Write("PaletteParser", "NumberBase", 2); } //--------------------------------------------------------------------------- String __fastcall TfrmPaletteParserOptions::NumToStr(unsigned char iNum) { String sNum = ""; String sPrefix = frmPaletteParserOptions->edtNumericalPrefix->Text.Trim(); if (radZXPaletteParserDecimal->Checked) { sNum = " " + IntToStr(iNum); sNum = sPrefix + sNum.SubString(sNum.Length() - 2, 3); } else if (radZXPaletteParserHexidecimal->Checked) { sNum = "00" + IntToHex(iNum, 2); sNum = sPrefix + sNum.SubString(sNum.Length() - 1, 2); } else if (radZXPaletteParserBinary->Checked) { sNum = sPrefix; unsigned char bitmask = 0x80; for (int i = 0; i < 8; i++) { sNum += iNum & bitmask ? "1" : "0"; bitmask >>= 1; } } return sNum; } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::edtLabelPrefixChange(TObject *Sender) { lblExample->Caption = edtLabelPrefix->Text + "MyLabel" + edtLabelPostfix->Text; } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::edtNumericalPrefixChange(TObject *Sender) { regScorpio->Write("PaletteParser", "Prefix", edtNumericalPrefix->Text); } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radSourceCodeAsmClick(TObject *Sender) { lblPrefix->Enabled = radSourceCodeAsm->Checked; edtPrefix->Enabled = radSourceCodeAsm->Checked; chkSourceCodeUseLabel->Enabled = radSourceCodeAsm->Checked; lblLabelPrefix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; lblLabelPostfix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; edtLabelPrefix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; edtLabelPostfix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; lblExample->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; } //---------------------------------------------------------------------------
39.028369
98
0.466291
tonyt73
10f90ea1255b7f9a7642b6ba90d913b76e71857c
3,296
cpp
C++
ver1/answers/lp-12-33.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
ver1/answers/lp-12-33.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
ver1/answers/lp-12-33.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
// 18/03/01 = Thu // Exercise 12.33: In Chapter 15 we’ll extend our query system and will need some additional members in the QueryResult class. Add members named begin and end that return iterators into the set of line numbers returned by a given query, and a member named get_file that returns a shared_ptr to the file in the QueryResult object. // Modified from lp-12-32.cpp, with StrBlob replaced with vector<string> // To run, enter, for example, "a data\gatsby" in command prompt. #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <vector> using namespace std; using lino = vector<string>::size_type; using lset = set<vector<string>::size_type>; // add using lsha = shared_ptr<set<vector<string>::size_type>>; using tsha = shared_ptr<vector<string>>; string & standardize(string & s) { transform(s.cbegin(), s.cend(), s.begin(), ::tolower); s.erase(remove_if(s.begin(), s.end(), [](char c){ return !isalpha(c); }), s.end()); return s; } class QueryResult { string aim; tsha txt; lsha loc; public: QueryResult(string, tsha, lsha); lset::iterator begin() { return loc->begin(); } // add lset::iterator end() { return loc->end(); } // add tsha get_file() { return txt; } // add friend ostream & print(ostream &, const QueryResult &); }; class TextQuery { tsha txt; map<string, set<lino>> index; public: TextQuery(istream &); QueryResult query(const string &) const; }; QueryResult:: QueryResult(string a, tsha t, lsha l) : aim(a), txt(t), loc(l) {} TextQuery:: TextQuery(istream & is) : txt(make_shared<vector<string>>()) { lino n = 0; for (string line; getline(is, line); txt->push_back(line), ++n) { istringstream iss(line); for (string word; iss >> word; ) index[standardize(word)].insert(n); } clog << "Number of lines = " << n << endl; clog << "Number of distinct words = " << index.size() << endl; } QueryResult TextQuery:: query(const string & word) const { string aim(word); standardize(aim); auto it = index.find(aim); return QueryResult(aim, txt, (it == index.end() ? make_shared<set<lino>>() : make_shared<set<lino>>(it->second))); } ostream & print(ostream & os, const QueryResult & qr) { lino count = 0; cin.ignore(256, '\n'); for (auto n : *qr.loc) { os << "(line " << n + 1 << ") " << "\t" << qr.txt->at(n) << endl; if (++count % 100 == 0) { cout << "Press Enter to continue or B to break ...... "; if (cin.get() != '\n') { cin.ignore(256, '\n'); count = qr.loc->size(); break; } } } os << "\"" << qr.aim << "\"" << " occurs " << count << (count > 1 ? " times." : " time.") << endl; return os; } void runQueries(ifstream & ifs) { TextQuery tq(ifs); const string prompt = "Enter word to search or Q to quit: "; cout << prompt; for (string word; cin >> word && word != "Q" && word != "q"; cout << prompt) { QueryResult result = tq.query(word); print(cout, result) << endl; } ifs.close(); } int main(int argc, char ** argv) { if (argc == 1) { cerr << "Error: Format is [command][filename]!" << endl; return -1; } ifstream ifs(argv[1]); if (!ifs) { cerr << "Error: Cannot open file!" << endl; return -1; } runQueries(ifs); ifs.close(); return 0; }
24.781955
329
0.629551
aafulei
10fbc17be7c46cd179d7c469a97ba04bef88412a
2,689
cpp
C++
3rdParty/Aria/src/ArTransform.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
3rdParty/Aria/src/ArTransform.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
3rdParty/Aria/src/ArTransform.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2015 Adept Technology, Inc. Copyright (C) 2016 Omron Adept Technologies, Inc. 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 If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ #include "ArExport.h" #include "ariaOSDef.h" #include "ArTransform.h" AREXPORT void ArTransform::doTransform(std::list<ArPose *> *poseList) { std::list<ArPose *>::iterator it; ArPose *pose; for (it = poseList->begin(); it != poseList->end(); it++) { pose = (*it); *pose = doTransform(*pose); } } AREXPORT void ArTransform::doTransform(std::list<ArPoseWithTime *> *poseList) { std::list<ArPoseWithTime *>::iterator it; ArPoseWithTime *pose; for (it = poseList->begin(); it != poseList->end(); it++) { pose = (*it); *pose = doTransform(*pose); } } /** @param pose the coord system from which we transform to abs world coords */ AREXPORT void ArTransform::setTransform(ArPose pose) { myTh = pose.getTh(); myCos = ArMath::cos(-myTh); mySin = ArMath::sin(-myTh); myX = pose.getX(); myY = pose.getY(); } /** @param pose1 transform this into pose2 @param pose2 transform pose1 into this */ AREXPORT void ArTransform::setTransform(ArPose pose1, ArPose pose2) { myTh = ArMath::subAngle(pose2.getTh(), pose1.getTh()); myCos = ArMath::cos(-myTh); mySin = ArMath::sin(-myTh); myX = pose2.getX() - (myCos * pose1.getX() + mySin * pose1.getY()); myY = pose2.getY() - (myCos * pose1.getY() - mySin * pose1.getX()); } AREXPORT void ArTransform::setTransformLowLevel(double x, double y, double th) { myTh = th; myCos = ArMath::cos(-myTh); mySin = ArMath::sin(-myTh); myX = x; myY = y; }
29.877778
78
0.693938
bellonemauro
10fdbd6e0411cb21703639b223a644b5a2492b48
738
cpp
C++
console/Warthog/hog/rsr/EmptyClusterFactory.cpp
pathfindingdebugger/pathfindingdebugger.github.io
a836c1611e1da5ee0331c3ef3e6d9e7702668461
[ "CC-BY-3.0" ]
null
null
null
console/Warthog/hog/rsr/EmptyClusterFactory.cpp
pathfindingdebugger/pathfindingdebugger.github.io
a836c1611e1da5ee0331c3ef3e6d9e7702668461
[ "CC-BY-3.0" ]
null
null
null
console/Warthog/hog/rsr/EmptyClusterFactory.cpp
pathfindingdebugger/pathfindingdebugger.github.io
a836c1611e1da5ee0331c3ef3e6d9e7702668461
[ "CC-BY-3.0" ]
1
2019-09-17T03:12:12.000Z
2019-09-17T03:12:12.000Z
#include "EmptyClusterFactory.h" #include "EmptyCluster.h" #include "EmptyClusterAbstraction.h" EmptyClusterFactory::EmptyClusterFactory() { } EmptyClusterFactory::~EmptyClusterFactory() { } AbstractCluster* EmptyClusterFactory::createCluster(int x, int y, GenericClusterAbstraction* map_) { EmptyClusterAbstraction *map = dynamic_cast<EmptyClusterAbstraction*>(map_); if(map == 0) throw std::invalid_argument("EmptyClusterFactory: new cluster " "requires a map abstraction of type EmptyClusterAbstraction"); return createCluster(x, y, map, false, false); } EmptyCluster* EmptyClusterFactory::createCluster(int x, int y, EmptyClusterAbstraction* map, bool pr, bool bfr) { return new EmptyCluster(x, y, map, pr, bfr); }
23.806452
77
0.772358
pathfindingdebugger
10ff9243ff70b7edce6d99b3edda04c3ee82e67b
1,737
cpp
C++
scenewidget.cpp
predmach/vtk_realsense
4139a86b07ced908ce5b4b9f3089a4fb9fa6a532
[ "Apache-2.0" ]
103
2017-04-01T06:10:08.000Z
2022-03-23T03:13:49.000Z
scenewidget.cpp
JoyPoint/Qt-VTK-viewer
51ee2c4b99982c2798fd99ba89212940861768ac
[ "Apache-2.0" ]
9
2018-04-04T16:14:10.000Z
2021-01-24T15:20:58.000Z
scenewidget.cpp
JoyPoint/Qt-VTK-viewer
51ee2c4b99982c2798fd99ba89212940861768ac
[ "Apache-2.0" ]
35
2017-01-25T01:48:47.000Z
2022-03-27T07:39:30.000Z
#include "scenewidget.h" #include <vtkCamera.h> #include <vtkDataSetMapper.h> #include <vtkGenericOpenGLRenderWindow.h> #include <vtkProperty.h> #include <vtkRenderWindowInteractor.h> SceneWidget::SceneWidget(QWidget* parent) : QVTKOpenGLNativeWidget(parent) { vtkNew<vtkGenericOpenGLRenderWindow> window; setRenderWindow(window.Get()); // Camera vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New(); camera->SetViewUp(0, 1, 0); camera->SetPosition(0, 0, 10); camera->SetFocalPoint(0, 0, 0); // Renderer m_renderer = vtkSmartPointer<vtkRenderer>::New(); m_renderer->SetActiveCamera(camera); m_renderer->SetBackground(0.5, 0.5, 0.5); renderWindow()->AddRenderer(m_renderer); } void SceneWidget::addDataSet(vtkSmartPointer<vtkDataSet> dataSet) { // Actor vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); // Mapper vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(dataSet); actor->SetMapper(mapper); m_renderer->AddActor(actor); m_renderer->ResetCamera(dataSet->GetBounds()); renderWindow()->Render(); } void SceneWidget::removeDataSet() { vtkActor* actor = m_renderer->GetActors()->GetLastActor(); if (actor != nullptr) { m_renderer->RemoveActor(actor); } renderWindow()->Render(); } void SceneWidget::zoomToExtent() { // Zoom to extent of last added actor vtkSmartPointer<vtkActor> actor = m_renderer->GetActors()->GetLastActor(); if (actor != nullptr) { m_renderer->ResetCamera(actor->GetBounds()); } renderWindow()->Render(); }
27.140625
89
0.671272
predmach
8004c29dd80c14e283e34b6242851911f46adab1
5,919
cc
C++
xls/dslx/ast_utils.cc
netskink/xls
78d38c626a360cb835e1c59639a36c67f077769d
[ "Apache-2.0" ]
null
null
null
xls/dslx/ast_utils.cc
netskink/xls
78d38c626a360cb835e1c59639a36c67f077769d
[ "Apache-2.0" ]
null
null
null
xls/dslx/ast_utils.cc
netskink/xls
78d38c626a360cb835e1c59639a36c67f077769d
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The XLS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xls/dslx/ast_utils.h" #include "xls/common/status/ret_check.h" #include "xls/common/status/status_macros.h" namespace xls::dslx { namespace { // Has to be an enum, given the context we're in: looking for _values_. absl::StatusOr<EnumDef*> ResolveTypeDefToEnum(ImportData* import_data, const TypeInfo* type_info, TypeDef* type_def) { TypeDefinition td = type_def; while (absl::holds_alternative<TypeDef*>(td)) { TypeDef* type_def = absl::get<TypeDef*>(td); TypeAnnotation* type = type_def->type_annotation(); TypeRefTypeAnnotation* type_ref_type = dynamic_cast<TypeRefTypeAnnotation*>(type); // TODO(rspringer): We'll need to collect parametrics from type_ref_type to // support parametric TypeDefs. XLS_RET_CHECK(type_ref_type != nullptr); td = type_ref_type->type_ref()->type_definition(); } if (absl::holds_alternative<ColonRef*>(td)) { ColonRef* colon_ref = absl::get<ColonRef*>(td); XLS_ASSIGN_OR_RETURN(auto subject, ResolveColonRefSubject( import_data, type_info, colon_ref)); XLS_RET_CHECK(absl::holds_alternative<Module*>(subject)); Module* module = absl::get<Module*>(subject); XLS_ASSIGN_OR_RETURN(td, module->GetTypeDefinition(colon_ref->attr())); if (absl::holds_alternative<TypeDef*>(td)) { // We need to get the right type info for the enum's containing module. We // can get the top-level module since [currently?] enums can't be // parameterized. type_info = import_data->GetRootTypeInfo(module).value(); return ResolveTypeDefToEnum(import_data, type_info, absl::get<TypeDef*>(td)); } } if (!absl::holds_alternative<EnumDef*>(td)) { return absl::InternalError( "ResolveTypeDefToEnum() can only be called when the TypeDef " "directory or indirectly refers to an EnumDef."); } return absl::get<EnumDef*>(td); } } // namespace absl::StatusOr<Proc*> ResolveProc(Expr* callee, TypeInfo* type_info) { if (NameRef* name_ref = dynamic_cast<NameRef*>(callee); name_ref != nullptr) { return name_ref->owner()->GetProcOrError(name_ref->identifier()); } auto* colon_ref = dynamic_cast<ColonRef*>(callee); XLS_RET_CHECK_NE(colon_ref, nullptr); absl::optional<Import*> import = colon_ref->ResolveImportSubject(); XLS_RET_CHECK(import.has_value()) << "ColonRef did not refer to an import: " << colon_ref->ToString(); absl::optional<const ImportedInfo*> imported_info = type_info->GetImported(*import); return imported_info.value()->module->GetProcOrError(colon_ref->attr()); } absl::StatusOr<absl::variant<Module*, EnumDef*>> ResolveColonRefSubject( ImportData* import_data, const TypeInfo* type_info, ColonRef* colon_ref) { if (absl::holds_alternative<NameRef*>(colon_ref->subject())) { // Inside a ColonRef, the LHS can't be a BuiltinNameDef. NameRef* name_ref = absl::get<NameRef*>(colon_ref->subject()); NameDef* name_def = absl::get<NameDef*>(name_ref->name_def()); if (Import* import = dynamic_cast<Import*>(name_def->definer()); import != nullptr) { absl::optional<const ImportedInfo*> imported = type_info->GetImported(import); if (!imported.has_value()) { return absl::InternalError(absl::StrCat( "Could not find Module for Import: ", import->ToString())); } return imported.value()->module; } // If the LHS isn't an Import, then it has to be an EnumDef (possibly via a // TypeDef). if (EnumDef* enum_def = dynamic_cast<EnumDef*>(name_def->definer()); enum_def != nullptr) { return enum_def; } TypeDef* type_def = dynamic_cast<TypeDef*>(name_def->definer()); XLS_RET_CHECK(type_def != nullptr); if (type_def->owner() != type_info->module()) { // We need to get the right type info for the enum's containing module. We // can get the top-level module since [currently?] enums can't be // parameterized (and we know this must be an enum, per the above). type_info = import_data->GetRootTypeInfo(type_def->owner()).value(); } return ResolveTypeDefToEnum(import_data, type_info, type_def); } XLS_RET_CHECK(absl::holds_alternative<ColonRef*>(colon_ref->subject())); ColonRef* subject = absl::get<ColonRef*>(colon_ref->subject()); XLS_ASSIGN_OR_RETURN(auto resolved_subject, ResolveColonRefSubject(import_data, type_info, subject)); // Has to be a module, since it's a ColonRef inside a ColonRef. XLS_RET_CHECK(absl::holds_alternative<Module*>(resolved_subject)); Module* module = absl::get<Module*>(resolved_subject); // And the subject has to be a type, namely an enum, since the ColonRef must // be of the form: <MODULE>::SOMETHING::SOMETHING_ELSE. Keep in mind, though, // that we might have to traverse an EnumDef. XLS_ASSIGN_OR_RETURN(TypeDefinition td, module->GetTypeDefinition(subject->attr())); if (absl::holds_alternative<TypeDef*>(td)) { return ResolveTypeDefToEnum(import_data, type_info, absl::get<TypeDef*>(td)); } return absl::get<EnumDef*>(td); } } // namespace xls::dslx
42.278571
80
0.675283
netskink
8007346c8b0fb80fbfd2d8e50fe82ff5e8d7cf77
1,083
cpp
C++
EmerCert/MainWindow.cpp
emercoin-scratch/EmerCert
9d17b363dd0e9d6feb07c62ee385e585d9a72dee
[ "BSD-2-Clause" ]
2
2018-11-12T16:22:44.000Z
2021-04-24T03:08:24.000Z
EmerCert/MainWindow.cpp
emercoin-scratch/EmerCert
9d17b363dd0e9d6feb07c62ee385e585d9a72dee
[ "BSD-2-Clause" ]
1
2018-07-09T22:20:45.000Z
2021-03-20T05:00:55.000Z
EmerCert/MainWindow.cpp
emercoin-scratch/EmerCert
9d17b363dd0e9d6feb07c62ee385e585d9a72dee
[ "BSD-2-Clause" ]
3
2018-10-06T20:35:05.000Z
2020-11-26T00:15:45.000Z
#include "pch.h" #include "MainWindow.h" #include "InfoCardsWidget.h" #include "ManageSslPage.h" #include "ManageDnsPage.h" #include "EnumerDialog.h" #include "DiplomaWidget.h" #include "DpoWidget.h" #include "AboutWidget.h" MainWindow::MainWindow(QWidget *parent): QTabWidget(parent) { setWindowTitle(tr("EmerCert Manager ") + QCoreApplication::applicationVersion()); add(new ManageSslPage); add(new InfoCardsWidget); add(new ManageDnsPage); add(new DpoWidget); add(new DiplomaWidget); #ifdef _DEBUG add(new EnumerDialog); #endif add(new AboutWidget); setIconSize({32, 32}); auto quit = new QAction(tr("Quit")); quit->setShortcut(QKeySequence("Ctrl+Q")); connect(quit, &QAction::triggered, qApp, &QCoreApplication::quit); addAction(quit); QSettings sett; int index = sett.value("MainWindow.tabIndex", 0).toInt(); index = qBound(0, index, count()-1); setCurrentIndex(index); } void MainWindow::add(QWidget *w) { addTab(w, w->windowIcon(), w->windowTitle()); } MainWindow::~MainWindow() { QSettings sett; sett.setValue("MainWindow.tabIndex", currentIndex()); }
27.075
82
0.730379
emercoin-scratch
800950a892025477a88272510d8be9b29912b92c
4,415
cpp
C++
qgeotiledmappingmanagerenginegooglemaps.cpp
mfbernardes/googlemaps
7ce7124b385b2ebac0f72c38b094f436d4fe5c58
[ "MIT" ]
123
2016-07-18T07:53:34.000Z
2022-02-21T20:30:27.000Z
qgeotiledmappingmanagerenginegooglemaps.cpp
mfbernardes/googlemaps
7ce7124b385b2ebac0f72c38b094f436d4fe5c58
[ "MIT" ]
30
2016-07-18T07:55:30.000Z
2022-03-06T02:03:24.000Z
qgeotiledmappingmanagerenginegooglemaps.cpp
mfbernardes/googlemaps
7ce7124b385b2ebac0f72c38b094f436d4fe5c58
[ "MIT" ]
66
2016-09-17T12:41:41.000Z
2021-12-28T16:39:48.000Z
#include "QtLocation/private/qgeocameracapabilities_p.h" #include "qgeotiledmappingmanagerenginegooglemaps.h" #include "qgeotiledmapgooglemaps.h" #include "qgeotilefetchergooglemaps.h" #include "QtLocation/private/qgeotilespec_p.h" #if QT_VERSION < QT_VERSION_CHECK(5,6,0) #include <QStandardPaths> #include "QtLocation/private/qgeotilecache_p.h" #else #include "QtLocation/private/qgeofiletilecache_p.h" #endif #include <QDebug> #include <QDir> #include <QVariant> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QJsonDocument> #include <QtCore/qmath.h> #include <QtCore/qstandardpaths.h> QT_BEGIN_NAMESPACE QGeoTiledMappingManagerEngineGooglemaps::QGeoTiledMappingManagerEngineGooglemaps(const QVariantMap &parameters, QGeoServiceProvider::Error *error, QString *errorString) : QGeoTiledMappingManagerEngine() { Q_UNUSED(error); Q_UNUSED(errorString); QGeoCameraCapabilities capabilities; capabilities.setMinimumZoomLevel(0.0); capabilities.setMaximumZoomLevel(21.0); setCameraCapabilities(capabilities); int tile = parameters.value(QStringLiteral("googlemaps.maps.tilesize"), 256).toInt(); setTileSize(QSize(tile, tile)); QList<QGeoMapType> types; #if QT_VERSION < QT_VERSION_CHECK(5,9,0) types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1); types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2); types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3); types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4); #elif QT_VERSION < QT_VERSION_CHECK(5,10,0) types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps"); types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps"); types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps"); types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps"); #else types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps", capabilities, parameters); types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps", capabilities, parameters); types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps", capabilities, parameters); types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps", capabilities, parameters); #endif setSupportedMapTypes(types); QGeoTileFetcherGooglemaps *fetcher = new QGeoTileFetcherGooglemaps(parameters, this, tileSize()); setTileFetcher(fetcher); if (parameters.contains(QStringLiteral("googlemaps.cachefolder"))) m_cacheDirectory = parameters.value(QStringLiteral("googlemaps.cachefolder")).toString(); const int szCache = 100 * 1024 * 1024; #if QT_VERSION < QT_VERSION_CHECK(5,6,0) if (m_cacheDirectory.isEmpty()) m_cacheDirectory = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("googlemaps"); QGeoTileCache *tileCache = createTileCacheWithDir(m_cacheDirectory); if (tileCache) tileCache->setMaxDiskUsage(szCache); #else if (m_cacheDirectory.isEmpty()) m_cacheDirectory = QAbstractGeoTileCache::baseCacheDirectory() + QLatin1String("googlemaps"); QAbstractGeoTileCache *tileCache = new QGeoFileTileCache(m_cacheDirectory); tileCache->setMaxDiskUsage(szCache); setTileCache(tileCache); #endif *error = QGeoServiceProvider::NoError; errorString->clear(); } QGeoTiledMappingManagerEngineGooglemaps::~QGeoTiledMappingManagerEngineGooglemaps() { } QGeoMap *QGeoTiledMappingManagerEngineGooglemaps::createMap() { return new QGeoTiledMapGooglemaps(this); } QT_END_NAMESPACE
45.515464
176
0.752435
mfbernardes
800a5d7416a13180aafa1398d84598e65c192f5a
5,508
cpp
C++
Src/lunaui/launcher/gfx/scrollingsurface.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/lunaui/launcher/gfx/scrollingsurface.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/lunaui/launcher/gfx/scrollingsurface.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "scrollingsurface.h" #include "pixmapobject.h" #include "dimensionsglobal.h" #include <QPainter> #include <QDebug> ScrollingSurface::ScrollingSurface(const QRectF& geometry) : ScrollableObject(geometry) , m_qp_surfacePmo(0) { } //virtual ScrollingSurface::~ScrollingSurface() { } void ScrollingSurface::resetTargetRectValid() { m_targetRect = QRect(m_screenGeom.x(), m_screenGeom.y(), m_maxSourceRectWidth, m_maxSourceRectHeight); } //TODO: pixmap management - deletion of unused when new ones are set void ScrollingSurface::setPixmapObject(PixmapObject * p_pmo) { m_qp_surfacePmo = p_pmo; if (p_pmo) { setFlag(QGraphicsItem::ItemHasNoContents,false); setSourceContentGeom(DimensionsGlobal::realRectAroundRealPoint(QSizeF(p_pmo->size()))); } else { setFlag(QGraphicsItem::ItemHasNoContents,true); m_sourceRect = QRect(0,0,0,0); setSourceContentGeom(QRectF(0,0,0,0)); //TODO: TEST: see setSourceContentGeom. clean this up m_targetRect = QRect(0,0,0,0); } update(m_boundingRect); } bool ScrollingSurface::testAndtranslateScrollSurfacePointToPixmapPoint(const QPointF& pointF,QPoint& r_translatedPoint) { // QPoint point = pointF.toPoint(); // if (m_targetRect.contains(point)) // { // //ask the pixmapobject to map this for me // r_translatedPoint = m_qp_surfacePmo->translatePaintTargetPointToPixmapPoint(point,m_sourceRect,m_targetRect); // //qDebug() << __PRETTY_FUNCTION__ << ": point: " << point << " , pixmap point: " << r_translatedPoint; // return true; // } // //qDebug() << __PRETTY_FUNCTION__ << ": point: " << point << " is not contained in the target paint rect " << m_targetRect; return false; } //virtual qint32 ScrollingSurface::scrollValue() const { if (m_overscrollVal) return m_overscrollVal; //else not in overscroll, return the top y of the source rect return m_sourceRect.top(); } //virtual qint32 ScrollingSurface::rawScrollValue() const { return m_sourceRect.top(); } //virtual void ScrollingSurface::setScrollValue(qint32 v) { //qDebug() << __FUNCTION__ << " " << v; if ((v >= 0) && (v < m_overscrollBottomStart)) { //no overscroll...somewhere in the middle of things m_sourceRect.setY(v); m_sourceRect.setHeight(m_maxSourceRectHeight); resetTargetRectValid(); m_overscrollVal = 0; } else if (v < 0) { //Negative values: set it to overscroll from top. //the source rect is shrunk, with the shrinking coming from the bottom of the rect m_sourceRect.setY(0); m_sourceRect.setHeight(qMax(0,m_screenGeom.height()+v)); m_targetRect.setY(m_screenGeom.top() + qMin(-v,m_screenGeom.height())); m_targetRect.setHeight(m_sourceRect.height()); m_overscrollVal = v; } else { //TODO: PIXEL-ALIGN QSize sourceSize = m_sourceGeom.size().toSize(); //Positive value > m_overscrollBottomStart //the source rect is shrunk, with the shrinking coming from the top qint32 va = qMin(v,sourceSize.height()); m_sourceRect.setY(va); m_sourceRect.setHeight(sourceSize.height()-va); m_targetRect.setY(m_screenGeom.top()); m_targetRect.setHeight(m_sourceRect.height()); m_overscrollVal = v; } update(m_boundingRect); } ////public Q_SLOTS: /* * * These geom change functions are empty on purpose...see .h file * */ //virtual void ScrollingSurface::slotSourceGeomChanged(const QRectF& newGeom) { } //virtual void ScrollingSurface::slotSourceContentSizeChanged(const QSizeF& newContentSize) { } //virtual void ScrollingSurface::slotSourceContentSizeChanged(const QSize& newContentSize) { } ////protected: //virtual void ScrollingSurface::setSourceContentGeom(const QRectF& newContentGeom) { m_sourceGeom = newContentGeom; //TODO: PIXEL-ALIGN QSize sourceSize = m_sourceGeom.size().toSize(); m_maxSourceRectWidth = qMin(sourceSize.width(),m_screenGeom.width()); m_maxSourceRectHeight = qMin(sourceSize.height(),m_screenGeom.height()); m_sourceRect = QRect(0,0,m_maxSourceRectWidth,m_maxSourceRectHeight); m_targetRect = QRect(m_screenGeom.x(), m_screenGeom.y(), m_maxSourceRectWidth, m_maxSourceRectHeight); m_overscrollBottomStart = qMax(0,sourceSize.height()-m_screenGeom.height()); } //virtual void ScrollingSurface::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget) { //ASSUMES m_qp_surfacePmo is valid; the ItemHasNoContents should have been set otherwise QPen sp = painter->pen(); painter->setPen(Qt::green); painter->drawRect(m_screenGeom); painter->setPen(sp); // painter->drawPixmap(m_screenGeom.x(),m_screenGeom.y(), // m_screenGeom.width(),m_screenGeom.height(), // (*(*m_qp_surfacePmo)),m_sourceRect.x(),m_sourceRect.y(), // m_sourceRect.width(),m_sourceRect.height()); //COMMENTED TO TEST OUT HUGE PIXMAP // painter->drawPixmap(m_targetRect, // (*(*m_qp_surfacePmo)), // m_sourceRect); // m_qp_surfacePmo->paint(painter,m_targetRect,m_sourceRect); }
27.402985
127
0.741649
ericblade
800ca97ca8a69dfdb3c41e0cfdea9e54d4119fd9
13,625
cpp
C++
kernel/common/SSMMsg.cpp
TonnyRed/sedna
06ff5a13a16f2d820d3cf0ce579df23f03a59eda
[ "ECL-2.0", "Apache-2.0" ]
14
2015-09-06T10:17:02.000Z
2021-12-14T22:39:25.000Z
kernel/common/SSMMsg.cpp
TonnyRed/sedna
06ff5a13a16f2d820d3cf0ce579df23f03a59eda
[ "ECL-2.0", "Apache-2.0" ]
1
2020-02-15T22:02:14.000Z
2020-02-17T10:30:14.000Z
kernel/common/SSMMsg.cpp
TonnyRed/sedna
06ff5a13a16f2d820d3cf0ce579df23f03a59eda
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-23T05:48:20.000Z
2021-04-11T05:01:39.000Z
/* * File: SSMMsg.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include <assert.h> #include "common/SSMMsg.h" #include "common/utils.h" #include "common/errdbg/d_printf.h" #include "common/u/ugnames.h" using namespace std; // SSMMsg stands for Simple Shared Memory Messages Client/Server Architecture #define SSMMSG_PAGE_SIZE 4096 #define MESSAGES_IN_QUEUE 100 #define PROCESS_METHOD_THREAD_STACK_SIZE (1024 * 100) #define SSMMSG_SHMEM_SUFFIX "shmem" #define SSMMSG_SEMS_SUFFIX "sems" #define sem_clients 0 #define sem_servers 1 #define sem_mutex 2 #define sem_pact 3 #define sem_pact_written 4 #define sem_pact_read 5 #define NAMED_SEMS_NUM 6 #define sem_data_written NAMED_SEMS_NUM #define sem_data_processed (NAMED_SEMS_NUM + servers_amount) #define sem_data_read (NAMED_SEMS_NUM + 2 * servers_amount) #define sem_data_processed2(s) (NAMED_SEMS_NUM + (s)->servers_amount) #define sem_data_read2(s) (NAMED_SEMS_NUM + 2 * (s)->servers_amount) struct SSMMsgNames { global_name memory; global_name sems; }; static void InitSSMMsgNames(SSMMsgNames *names, global_name name, char *buf, size_t bufSz) { assert(names); if ((names->memory = UGlobalNameFromCompoundName(name, 0, buf, bufSz))) { size_t consumed = strlen(names->memory)+1; buf+=consumed; bufSz-=consumed; } names->sems = UGlobalNameFromCompoundName(name, 0, buf, bufSz); } SSMMsg::SSMMsg(mode _m_, int _msg_size_, global_name _g_name_, int _servers_amount_, unsigned int _millisec_) { m = _m_; msg_size = _msg_size_; servers_amount = _servers_amount_; real_block_size = 0; shared_memory_size = 0; waiting = NULL; slot = NULL; process_messages = NULL; busy_servers_amount = NULL; shar_mem = NULL; buf_addr = NULL; sysinf_addr = NULL; sems_num = NAMED_SEMS_NUM + 3 * servers_amount; SSMMsgNames names = {}; InitSSMMsgNames(&names, _g_name_, g_names__buf__, 256); g_name_shmem = names.memory; g_name_sems = names.sems; server_param = NULL; millisec = _millisec_; thread_handles = NULL; sems = 0; real_block_size = msg_size % SSMMSG_PAGE_SIZE == 0 ? msg_size : (msg_size / SSMMSG_PAGE_SIZE + 1) * SSMMSG_PAGE_SIZE; // the idea is that first page is for system purposes (it contains system // data) shared_memory_size = SSMMSG_PAGE_SIZE + real_block_size * servers_amount; shutdown_server_proc = false; } int SSMMsg::init() { //d_printf1("!!!!!!!! SSMMsg::init() !!!!!!!\n"); if (m == Server) { if (0 != uCreateShMem(&sh_mem, g_name_shmem, shared_memory_size, NULL, __sys_call_error)) { d_printf1("uCreateShMem failed\n"); return 1; } shar_mem = uAttachShMem(&sh_mem, NULL, 0, __sys_call_error); if (shar_mem == NULL) { d_printf1("uAttachShMem failed\n"); return 1; } //d_printf2("shar_mem 0x%x\n", shar_mem); //d_printf2("shared_memory_size %d\n", shared_memory_size); int *init_values = se_new int[sems_num]; init_values[sem_clients] = 0; init_values[sem_servers] = 0; init_values[sem_mutex] = 1; init_values[sem_pact] = 1; init_values[sem_pact_written] = 0; init_values[sem_pact_read] = 0; int i = 0; for (i = NAMED_SEMS_NUM; i < sems_num; i++) init_values[i] = 0; if (0 != USemaphoreArrCreate(&sems, sems_num, init_values, g_name_sems, NULL, __sys_call_error)) { d_printf1("USemaphoreArrCreate failed\n"); return 1; } delete [] init_values; sysinf_addr = shar_mem; buf_addr = (void*)((char*)shar_mem + SSMMSG_PAGE_SIZE); waiting = (int*)sysinf_addr; slot = (int*)sysinf_addr + 1; process_messages = (int*)sysinf_addr + 2; busy_servers_amount = (int*)sysinf_addr + 3; *waiting = 0; *slot = 0; *process_messages = 1; *busy_servers_amount = 0; } else if (m == Client) { //d_printf1("!!!!!!!!!!! Client initialization !!!!!!!!!!!!!!!!!!!!!!!!!\n"); if (0 != uOpenShMem(&sh_mem, g_name_shmem, __sys_call_error)) { d_printf1("uOpenShMem failed\n"); return 1; } shar_mem = uAttachShMem(&sh_mem, NULL, 0, __sys_call_error); if (shar_mem == NULL) { d_printf1("uAttachShMem failed\n"); return 1; } //d_printf2("shar_mem 0x%x\n", shar_mem); //d_printf2("shared_memory_size %d\n", shared_memory_size); if (0 != USemaphoreArrOpen(&sems, sems_num, g_name_sems, __sys_call_error)) { d_printf1("USemaphoreArrOpen failed\n"); return 1; } sysinf_addr = shar_mem; buf_addr = (void*)((char*)shar_mem + SSMMSG_PAGE_SIZE); waiting = (int*)sysinf_addr; slot = (int*)sysinf_addr + 1; process_messages = (int*)sysinf_addr + 2; busy_servers_amount = (int*)sysinf_addr + 3; } else return 1; return 0; } int SSMMsg::shutdown() { if (0 != uDettachShMem(&sh_mem, shar_mem, __sys_call_error)) { d_printf1("uDettachShMem failed\n"); return 1; } if (m == Server) { if (0 != uReleaseShMem(&sh_mem, g_name_shmem, __sys_call_error)) { d_printf1("uReleaseShMem failed\n"); return 1; } if (0 != USemaphoreArrRelease(sems, sems_num, __sys_call_error)) { d_printf1("USemaphoreArrRelease failed\n"); return 1; } } else if (m == Client) { if (0 != uCloseShMem(&sh_mem, __sys_call_error)) { d_printf1("uCloseShMem failed\n"); return 1; } if (0 != USemaphoreArrClose(sems, sems_num, __sys_call_error)) { d_printf1("USemaphoreArrClose failed\n"); return 1; } } else return 1; delete server_param; delete [] thread_handles; return 0; } #define down1(sems, idx, ret) if (0 != USemaphoreArrDown(sems, idx, __sys_call_error)) \ { \ d_printf1("USemaphoreArrDown1 failed\n"); \ return ret; \ } #define down2(sems, idx, ms, ret) if (0 != USemaphoreArrDown(sems, idx/*, ms*/, __sys_call_error)) \ { \ d_printf1("USemaphoreArrDown2 failed\n"); \ return ret; \ } #define up(sems, idx, ret) if (0 != USemaphoreArrUp(sems, idx, __sys_call_error)) \ { \ d_printf1("USemaphoreArrUp failed\n"); \ return ret; \ } int SSMMsg::send_msg(void * buf) { // static int i = 0; // d_printf2("send_msg called %d times\n", ++i); fflush(stdout); int server_num = 0; // d_printf2("down sem_mutex %d\n", (int)sem_mutex); fflush(stdout); down2(sems, sem_mutex, millisec, 1); // d_printf2("down sem_mutex %d\n", (int)sem_mutex); fflush(stdout); if (*waiting < MESSAGES_IN_QUEUE && *process_messages == 1) { *waiting += 1; // d_printf2("*waiting = %d\n", *waiting); fflush(stdout); // d_printf2("*process_messages = %d\n", *process_messages); fflush(stdout); up(sems, sem_clients, 1); up(sems, sem_mutex, 1); // d_printf1("down sem_servers\n"); fflush(stdout); down2(sems, sem_servers, millisec, 1); // d_printf1("down sem_pact_written\n"); fflush(stdout); down2(sems, sem_pact_written, millisec, 1); server_num = *slot; up(sems, sem_pact_read, 1); // d_printf2("server_num %d\n", server_num); fflush(stdout); // d_printf2("cell 0x%x\n", (void*)((char*)buf_addr + server_num * real_block_size)); fflush(stdout); memcpy((void*)((char*)buf_addr + server_num * real_block_size), buf, msg_size); up(sems, sem_data_written + server_num, 1); // d_printf2("down sem_data_processed[%d]\n", server_num); fflush(stdout); down2(sems, sem_data_processed + server_num, millisec, 1); // d_printf1("after down sem_data_processed\n"); memcpy(buf, (void*)((char*)buf_addr + server_num * real_block_size), msg_size); // d_printf2("up sem_data_read[%d]\n", server_num); fflush(stdout); up(sems, sem_data_read + server_num, 1); // d_printf1("client: msg sent\n"); fflush(stdout); } else { // if (!(*waiting < MESSAGES_IN_QUEUE)) d_printf2("Deny of service: server is busy (queue is too long) %d\n", *waiting); // if (!(*process_messages == 1)) d_printf2("Deny of service: server is being shutdown %d\n", *process_messages); up(sems, sem_mutex, 1); // d_printf1("Deny of service: server is busy or is being shutdown\n"); return 1; } return 0; } #ifdef _WIN32 #define THREAD_FUN_RET_TYPE DWORD #else #define THREAD_FUN_RET_TYPE void* #endif U_THREAD_PROC(SSMMsg_server_proc, arg) { if (uThreadBlockAllSignals(__sys_call_error) != 0) d_printf1("Failed to block signals for SSMMsg_server_proc"); int i = ((SSMMsg_server_thread_param*)arg)->i; process_msg_func func = ((SSMMsg_server_thread_param*)arg)->func; SSMMsg *ssmmsg = ((SSMMsg_server_thread_param*)arg)->ssmmsg; while (true) { //d_printf1("cycle iteration\n"); fflush(stdout); up(ssmmsg->sems, sem_servers, (THREAD_FUN_RET_TYPE)-1); down1(ssmmsg->sems, sem_clients, (THREAD_FUN_RET_TYPE)-1); if (ssmmsg->shutdown_server_proc) break; down1(ssmmsg->sems, sem_mutex, (THREAD_FUN_RET_TYPE)-1); *(ssmmsg->waiting) -= 1; *(ssmmsg->busy_servers_amount) += 1; up(ssmmsg->sems, sem_mutex, (THREAD_FUN_RET_TYPE)-1); down1(ssmmsg->sems, sem_pact, (THREAD_FUN_RET_TYPE)-1); *(ssmmsg->slot) = i; up(ssmmsg->sems, sem_pact_written, (THREAD_FUN_RET_TYPE)-1); down1(ssmmsg->sems, sem_pact_read, (THREAD_FUN_RET_TYPE)-1); up(ssmmsg->sems, sem_pact, (THREAD_FUN_RET_TYPE)-1); down1(ssmmsg->sems, sem_data_written + i, (THREAD_FUN_RET_TYPE)-1); // user activity func((void*)((char*)(ssmmsg->buf_addr) + i * ssmmsg->real_block_size)); // d_printf2("up sem_data_processed[%d]\n", i); fflush(stdout); up(ssmmsg->sems, sem_data_processed2(ssmmsg) + i, (THREAD_FUN_RET_TYPE)-1); // d_printf2("down sem_data_read[%d]\n", i); fflush(stdout); down1(ssmmsg->sems, sem_data_read2(ssmmsg) + i, (THREAD_FUN_RET_TYPE)-1); down1(ssmmsg->sems, sem_mutex, (THREAD_FUN_RET_TYPE)-1); *(ssmmsg->busy_servers_amount) -= 1; up(ssmmsg->sems, sem_mutex, (THREAD_FUN_RET_TYPE)-1); } return 0; } int SSMMsg::serve_clients(process_msg_func func) { shutdown_server_proc = false; server_param = se_new SSMMsg_server_thread_param; server_param->func = func; server_param->ssmmsg = this; thread_handles = se_new UTHANDLE[servers_amount]; for (int i = 0; i < servers_amount; i++) { //d_printf2("server thread number %d started\n", i); UTHANDLE id; server_param->i = i; uResVal res = uCreateThread(SSMMsg_server_proc, server_param, &id, PROCESS_METHOD_THREAD_STACK_SIZE, NULL, __sys_call_error); if (res != 0) { d_printf1("Failed to create thread\n"); return 1; } thread_handles[i] = id; } return 0; } int SSMMsg::stop_serve_clients() { down1(sems, sem_mutex, 1); *process_messages = 0; up(sems, sem_mutex, 1); while (true) { down1(sems, sem_mutex, 1); if (*waiting == 0 && *busy_servers_amount == 0) { int i = 0; up(sems, sem_mutex, 1); shutdown_server_proc = true; for (i = 0; i < servers_amount; i++) up(sems, sem_clients, 1); for (i = 0; i < servers_amount; i++) { if (uThreadJoin(thread_handles[i], __sys_call_error) != 0) { d_printf1("uThreadJoin failed\n"); return 1; } if (uCloseThreadHandle(thread_handles[i], __sys_call_error) != 0) { d_printf1("uCloseThreadHandle failed\n"); return 1; } } break; } else up(sems, sem_mutex, 1); uSleep(1, __sys_call_error); } return 0; } void SSMMsg::ipc_cleanup(global_name name) { USemaphoreArr sems; UShMem memory; SSMMsgNames names; char buf[256]; InitSSMMsgNames(&names, name, buf, sizeof buf); if (uOpenShMem(&memory, names.memory, __sys_call_error) == 0) { uReleaseShMem(&memory, names.memory, __sys_call_error); } if (USemaphoreArrOpen(&sems, 9, names.sems, __sys_call_error) == 0) { USemaphoreArrRelease(sems, 9, __sys_call_error); } }
29.945055
133
0.581431
TonnyRed
800e306476ab6fb4dc72b154621b2dff5751f4b3
264
cc
C++
JetMETCorrections/JetVertexAssociation/src/SealModule.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
JetMETCorrections/JetVertexAssociation/src/SealModule.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
JetMETCorrections/JetVertexAssociation/src/SealModule.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "JetMETCorrections/JetVertexAssociation/interface/JetVertexAssociation.h" using cms::JetVertexAssociation; DEFINE_FWK_MODULE(JetVertexAssociation);
37.714286
82
0.859848
ckamtsikis
800eba6e0c7a203f14a2419451b78d2a633068a9
199
hpp
C++
src/Dome.hpp
kant/GeoLEDic
3cfb343576c9fb1a5470b0f604891b7d9033cdbb
[ "MIT" ]
null
null
null
src/Dome.hpp
kant/GeoLEDic
3cfb343576c9fb1a5470b0f604891b7d9033cdbb
[ "MIT" ]
8
2021-06-14T09:09:28.000Z
2021-12-05T04:56:08.000Z
src/Dome.hpp
kant/GeoLEDic
3cfb343576c9fb1a5470b0f604891b7d9033cdbb
[ "MIT" ]
1
2021-11-12T01:39:56.000Z
2021-11-12T01:39:56.000Z
#ifndef GEOLEDIC_DOME_HPP #define GEOLEDIC_DOME_HPP #include "DomeDefs.hpp" #include "Triangle.hpp" extern CRGB leds[NUM_STRIPS * LEDS_PER_STRIP]; extern Triangle dome[DOME_NUM_TRIANGLES]; #endif
18.090909
46
0.809045
kant
801398d4c6d03f35777e2ef827ebe9c9d8a98a7a
12,288
cpp
C++
lab4/lab4.cpp
Emberwalker/ac41001_opengl_cpp
c2f63fb6bb200a44f93e43af00b32a9d7b5df05a
[ "MIT" ]
1
2017-10-31T16:03:47.000Z
2017-10-31T16:03:47.000Z
lab4/lab4.cpp
Emberwalker/ac41001_opengl_cpp
c2f63fb6bb200a44f93e43af00b32a9d7b5df05a
[ "MIT" ]
null
null
null
lab4/lab4.cpp
Emberwalker/ac41001_opengl_cpp
c2f63fb6bb200a44f93e43af00b32a9d7b5df05a
[ "MIT" ]
null
null
null
/* poslight.cpp Demonstrates a positional light with attenuation Displays a cube and a sphere and a small sphere to show the light position Includes controls to move the light source and rotate the view Iain Martin October 2017 */ #include <guts/guts.h> #include <iostream> #include <stack> #include <glm/glm.hpp> #include "glm/gtc/matrix_transform.hpp" #include <glm/gtc/type_ptr.hpp> #include <guts/objs/cube.h> #include <guts/objs/sphere.h> #include <memory> /* Define buffer object indices */ GLuint elementbuffer; GLuint program; /* Identifier for the shader prgoram */ GLuint vao; /* Vertex array (Containor) object. This is the index of the VAO that will be the container for our buffer objects */ GLuint colourmode; /* Index of a uniform to switch the colour mode in the vertex shader I've included this to show you how to pass in an unsigned integer into your vertex shader. */ GLuint emitmode; /* Position and view globals */ GLfloat angle_x, angle_inc_x, x, model_scale, z, y, vx, vy, vz; GLfloat angle_y, angle_inc_y, angle_z, angle_inc_z; GLuint drawmode; // Defines drawing mode of sphere as points, lines or filled polygons GLuint numlats, numlongs; //Define the resolution of the sphere object GLfloat light_x, light_y, light_z; /* Uniforms*/ GLint lightposID, normalmatrixID, emitmodeID; std::unique_ptr<guts::GLUniform<GLuint>> uniform_colourmode; std::unique_ptr<guts::GLUniform<glm::mat4>> uniform_model, uniform_view, uniform_projection; GLfloat aspect_ratio; /* Aspect ratio of the window defined in the reshape callback*/ /* Global instances of our objects */ std::unique_ptr<guts::objs::Sphere> aSphere; std::unique_ptr<guts::objs::Cube> aCube; using namespace std; using namespace glm; /* This function is called before entering the main rendering loop. Use it for all your initialisation stuff */ void init(guts::GlfwWindow *glw) { /* Set the object transformation controls to their initial values */ x = 0.05f; y = 0; z = 0; vx = 0; vx = 0, vz = 4.f; light_x = 0; light_y = 0; light_z = 0; angle_x = angle_y = angle_z = 0; angle_inc_x = angle_inc_y = angle_inc_z = 0; model_scale = 1.f; aspect_ratio = 1.3333f; colourmode = 0; emitmode = 0; numlats = 200; // Number of latitudes in our sphere numlongs = 200; // Number of longitudes in our sphere // Generate index (name) for one vertex array object gl::GenVertexArrays(1, &vao); // Create the vertex array object and make it current gl::BindVertexArray(vao); /* Load and build the vertex and fragment shaders */ try { guts::GLProgramBuilder builder; builder.AddShader(gl::VERTEX_SHADER, "lab4.vert"); builder.AddShader(gl::FRAGMENT_SHADER, "lab4.frag"); program = builder.BuildProgram(); } catch (exception &e) { cout << "Caught exception: " << e.what() << endl; cin.ignore(); exit(0); } /* Define uniforms to send to vertex shader */ //modelID = gl::GetUniformLocation(program, "model"); //colourmodeID = gl::GetUniformLocation(program, "colourmode"); emitmodeID = gl::GetUniformLocation(program, "emitmode"); //viewID = gl::GetUniformLocation(program, "view"); //projectionID = gl::GetUniformLocation(program, "projection"); lightposID = gl::GetUniformLocation(program, "lightpos"); normalmatrixID = gl::GetUniformLocation(program, "normalmatrix"); uniform_colourmode = std::make_unique<guts::GLUniform<GLuint>>( program, "colourmode"); uniform_model = std::make_unique<guts::GLUniform<glm::mat4>>( program, "model"); uniform_view = std::make_unique<guts::GLUniform<glm::mat4>>( program, "view"); uniform_projection = std::make_unique<guts::GLUniform<glm::mat4>>( program, "projection"); /* create our sphere and cube objects */ aSphere = std::make_unique<guts::objs::Sphere>(numlats, numlongs); aCube = std::make_unique<guts::objs::Cube>(); } /* Called to update the display. Note that this function is called in the event loop in the wrapper class because we registered display as a callback function */ void display(guts::GlfwWindow *window) { /* Define the background colour */ gl::ClearColor(0.0f, 0.0f, 0.0f, 1.0f); /* Clear the colour and frame buffers */ gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); /* Enable depth test */ gl::Enable(gl::DEPTH_TEST); /* Make the compiled shader program current */ gl::UseProgram(program); // Define our model transformation in a stack and // push the identity matrix onto the stack stack<mat4> model; model.push(mat4(1.0f)); // Define the normal matrix mat3 normalmatrix; // Projection matrix : 45� Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units mat4 projection = perspective(30.0f, aspect_ratio, 0.1f, 100.0f); // Camera matrix mat4 view = lookAt( vec3(0, 0, 4), // Camera is at (0,0,4), in World Space vec3(0, 0, 0), // and looks at the origin vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down) ); // Apply rotations to the view position. This wil get appleid to the whole scene view = rotate(view, -vx, vec3(1, 0, 0)); //rotating in clockwise direction around x-axis view = rotate(view, -vy, vec3(0, 1, 0)); //rotating in clockwise direction around y-axis view = rotate(view, -vz, vec3(0, 0, 1)); // Define the light position and transform by the view matrix vec4 lightpos = view * vec4(light_x, light_y, light_z, 1.0); // Send our projection and view uniforms to the currently bound shader // I do that here because they are the same for all objects //gl::Uniform1ui(colourmodeID, colourmode); uniform_colourmode->Set(colourmode); //gl::UniformMatrix4fv(viewID, 1, gl::FALSE_, &view[0][0]); uniform_view->Set(view); //gl::UniformMatrix4fv(projectionID, 1, gl::FALSE_, &projection[0][0]); uniform_projection->Set(projection); gl::Uniform4fv(lightposID, 1, value_ptr(lightpos)); /* Draw a small sphere in the lightsource position to visually represent the light source */ model.push(model.top()); { model.top() = translate(model.top(), vec3(light_x, light_y, light_z)); model.top() = scale(model.top(), vec3(0.05f, 0.05f, 0.05f)); // make a small sphere // Recalculate the normal matrix and send the model and normal matrices to the vertex shader // Recalculate the normal matrix and send to the vertex shader // Recalculate the normal matrix and send to the vertex shader // Recalculate the normal matrix and send to the vertex shader // Recalculate the normal matrix and send to the vertex shader //gl::UniformMatrix4fv(modelID, 1, gl::FALSE_, &(model.top()[0][0])); uniform_model->Set(model.top()); normalmatrix = guts::InverseTranspose(mat3(view * model.top())); gl::UniformMatrix3fv(normalmatrixID, 1, gl::FALSE_, &normalmatrix[0][0]); /* Draw our lightposition sphere with emit mode on*/ emitmode = 1; gl::Uniform1ui(emitmodeID, emitmode); aSphere->Render(static_cast<guts::GLRenderMode>(drawmode)); emitmode = 0; gl::Uniform1ui(emitmodeID, emitmode); } model.pop(); // Define the global model transformations (rotate and scale). Note, we're not modifying thel ight source position model.top() = scale(model.top(), vec3(model_scale, model_scale, model_scale));//scale equally in all axis model.top() = rotate(model.top(), -angle_x, glm::vec3(1, 0, 0)); //rotating in clockwise direction around x-axis model.top() = rotate(model.top(), -angle_y, glm::vec3(0, 1, 0)); //rotating in clockwise direction around y-axis model.top() = rotate(model.top(), -angle_z, glm::vec3(0, 0, 1)); //rotating in clockwise direction around z-axis // This block of code draws the cube model.push(model.top()); { // Define the model transformations for the cube model.top() = translate(model.top(), vec3(x + 0.5f, y, z)); // Send the model uniform and normal matrix to the currently bound shader, //gl::UniformMatrix4fv(modelID, 1, gl::FALSE_, &(model.top()[0][0])); uniform_model->Set(model.top()); // Recalculate the normal matrix and send to the vertex shader normalmatrix = guts::InverseTranspose(mat3(view * model.top())); gl::UniformMatrix3fv(normalmatrixID, 1, gl::FALSE_, &normalmatrix[0][0]); /* Draw our cube*/ aCube->Render(static_cast<guts::GLRenderMode>(drawmode)); } model.pop(); // This block of code draws the sphere model.push(model.top()); { model.top() = translate(model.top(), vec3(-x - 0.5f, 0, 0)); model.top() = scale(model.top(), vec3(model_scale / 3.f, model_scale / 3.f, model_scale / 3.f));//scale equally in all axis // Recalculate the normal matrix and send the model and normal matrices to the vertex shader // Recalculate the normal matrix and send to the vertex shader // Recalculate the normal matrix and send to the vertex shader // Recalculate the normal matrix and send to the vertex shader // Recalculate the normal matrix and send to the vertex shader //gl::UniformMatrix4fv(modelID, 1, gl::FALSE_, &(model.top()[0][0])); uniform_model->Set(model.top()); normalmatrix = guts::InverseTranspose(mat3(view * model.top())); gl::UniformMatrix3fv(normalmatrixID, 1, gl::FALSE_, &normalmatrix[0][0]); aSphere->Render(static_cast<guts::GLRenderMode>(drawmode)); // Draw our sphere } model.pop(); gl::DisableVertexAttribArray(0); gl::UseProgram(0); /* Modify our animation variables */ angle_x += angle_inc_x; angle_y += angle_inc_y; angle_z += angle_inc_z; } /* Called whenever the window is resized. The new window size is given, in pixels. */ static void reshape(GLFWwindow *window, int w, int h) { gl::Viewport(0, 0, (GLsizei) w, (GLsizei) h); aspect_ratio = ((float) w / 640.f * 4.f) / ((float) h / 480.f * 3.f); } /* change view angle, exit upon ESC */ static void keyCallback(GLFWwindow *window, int key, int s, int action, int mods) { /* Enable this call if you want to disable key responses to a held down key*/ //if (action != GLFW_PRESS) return; if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, gl::TRUE_); if (key == 'Q') angle_inc_x -= 0.05f; if (key == 'W') angle_inc_x += 0.05f; if (key == 'E') angle_inc_y -= 0.05f; if (key == 'R') angle_inc_y += 0.05f; if (key == 'T') angle_inc_z -= 0.05f; if (key == 'Y') angle_inc_z += 0.05f; if (key == 'A') model_scale -= 0.02f; if (key == 'S') model_scale += 0.02f; if (key == 'Z') x -= 0.05f; if (key == 'X') x += 0.05f; if (key == 'C') y -= 0.05f; if (key == 'V') y += 0.05f; if (key == 'B') z -= 0.05f; if (key == 'N') z += 0.05f; if (key == '1') light_x -= 0.05f; if (key == '2') light_x += 0.05f; if (key == '3') light_y -= 0.05f; if (key == '4') light_y += 0.05f; if (key == '5') light_z -= 0.05f; if (key == '6') light_z += 0.05f; if (key == '7') vx -= 1.f; if (key == '8') vx += 1.f; if (key == '9') vy -= 1.f; if (key == '0') vy += 1.f; if (key == 'O') vz -= 1.f; if (key == 'P') vz += 1.f; if (key == 'M' && action != GLFW_PRESS) { colourmode = !colourmode; cout << "colourmode=" << colourmode << endl; } /* Cycle between drawing vertices, mesh and filled polygons */ if (key == ',' && action != GLFW_PRESS) { drawmode++; if (drawmode > 2) drawmode = 0; } } /* Entry point of program */ int main(int argc, char *argv[]) { guts::GlfwWindow *glw = new guts::GlfwWindow(1024, 768, "Position light example"); glw->SetRenderer(display); glw->SetKeyCallback(keyCallback); glw->SetReshapeCallback(reshape); init(glw); glw->EventLoop(); delete (glw); return 0; }
37.012048
437
0.638997
Emberwalker
801688ce44ba2583481e7be9f6b3ee0f1866eac3
28,015
cpp
C++
B2G/gecko/netwerk/cache/nsDiskCacheStreams.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/netwerk/cache/nsDiskCacheStreams.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/netwerk/cache/nsDiskCacheStreams.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsDiskCache.h" #include "nsDiskCacheDevice.h" #include "nsDiskCacheStreams.h" #include "nsCacheService.h" #include "mozilla/FileUtils.h" #include "nsIDiskCacheStreamInternal.h" #include "nsThreadUtils.h" #include "mozilla/Telemetry.h" #include "mozilla/TimeStamp.h" // Assumptions: // - cache descriptors live for life of streams // - streams will only be used by FileTransport, // they will not be directly accessible to clients // - overlapped I/O is NOT supported /****************************************************************************** * nsDiskCacheInputStream *****************************************************************************/ class nsDiskCacheInputStream : public nsIInputStream { public: nsDiskCacheInputStream( nsDiskCacheStreamIO * parent, PRFileDesc * fileDesc, const char * buffer, uint32_t endOfStream); virtual ~nsDiskCacheInputStream(); NS_DECL_ISUPPORTS NS_DECL_NSIINPUTSTREAM private: nsDiskCacheStreamIO * mStreamIO; // backpointer to parent PRFileDesc * mFD; const char * mBuffer; uint32_t mStreamEnd; uint32_t mPos; // stream position bool mClosed; }; NS_IMPL_THREADSAFE_ISUPPORTS1(nsDiskCacheInputStream, nsIInputStream) nsDiskCacheInputStream::nsDiskCacheInputStream( nsDiskCacheStreamIO * parent, PRFileDesc * fileDesc, const char * buffer, uint32_t endOfStream) : mStreamIO(parent) , mFD(fileDesc) , mBuffer(buffer) , mStreamEnd(endOfStream) , mPos(0) , mClosed(false) { NS_ADDREF(mStreamIO); mStreamIO->IncrementInputStreamCount(); } nsDiskCacheInputStream::~nsDiskCacheInputStream() { Close(); mStreamIO->DecrementInputStreamCount(); NS_RELEASE(mStreamIO); } NS_IMETHODIMP nsDiskCacheInputStream::Close() { if (!mClosed) { if (mFD) { (void) PR_Close(mFD); mFD = nullptr; } mClosed = true; } return NS_OK; } NS_IMETHODIMP nsDiskCacheInputStream::Available(uint64_t * bytesAvailable) { if (mClosed) return NS_BASE_STREAM_CLOSED; if (mStreamEnd < mPos) return NS_ERROR_UNEXPECTED; *bytesAvailable = mStreamEnd - mPos; return NS_OK; } NS_IMETHODIMP nsDiskCacheInputStream::Read(char * buffer, uint32_t count, uint32_t * bytesRead) { *bytesRead = 0; if (mClosed) { CACHE_LOG_DEBUG(("CACHE: nsDiskCacheInputStream::Read " "[stream=%p] stream was closed", this, buffer, count)); return NS_OK; } if (mPos == mStreamEnd) { CACHE_LOG_DEBUG(("CACHE: nsDiskCacheInputStream::Read " "[stream=%p] stream at end of file", this, buffer, count)); return NS_OK; } if (mPos > mStreamEnd) { CACHE_LOG_DEBUG(("CACHE: nsDiskCacheInputStream::Read " "[stream=%p] stream past end of file (!)", this, buffer, count)); return NS_ERROR_UNEXPECTED; } if (count > mStreamEnd - mPos) count = mStreamEnd - mPos; if (mFD) { // just read from file int32_t result = PR_Read(mFD, buffer, count); if (result < 0) { nsresult rv = NS_ErrorAccordingToNSPR(); CACHE_LOG_DEBUG(("CACHE: nsDiskCacheInputStream::Read PR_Read failed" "[stream=%p, rv=%d, NSPR error %s", this, int(rv), PR_ErrorToName(PR_GetError()))); return rv; } mPos += (uint32_t)result; *bytesRead = (uint32_t)result; } else if (mBuffer) { // read data from mBuffer memcpy(buffer, mBuffer + mPos, count); mPos += count; *bytesRead = count; } else { // no data source for input stream } CACHE_LOG_DEBUG(("CACHE: nsDiskCacheInputStream::Read " "[stream=%p, count=%ud, byteRead=%ud] ", this, unsigned(count), unsigned(*bytesRead))); return NS_OK; } NS_IMETHODIMP nsDiskCacheInputStream::ReadSegments(nsWriteSegmentFun writer, void * closure, uint32_t count, uint32_t * bytesRead) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDiskCacheInputStream::IsNonBlocking(bool * nonBlocking) { *nonBlocking = false; return NS_OK; } /****************************************************************************** * nsDiskCacheOutputStream *****************************************************************************/ class nsDiskCacheOutputStream : public nsIOutputStream , public nsIDiskCacheStreamInternal { public: nsDiskCacheOutputStream( nsDiskCacheStreamIO * parent); virtual ~nsDiskCacheOutputStream(); NS_DECL_ISUPPORTS NS_DECL_NSIOUTPUTSTREAM NS_DECL_NSIDISKCACHESTREAMINTERNAL void ReleaseStreamIO() { NS_IF_RELEASE(mStreamIO); } private: nsDiskCacheStreamIO * mStreamIO; // backpointer to parent bool mClosed; }; NS_IMPL_THREADSAFE_ISUPPORTS2(nsDiskCacheOutputStream, nsIOutputStream, nsIDiskCacheStreamInternal) nsDiskCacheOutputStream::nsDiskCacheOutputStream( nsDiskCacheStreamIO * parent) : mStreamIO(parent) , mClosed(false) { NS_ADDREF(mStreamIO); } nsDiskCacheOutputStream::~nsDiskCacheOutputStream() { Close(); ReleaseStreamIO(); } NS_IMETHODIMP nsDiskCacheOutputStream::Close() { nsresult rv = NS_OK; mozilla::TimeStamp start = mozilla::TimeStamp::Now(); if (!mClosed) { mClosed = true; // tell parent streamIO we are closing rv = mStreamIO->CloseOutputStream(this); } mozilla::Telemetry::ID id; if (NS_IsMainThread()) id = mozilla::Telemetry::NETWORK_DISK_CACHE_OUTPUT_STREAM_CLOSE_MAIN_THREAD; else id = mozilla::Telemetry::NETWORK_DISK_CACHE_OUTPUT_STREAM_CLOSE; mozilla::Telemetry::AccumulateTimeDelta(id, start); return rv; } NS_IMETHODIMP nsDiskCacheOutputStream::CloseInternal() { nsresult rv = NS_OK; mozilla::TimeStamp start = mozilla::TimeStamp::Now(); if (!mClosed) { mClosed = true; // tell parent streamIO we are closing rv = mStreamIO->CloseOutputStreamInternal(this); } mozilla::Telemetry::ID id; if (NS_IsMainThread()) id = mozilla::Telemetry::NETWORK_DISK_CACHE_OUTPUT_STREAM_CLOSE_INTERNAL_MAIN_THREAD; else id = mozilla::Telemetry::NETWORK_DISK_CACHE_OUTPUT_STREAM_CLOSE_INTERNAL; mozilla::Telemetry::AccumulateTimeDelta(id, start); return rv; } NS_IMETHODIMP nsDiskCacheOutputStream::Flush() { if (mClosed) return NS_BASE_STREAM_CLOSED; // yeah, yeah, well get to it...eventually... return NS_OK; } NS_IMETHODIMP nsDiskCacheOutputStream::Write(const char *buf, uint32_t count, uint32_t *bytesWritten) { if (mClosed) return NS_BASE_STREAM_CLOSED; return mStreamIO->Write(buf, count, bytesWritten); } NS_IMETHODIMP nsDiskCacheOutputStream::WriteFrom(nsIInputStream *inStream, uint32_t count, uint32_t *bytesWritten) { NS_NOTREACHED("WriteFrom"); return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDiskCacheOutputStream::WriteSegments( nsReadSegmentFun reader, void * closure, uint32_t count, uint32_t * bytesWritten) { NS_NOTREACHED("WriteSegments"); return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDiskCacheOutputStream::IsNonBlocking(bool * nonBlocking) { *nonBlocking = false; return NS_OK; } /****************************************************************************** * nsDiskCacheStreamIO *****************************************************************************/ NS_IMPL_THREADSAFE_ISUPPORTS0(nsDiskCacheStreamIO) // we pick 16k as the max buffer size because that is the threshold above which // we are unable to store the data in the cache block files // see nsDiskCacheMap.[cpp,h] #define kMaxBufferSize (16 * 1024) nsDiskCacheStreamIO::nsDiskCacheStreamIO(nsDiskCacheBinding * binding) : mBinding(binding) , mOutStream(nullptr) , mInStreamCount(0) , mFD(nullptr) , mStreamPos(0) , mStreamEnd(0) , mBufPos(0) , mBufEnd(0) , mBufSize(0) , mBufDirty(false) , mBuffer(nullptr) { mDevice = (nsDiskCacheDevice *)mBinding->mCacheEntry->CacheDevice(); // acquire "death grip" on cache service nsCacheService *service = nsCacheService::GlobalInstance(); NS_ADDREF(service); } nsDiskCacheStreamIO::~nsDiskCacheStreamIO() { Close(); // release "death grip" on cache service nsCacheService *service = nsCacheService::GlobalInstance(); NS_RELEASE(service); } void nsDiskCacheStreamIO::Close() { // this should only be called from our destructor // no one is interested in us anymore, so we don't need to grab any locks // assert streams closed NS_ASSERTION(!mOutStream, "output stream still open"); NS_ASSERTION(mInStreamCount == 0, "input stream still open"); NS_ASSERTION(!mFD, "file descriptor not closed"); DeleteBuffer(); } // NOTE: called with service lock held nsresult nsDiskCacheStreamIO::GetInputStream(uint32_t offset, nsIInputStream ** inputStream) { NS_ENSURE_ARG_POINTER(inputStream); NS_ENSURE_TRUE(offset == 0, NS_ERROR_NOT_IMPLEMENTED); *inputStream = nullptr; if (!mBinding) return NS_ERROR_NOT_AVAILABLE; if (mOutStream) { NS_WARNING("already have an output stream open"); return NS_ERROR_NOT_AVAILABLE; } nsresult rv; PRFileDesc * fd = nullptr; mStreamEnd = mBinding->mCacheEntry->DataSize(); if (mStreamEnd == 0) { // there's no data to read NS_ASSERTION(!mBinding->mRecord.DataLocationInitialized(), "storage allocated for zero data size"); } else if (mBinding->mRecord.DataFile() == 0) { // open file desc for data rv = OpenCacheFile(PR_RDONLY, &fd); if (NS_FAILED(rv)) return rv; // unable to open file NS_ASSERTION(fd, "cache stream lacking open file."); } else if (!mBuffer) { // read block file for data rv = ReadCacheBlocks(); if (NS_FAILED(rv)) return rv; } // else, mBuffer already contains all of the data (left over from a // previous block-file read or write). NS_ASSERTION(!(fd && mBuffer), "ambiguous data sources for input stream"); // create a new input stream nsDiskCacheInputStream * inStream = new nsDiskCacheInputStream(this, fd, mBuffer, mStreamEnd); if (!inStream) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(*inputStream = inStream); return NS_OK; } // NOTE: called with service lock held nsresult nsDiskCacheStreamIO::GetOutputStream(uint32_t offset, nsIOutputStream ** outputStream) { NS_ENSURE_ARG_POINTER(outputStream); *outputStream = nullptr; if (!mBinding) return NS_ERROR_NOT_AVAILABLE; NS_ASSERTION(!mOutStream, "already have an output stream open"); NS_ASSERTION(mInStreamCount == 0, "we already have input streams open"); if (mOutStream || mInStreamCount) return NS_ERROR_NOT_AVAILABLE; // mBuffer lazily allocated, but might exist if a previous stream already // created one. mBufPos = 0; mStreamPos = 0; mStreamEnd = mBinding->mCacheEntry->DataSize(); nsresult rv; if (offset) { rv = Seek(PR_SEEK_SET, offset); if (NS_FAILED(rv)) return rv; } rv = SetEOF(); if (NS_FAILED(rv)) return rv; // create a new output stream mOutStream = new nsDiskCacheOutputStream(this); if (!mOutStream) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(*outputStream = mOutStream); return NS_OK; } nsresult nsDiskCacheStreamIO::ClearBinding() { nsresult rv = NS_OK; if (mBinding && mOutStream) rv = Flush(); mBinding = nullptr; return rv; } nsresult nsDiskCacheStreamIO::CloseOutputStream(nsDiskCacheOutputStream * outputStream) { nsCacheServiceAutoLock lock(LOCK_TELEM(NSDISKCACHESTREAMIO_CLOSEOUTPUTSTREAM)); // grab service lock return CloseOutputStreamInternal(outputStream); } nsresult nsDiskCacheStreamIO::CloseOutputStreamInternal( nsDiskCacheOutputStream * outputStream) { nsresult rv; if (outputStream != mOutStream) { NS_WARNING("mismatched output streams"); return NS_ERROR_UNEXPECTED; } // output stream is closing if (!mBinding) { // if we're severed, just clear member variables NS_ASSERTION(!mBufDirty, "oops"); mOutStream = nullptr; outputStream->ReleaseStreamIO(); return NS_ERROR_NOT_AVAILABLE; } rv = Flush(); if (NS_FAILED(rv)) NS_WARNING("Flush() failed"); mOutStream = nullptr; return rv; } nsresult nsDiskCacheStreamIO::Flush() { NS_ASSERTION(mBinding, "oops"); CACHE_LOG_DEBUG(("CACHE: Flush [%x doomed=%u]\n", mBinding->mRecord.HashNumber(), mBinding->mDoomed)); if (!mBufDirty) { if (mFD) { (void) PR_Close(mFD); mFD = nullptr; } return NS_OK; } // write data to cache blocks, or flush mBuffer to file nsDiskCacheMap *cacheMap = mDevice->CacheMap(); // get map reference nsresult rv; bool written = false; if ((mStreamEnd <= kMaxBufferSize) && (mBinding->mCacheEntry->StoragePolicy() != nsICache::STORE_ON_DISK_AS_FILE)) { // store data (if any) in cache block files mBufDirty = false; // delete existing storage nsDiskCacheRecord * record = &mBinding->mRecord; if (record->DataLocationInitialized()) { rv = cacheMap->DeleteStorage(record, nsDiskCache::kData); if (NS_FAILED(rv)) { NS_WARNING("cacheMap->DeleteStorage() failed."); return rv; } if (mFD) { PR_Close(mFD); mFD = nullptr; } } // flush buffer to block files written = true; if (mStreamEnd > 0) { rv = cacheMap->WriteDataCacheBlocks(mBinding, mBuffer, mBufEnd); if (NS_FAILED(rv)) { NS_WARNING("WriteDataCacheBlocks() failed."); written = false; } } } if (!written) { // make sure we save as separate file rv = FlushBufferToFile(); // initializes DataFileLocation() if necessary if (mFD) { // Update the file size of the disk file in the cache UpdateFileSize(); // close file descriptor (void) PR_Close(mFD); mFD = nullptr; } else NS_WARNING("no file descriptor"); // close mFD first if possible before returning if FlushBufferToFile // failed NS_ENSURE_SUCCESS(rv, rv); // since the data location is on disk as a single file, the only value // in keeping mBuffer around is to avoid an extra malloc the next time // we need to write to this file. reading will use a file descriptor. // therefore, it's probably not worth optimizing for the subsequent // write, so we unconditionally delete mBuffer here. DeleteBuffer(); } // XXX do we need this here? WriteDataCacheBlocks() calls UpdateRecord() // update cache map if entry isn't doomed if (!mBinding->mDoomed) { rv = cacheMap->UpdateRecord(&mBinding->mRecord); if (NS_FAILED(rv)) { NS_WARNING("cacheMap->UpdateRecord() failed."); return rv; // XXX doom cache entry } } return NS_OK; } // assumptions: // only one thread writing at a time // never have both output and input streams open // OnDataSizeChanged() will have already been called to update entry->DataSize() nsresult nsDiskCacheStreamIO::Write( const char * buffer, uint32_t count, uint32_t * bytesWritten) { nsresult rv = NS_OK; nsCacheServiceAutoLock lock(LOCK_TELEM(NSDISKCACHESTREAMIO_WRITE)); // grab service lock if (!mBinding) return NS_ERROR_NOT_AVAILABLE; if (mInStreamCount) { // we have open input streams already // this is an error until we support overlapped I/O NS_WARNING("Attempting to write to cache entry with open input streams.\n"); return NS_ERROR_NOT_AVAILABLE; } NS_ASSERTION(count, "Write called with count of zero"); NS_ASSERTION(mBufPos <= mBufEnd, "streamIO buffer corrupted"); uint32_t bytesLeft = count; bool flushed = false; while (bytesLeft) { if (mBufPos == mBufSize) { if (mBufSize < kMaxBufferSize) { mBufSize = kMaxBufferSize; char *buffer = mBuffer; mBuffer = (char *) realloc(mBuffer, mBufSize); if (!mBuffer) { free(buffer); mBufSize = 0; break; } } else { nsresult rv = FlushBufferToFile(); if (NS_FAILED(rv)) break; flushed = true; } } uint32_t chunkSize = bytesLeft; if (chunkSize > (mBufSize - mBufPos)) chunkSize = mBufSize - mBufPos; memcpy(mBuffer + mBufPos, buffer, chunkSize); mBufDirty = true; mBufPos += chunkSize; bytesLeft -= chunkSize; buffer += chunkSize; if (mBufEnd < mBufPos) mBufEnd = mBufPos; } if (bytesLeft) { *bytesWritten = 0; return NS_ERROR_FAILURE; } *bytesWritten = count; // update mStreamPos, mStreamEnd mStreamPos += count; if (mStreamEnd < mStreamPos) { mStreamEnd = mStreamPos; NS_ASSERTION(mBinding->mCacheEntry->DataSize() == mStreamEnd, "bad stream"); // If we have flushed to a file, update the file size if (flushed && mFD) { UpdateFileSize(); } } return rv; } void nsDiskCacheStreamIO::UpdateFileSize() { NS_ASSERTION(mFD, "nsDiskCacheStreamIO::UpdateFileSize should not have been called"); nsDiskCacheRecord * record = &mBinding->mRecord; const uint32_t oldSizeK = record->DataFileSize(); uint32_t newSizeK = (mStreamEnd + 0x03FF) >> 10; // make sure the size won't overflow (bug #651100) if (newSizeK > kMaxDataSizeK) newSizeK = kMaxDataSizeK; if (newSizeK == oldSizeK) return; record->SetDataFileSize(newSizeK); // update cache size totals nsDiskCacheMap * cacheMap = mDevice->CacheMap(); cacheMap->DecrementTotalSize(oldSizeK); // decrement old size cacheMap->IncrementTotalSize(newSizeK); // increment new size if (!mBinding->mDoomed) { nsresult rv = cacheMap->UpdateRecord(record); if (NS_FAILED(rv)) { NS_WARNING("cacheMap->UpdateRecord() failed."); // XXX doom cache entry? } } } nsresult nsDiskCacheStreamIO::OpenCacheFile(int flags, PRFileDesc ** fd) { NS_ENSURE_ARG_POINTER(fd); CACHE_LOG_DEBUG(("nsDiskCacheStreamIO::OpenCacheFile")); nsresult rv; nsDiskCacheMap * cacheMap = mDevice->CacheMap(); rv = cacheMap->GetLocalFileForDiskCacheRecord(&mBinding->mRecord, nsDiskCache::kData, !!(flags & PR_CREATE_FILE), getter_AddRefs(mLocalFile)); if (NS_FAILED(rv)) return rv; // create PRFileDesc for input stream - the 00600 is just for consistency rv = mLocalFile->OpenNSPRFileDesc(flags, 00600, fd); if (NS_FAILED(rv)) return rv; // unable to open file return NS_OK; } nsresult nsDiskCacheStreamIO::ReadCacheBlocks() { NS_ASSERTION(mStreamEnd == mBinding->mCacheEntry->DataSize(), "bad stream"); NS_ASSERTION(mStreamEnd <= kMaxBufferSize, "data too large for buffer"); nsDiskCacheRecord * record = &mBinding->mRecord; if (!record->DataLocationInitialized()) return NS_OK; NS_ASSERTION(record->DataFile() != kSeparateFile, "attempt to read cache blocks on separate file"); if (!mBuffer) { // allocate buffer mBuffer = (char *) malloc(mStreamEnd); if (!mBuffer) { return NS_ERROR_OUT_OF_MEMORY; } mBufSize = mStreamEnd; } // read data stored in cache block files nsDiskCacheMap *map = mDevice->CacheMap(); // get map reference nsresult rv = map->ReadDataCacheBlocks(mBinding, mBuffer, mStreamEnd); if (NS_FAILED(rv)) return rv; // update streamIO variables mBufPos = 0; mBufEnd = mStreamEnd; return NS_OK; } nsresult nsDiskCacheStreamIO::FlushBufferToFile() { nsresult rv; nsDiskCacheRecord * record = &mBinding->mRecord; if (!mFD) { if (record->DataLocationInitialized() && (record->DataFile() > 0)) { // remove cache block storage nsDiskCacheMap * cacheMap = mDevice->CacheMap(); rv = cacheMap->DeleteStorage(record, nsDiskCache::kData); if (NS_FAILED(rv)) return rv; } record->SetDataFileGeneration(mBinding->mGeneration); // allocate file rv = OpenCacheFile(PR_RDWR | PR_CREATE_FILE, &mFD); if (NS_FAILED(rv)) return rv; int64_t dataSize = mBinding->mCacheEntry->PredictedDataSize(); if (dataSize != -1) mozilla::fallocate(mFD, NS_MIN<int64_t>(dataSize, kPreallocateLimit)); } // write buffer int32_t bytesWritten = PR_Write(mFD, mBuffer, mBufEnd); if (uint32_t(bytesWritten) != mBufEnd) { NS_WARNING("failed to flush all data"); return NS_ERROR_UNEXPECTED; // NS_ErrorAccordingToNSPR() } mBufDirty = false; // reset buffer mBufPos = 0; mBufEnd = 0; return NS_OK; } void nsDiskCacheStreamIO::DeleteBuffer() { if (mBuffer) { NS_ASSERTION(!mBufDirty, "deleting dirty buffer"); free(mBuffer); mBuffer = nullptr; mBufPos = 0; mBufEnd = 0; mBufSize = 0; } } // NOTE: called with service lock held nsresult nsDiskCacheStreamIO::Seek(int32_t whence, int32_t offset) { int32_t newPos; if (!mBinding) return NS_ERROR_NOT_AVAILABLE; if (uint32_t(offset) > mStreamEnd) return NS_ERROR_FAILURE; if (mBinding->mRecord.DataLocationInitialized()) { if (mBinding->mRecord.DataFile() == 0) { if (!mFD) { // we need an mFD, we better open it now nsresult rv = OpenCacheFile(PR_RDWR | PR_CREATE_FILE, &mFD); if (NS_FAILED(rv)) return rv; } } } if (mFD) { // do we have data in the buffer that needs to be flushed? if (mBufDirty) { // XXX optimization: are we just moving within the current buffer? nsresult rv = FlushBufferToFile(); if (NS_FAILED(rv)) return rv; } newPos = PR_Seek(mFD, offset, (PRSeekWhence)whence); if (newPos == -1) return NS_ErrorAccordingToNSPR(); mStreamPos = (uint32_t) newPos; mBufPos = 0; mBufEnd = 0; return NS_OK; } // else, seek in mBuffer switch(whence) { case PR_SEEK_SET: newPos = offset; break; case PR_SEEK_CUR: // relative from current posistion newPos = offset + (uint32_t)mStreamPos; break; case PR_SEEK_END: // relative from end newPos = offset + (uint32_t)mBufEnd; break; default: return NS_ERROR_INVALID_ARG; } // read data into mBuffer if not read yet. if (mStreamEnd && !mBufEnd) { if (newPos > 0) { nsresult rv = ReadCacheBlocks(); if (NS_FAILED(rv)) return rv; } } // stream buffer sanity checks NS_ASSERTION(mBufEnd <= kMaxBufferSize, "bad stream"); NS_ASSERTION(mBufPos <= mBufEnd, "bad stream"); NS_ASSERTION(mStreamPos == mBufPos, "bad stream"); NS_ASSERTION(mStreamEnd == mBufEnd, "bad stream"); if ((newPos < 0) || (uint32_t(newPos) > mBufEnd)) { NS_WARNING("seek offset out of range"); return NS_ERROR_INVALID_ARG; } mStreamPos = newPos; mBufPos = newPos; return NS_OK; } // called only from nsDiskCacheOutputStream::Tell nsresult nsDiskCacheStreamIO::Tell(uint32_t * result) { NS_ENSURE_ARG_POINTER(result); *result = mStreamPos; return NS_OK; } // NOTE: called with service lock held nsresult nsDiskCacheStreamIO::SetEOF() { nsresult rv; bool needToCloseFD = false; NS_ASSERTION(mStreamPos <= mStreamEnd, "bad stream"); if (!mBinding) return NS_ERROR_NOT_AVAILABLE; if (mBinding->mRecord.DataLocationInitialized()) { if (mBinding->mRecord.DataFile() == 0) { if (!mFD) { // we need an mFD, we better open it now rv = OpenCacheFile(PR_RDWR | PR_CREATE_FILE, &mFD); if (NS_FAILED(rv)) return rv; needToCloseFD = true; } } else { // data in cache block files if ((mStreamPos != 0) && (mStreamPos != mBufPos)) { // only read data if there will be some left after truncation rv = ReadCacheBlocks(); if (NS_FAILED(rv)) return rv; } // We need to make sure we reflect this change in Flush(). // In particular, if mStreamPos is 0 and we never write to // the buffer, we want the storage to be deleted. mBufDirty = true; } } if (mFD) { rv = nsDiskCache::Truncate(mFD, mStreamPos); #ifdef DEBUG uint32_t oldSizeK = (mStreamEnd + 0x03FF) >> 10; NS_ASSERTION(mBinding->mRecord.DataFileSize() == oldSizeK, "bad disk cache entry size"); } else { // data stored in buffer. NS_ASSERTION(mStreamEnd <= kMaxBufferSize, "buffer truncation inadequate"); NS_ASSERTION(mBufPos == mStreamPos, "bad stream"); NS_ASSERTION(mBuffer ? mBufEnd == mStreamEnd : true, "bad stream"); #endif } NS_ASSERTION(mStreamEnd == mBinding->mCacheEntry->DataSize(), "cache entry not updated"); // we expect nsCacheEntryDescriptor::TransportWrapper::OpenOutputStream() // to eventually update the cache entry mStreamEnd = mStreamPos; mBufEnd = mBufPos; if (mFD) { UpdateFileSize(); if (needToCloseFD) { (void) PR_Close(mFD); mFD = nullptr; } } return NS_OK; }
28.911249
107
0.593539
wilebeast
80187f641b4aaa50fe7b57d6a3437056fcfe5292
3,443
hpp
C++
source/gameos/include/linkedlist.hpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/gameos/include/linkedlist.hpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/gameos/include/linkedlist.hpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
#pragma once //===========================================================================// // File: LinkedList.hpp // // Contents: Linked list routines // //---------------------------------------------------------------------------// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// class gosLink { public: gosLink* Next; gosLink* Prev; PVOID linkData; public: gosLink() { linkData = 0; Next = 0; Prev = 0; } gosLink(PVOID ptr) { linkData = ptr; Next = 0; Prev = 0; } virtual ~gosLink() { Next = 0; Prev = 0; } gosLink* GetNext() { return (gosLink*)linkData; } }; template <class T> class LinkedList { public: gosLink* m_Head; int32_t m_Size; public: LinkedList() { m_Head = 0; m_Size = 0; }; LinkedList(T ptr) { gosLink* newlink = (gosLink*)malloc(sizeof(gosLink)); m_Head = newlink; m_Head->Next = 0; m_Size = 1; }; ~LinkedList() { while (m_Head != 0) Del((T)m_Head->linkData); }; void Add(T ptr) { gosLink* newlink = (gosLink*)malloc(sizeof(gosLink)); newlink->linkData = ptr; newlink->Next = 0; newlink->Prev = 0; if (m_Head == 0) { m_Head = newlink; newlink->Next = 0; newlink->Prev = 0; } else { gosLink* tmp = m_Head; while (tmp->Next != 0) tmp = tmp->Next; tmp->Next = newlink; newlink->Next = 0; newlink->Prev = tmp; } m_Size += 1; } void Del(T ptr) { if (!m_Head) // YIK - Why does it need this! (Delete All surfaces used // to crash) return; gosLink* tmp = m_Head; if (tmp->linkData == (PVOID)ptr) { m_Head = tmp->Next; tmp->Prev = 0; m_Size -= 1; memset(tmp, 0, sizeof(tmp)); free(tmp); } else { gosLink* target; while (tmp->Next != 0) { if (tmp->Next->linkData == (PVOID)ptr) { target = tmp->Next; tmp->Next = target->Next; if (target->Next) target->Next->Prev = tmp; m_Size -= 1; free(target); memset(tmp, 0, sizeof(tmp)); return; } else { tmp = (gosLink*)tmp->Next; } } } } int32_t Size() { return m_Size; } T Get(int32_t index) { gosLink* tmp = m_Head; if (tmp == 0) { return 0; } while (index && tmp->Next) { tmp = tmp->Next; index--; } if (index != 0) { return 0; } else { return (T)tmp->linkData; } } }; template <class T> class LinkedListIterator { public: gosLink* m_Iterator; LinkedList<T>* m_List; public: LinkedListIterator(LinkedList<T>* list) { m_Iterator = list->m_Head; m_List = list; } ~LinkedListIterator() {} T Head() { m_Iterator = m_List->m_Head; if (m_List->m_Head == 0) return 0; return (T)((gosLink*)m_List->m_Head)->linkData; } T Tail() { m_Iterator = m_List->m_Head; if (!m_Iterator) return 0; while (m_Iterator->Next != 0) { m_Iterator = m_Iterator->Next; } return (T)((gosLink*)m_Iterator)->linkData; } T ReadAndNext() { gosLink* tmp = m_Iterator; if (tmp == 0) return (T)0; m_Iterator = m_Iterator->Next; return (T)((gosLink*)tmp)->linkData; } T ReadAndPrev() { gosLink* tmp = m_Iterator; if (tmp == 0) return (T)0; m_Iterator = m_Iterator->Prev; return (T)((gosLink*)tmp)->linkData; } T Next() { m_Iterator = m_Iterator->Next; if (m_Iterator == 0) return 0; return (T)m_Iterator->linkData; } };
16.960591
79
0.533256
mechasource
80190f529ea9128e88438cb7d6a9fb9d2fbfcb03
9,154
cpp
C++
rqt_multiplot_plugin/rqt_multiplot/src/rqt_multiplot/UrlItemModel.cpp
huying163/ros_environment
bac3343bf92e6fa2bd852baf261e80712564f990
[ "MIT" ]
8
2018-01-30T11:40:31.000Z
2021-05-03T05:52:47.000Z
rqt_multiplot_plugin/rqt_multiplot/src/rqt_multiplot/UrlItemModel.cpp
huying163/ros_environment
bac3343bf92e6fa2bd852baf261e80712564f990
[ "MIT" ]
null
null
null
rqt_multiplot_plugin/rqt_multiplot/src/rqt_multiplot/UrlItemModel.cpp
huying163/ros_environment
bac3343bf92e6fa2bd852baf261e80712564f990
[ "MIT" ]
1
2020-12-23T08:14:57.000Z
2020-12-23T08:14:57.000Z
/****************************************************************************** * Copyright (C) 2015 by Ralf Kaestner * * ralf.kaestner@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the Lesser 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 * * Lesser GNU General Public License for more details. * * * * You should have received a copy of the Lesser GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include <QStringList> #include "rqt_multiplot/UrlItemModel.h" namespace rqt_multiplot { /*****************************************************************************/ /* Constructors and Destructor */ /*****************************************************************************/ UrlItemModel::UrlItemModel(QObject* parent) { } UrlItemModel::~UrlItemModel() { for (QList<UrlItem*>::iterator it = schemeItems_.begin(); it != schemeItems_.end(); ++it) delete *it; } /*****************************************************************************/ /* Accessors */ /*****************************************************************************/ QString UrlItemModel::getUrl(const QModelIndex& index) const { if (index.isValid()) { UrlItem* item = static_cast<UrlItem*>(index.internalPointer()); UrlScheme* itemScheme = item->getScheme(); if (item->getType() == UrlItem::Scheme) return itemScheme->getPrefix()+"://"; else if (item->getType() == UrlItem::Host) return itemScheme->getPrefix()+"://"+itemScheme->getHost( item->getIndex()); else if (item->getType() == UrlItem::Path) { QModelIndex hostIndex = item->getIndex(UrlItem::Host); return itemScheme->getPrefix()+"://"+itemScheme->getHost(hostIndex)+ "/"+itemScheme->getPath(hostIndex, item->getIndex()); } } return QString(); } QString UrlItemModel::getFilePath(const QModelIndex& index) const { if (index.isValid()) { UrlItem* item = static_cast<UrlItem*>(index.internalPointer()); UrlScheme* itemScheme = item->getScheme(); if (item->getType() == UrlItem::Host) return itemScheme->getFilePath(item->getIndex(), QModelIndex()); else if (item->getType() == UrlItem::Path) { QModelIndex hostIndex = item->getIndex(UrlItem::Host); return itemScheme->getFilePath(hostIndex, item->getIndex()); } } return QString(); } QString UrlItemModel::getFilePath(const QString& url) const { QStringList urlParts = url.split("://"); if (urlParts.count() > 1) { QString prefix = urlParts[0]; for (QList<UrlScheme*>::const_iterator it = schemes_.begin(); it != schemes_.end(); ++it) { UrlScheme* scheme = *it; if (scheme->getPrefix() == prefix) { QStringList hostPathParts = urlParts[1].split("/"); QString host, path; if (hostPathParts.count() > 1) { host = hostPathParts[0]; hostPathParts.removeFirst(); path = hostPathParts.join("/"); } else host = urlParts[1]; return scheme->getFilePath(host, path); } } } return QString(); } UrlScheme* UrlItemModel::getScheme(const QModelIndex& index) const { if (index.isValid()) { UrlItem* item = static_cast<UrlItem*>(index.internalPointer()); if (item) return item->getScheme(); } return 0; } /*****************************************************************************/ /* Methods */ /*****************************************************************************/ void UrlItemModel::addScheme(UrlScheme* scheme) { schemes_.append(scheme); schemeItems_.append(new UrlItem(scheme)); connect(scheme, SIGNAL(resetStarted()), this, SLOT(schemeResetStarted())); connect(scheme, SIGNAL(resetFinished()), this, SLOT(schemeResetFinished())); connect(scheme, SIGNAL(pathLoaded(const QString&, const QString&)), this, SLOT(schemePathLoaded(const QString&, const QString&))); } int UrlItemModel::rowCount(const QModelIndex& parent) const { if (parent.column() <= 0) { if (parent.isValid()) { UrlItem* parentItem = static_cast<UrlItem*>(parent.internalPointer()); UrlScheme* parentScheme = parentItem->getScheme(); if (parentItem->getType() == UrlItem::Scheme) { size_t numHosts = parentScheme->getNumHosts(); if (!numHosts) return parentScheme->getNumPaths(QModelIndex()); else return numHosts; } else if (parentItem->getType() == UrlItem::Host) return parentScheme->getNumPaths(parentItem->getIndex()); else if (parentItem->getType() == UrlItem::Path) return parentScheme->getNumPaths(parentItem->getIndex( UrlItem::Host), parentItem->getIndex()); } else return schemes_.count(); } return 0; } int UrlItemModel::columnCount(const QModelIndex& parent) const { return 1; } QVariant UrlItemModel::data(const QModelIndex& index, int role) const { if (index.isValid()) { UrlItem* item = static_cast<UrlItem*>(index.internalPointer()); UrlScheme* itemScheme = item->getScheme(); if (item->getType() == UrlItem::Scheme) { if ((role == Qt::DisplayRole) || (role == Qt::EditRole)) return itemScheme->getPrefix()+"://"; } else if (item->getType() == UrlItem::Host) return itemScheme->getHostData(item->getIndex(), role); else if (item->getType() == UrlItem::Path) return itemScheme->getPathData(item->getIndex(), role); } return QVariant(); } QModelIndex UrlItemModel::index(int row, int column, const QModelIndex& parent) const { if (hasIndex(row, column, parent)) { if (parent.isValid()) { UrlItem* parentItem = static_cast<UrlItem*>(parent.internalPointer()); UrlScheme* parentScheme = parentItem->getScheme(); UrlItem* childItem = 0; if (parentItem->getType() == UrlItem::Scheme) { size_t numHosts = parentScheme->getNumHosts(); if (!numHosts) childItem = parentItem->addChild(row, UrlItem::Path, parentScheme->getPathIndex(QModelIndex(), row)); else childItem = parentItem->addChild(row, UrlItem::Host, parentScheme->getHostIndex(row)); } else if (parentItem->getType() == UrlItem::Host) childItem = parentItem->addChild(row, UrlItem::Path, parentScheme->getPathIndex(parentItem->getIndex(UrlItem::Host), row)); else if (parentItem->getType() == UrlItem::Path) childItem = parentItem->addChild(row, UrlItem::Path, parentScheme->getPathIndex(parentItem->getIndex(UrlItem::Host), row, parentItem->getIndex())); return createIndex(row, column, childItem); } else return createIndex(row, column, schemeItems_[row]); } return QModelIndex(); } QModelIndex UrlItemModel::parent(const QModelIndex& index) const { if (index.isValid()) { UrlItem* childItem = static_cast<UrlItem*>(index.internalPointer()); if (childItem) { UrlItem* parentItem = childItem->getParent(); if (parentItem) return createIndex(parentItem->getRow(), 0, parentItem); } } return QModelIndex(); } /*****************************************************************************/ /* Slots */ /*****************************************************************************/ void UrlItemModel::schemeResetStarted() { beginResetModel(); UrlScheme* scheme = static_cast<UrlScheme*>(sender()); int i = schemes_.indexOf(scheme); if (i >= 0) { delete schemeItems_[i]; schemeItems_[i] = new UrlItem(scheme); } } void UrlItemModel::schemeResetFinished() { endResetModel(); } void UrlItemModel::schemePathLoaded(const QString& host, const QString& path) { UrlScheme* scheme = static_cast<UrlScheme*>(sender()); QString url = scheme->getPrefix()+"://"+host; if (!path.isEmpty()) url += "/"+path; emit urlLoaded(url); } }
34.156716
80
0.538453
huying163
801aeba9d2d56daefc70741d6ed771cfe48bdc37
748
cpp
C++
经典算法练习题/翻转单词顺序序列.cpp
anbingxu666/WangDao-DataStructure
70dcd76c1e26852d659a01358ecb90b8eec2e2ba
[ "Apache-2.0" ]
382
2019-08-09T12:46:46.000Z
2022-03-31T08:38:48.000Z
经典算法练习题/翻转单词顺序序列.cpp
anbingxu666/WangDao-DataStructure
70dcd76c1e26852d659a01358ecb90b8eec2e2ba
[ "Apache-2.0" ]
1
2019-09-04T05:45:49.000Z
2020-12-17T12:02:22.000Z
经典算法练习题/翻转单词顺序序列.cpp
anbingxu666/WangDao-DataStructure
70dcd76c1e26852d659a01358ecb90b8eec2e2ba
[ "Apache-2.0" ]
86
2019-09-04T05:44:34.000Z
2022-03-08T05:06:00.000Z
// // Created by newLion on 2020-06-10. // #include <string> using namespace std; string ReverseSentence(string str) { if (str.empty()) return str; int i = 0, sz = str.size(); while (i < sz && str[i] == ' ') ++i; if (i == sz) return str; string ret = ""; //结果数组 string tmp = ""; //临时结果 bool hasstr = false; for (int i = sz - 1; i >= 0; --i) { // 合并一个单词 if (str[i] != ' ') { tmp = str[i] + tmp;; hasstr = true; } // 找到一个单词,将单词合并到结果串中 else if (str[i] == ' ' && hasstr) { ret = ret + tmp + " "; tmp = ""; hasstr = false; } } if (tmp != "") ret += tmp; return ret; }
19.684211
43
0.410428
anbingxu666
801e695b82291b98dbf5ec53ba811eb4107efb67
496
cpp
C++
Factory/examples/src/Derivee2.cpp
PhDunski/KoalaToolbox
ca2e46f886fe254324344ab0ddb612d1daa71e81
[ "MIT" ]
null
null
null
Factory/examples/src/Derivee2.cpp
PhDunski/KoalaToolbox
ca2e46f886fe254324344ab0ddb612d1daa71e81
[ "MIT" ]
null
null
null
Factory/examples/src/Derivee2.cpp
PhDunski/KoalaToolbox
ca2e46f886fe254324344ab0ddb612d1daa71e81
[ "MIT" ]
null
null
null
/** @file Derivee1.cpp * * Fournit la définition des fonctions membres de la classe Derivee2 * * Ce fichier permet de tester les classes de création d'objet au départ * de listes de paramètres à transmettre au constructeur * @author koala01 * @version 1.0 * @date 2013/12/15 */ #include <Derivee2.hpp> #include <iostream> void Derivee2::print() const{ std::cout<<"Derivee2 :" <<" str = "<< str_ <<" color : "<<color_<<std::endl; }
27.555556
74
0.610887
PhDunski
801f8b1416f4ea01aa775d1e7c0bdfa5ea0c6a27
39,876
cpp
C++
src/NetProtocol/Base/nNetConnector.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Base/nNetConnector.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Base/nNetConnector.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
#include <netprotocol.h> N::NetConnector:: NetConnector (void) : NetTalk ( ) { setParameter ( "Running" , true ) ; setParameter ( "Stopped" , true ) ; setParameter ( "ReadStopped" , true ) ; setParameter ( "WriteStopped" , true ) ; setParameter ( "Block" , false ) ; } N::NetConnector::~NetConnector (void) { } void N::NetConnector::Prepared (int flags) { } void N::NetConnector::Started (int flags) { } void N::NetConnector::Finished (int flags) { } bool N::NetConnector::AssignHost(void) { return false ; } bool N::NetConnector::BothChannels (void) { bool listening = false ; bool duty = false ; bool sleeping = true ; int state = 0 ; //////////////////////////////////////////////////////////////////////////// duty = Parameters [ "Running" ] . toBool ( ) ; setParameter ( "Stopped" , false ) ; setParameter ( "ReadStopped" , false ) ; setParameter ( "WriteStopped" , false ) ; //////////////////////////////////////////////////////////////////////////// if ( Parameters.contains("State" ) ) { state = Parameters [ "State" ] .toInt ( ) ; } else setParameter ( "State" , state ) ; ; //////////////////////////////////////////////////////////////////////////// AccessTime ( ) ; while ( duty ) { state = Parameters [ "State" ] .toInt ( ) ; switch ( state ) { case 0 : state = 101 ; sleeping = false ; setParameter ( "State" , state ) ; Prepend ( ) ; Prepared ( 3 ) ; AccessTime ( ) ; break ; case 101 : state = 102 ; sleeping = true ; AssignHost ( ) ; setParameter ( "State" , state ) ; AccessTime ( ) ; break ; case 102 : sleeping = true ; if ( Connect ( ) ) { state = 103 ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 103 : sleeping = true ; if ( isConnected ( 100 ) ) { state = 401 ; listening = true ; Started ( 3 ) ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 201 : sleeping = true ; listening = true ; if ( ReadChunk ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 202 : sleeping = true ; listening = true ; if ( ReadLine ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 203 : sleeping = true ; listening = true ; if ( ReadStructure ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 301 : sleeping = true ; listening = true ; if ( WriteCommand ( ) ) { state = 302 ; } else { state = 303 ; } ; setParameter ( "State" , state ) ; break ; case 302 : sleeping = true ; Interpreter -> Actions ( ) ; AccessTime ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 303 : sleeping = true ; Interpreter -> Actions ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 304 : sleeping = true ; state = 401 ; setParameter ( "State" , state ) ; break ; case 401 : sleeping = true ; if ( Interpreter->Data(NetProtocol::Output).size() > 0 ) { state = 301 ; } else if ( Interpreter -> contains ( "State" ) ) { Interpreter -> Actions ( ) ; state = Interpreter -> value ( "State" ) . toInt ( ) ; switch ( state ) { case 0 : state = 901 ; break ; case 1 : state = 201 ; break ; case 2 : state = 202 ; break ; case 3 : state = 203 ; break ; } ; } ; setParameter ( "State" , state ) ; break ; case 901 : sleeping = true ; listening = false ; Close ( ) ; state = 999 ; setParameter ( "State" , state ) ; break ; case 911 : Time :: msleep ( 10 ) ; break ; case 999 : if ( Parameters . contains ( "Running" ) && Parameters [ "Running" ] . toBool ( ) ) { bool retry = false ; bool Forever = false ; //////////////////////////////////////////////////////////////////// if ( Parameters . contains ( "Forever" ) ) { Forever = Parameters [ "Forever" ] . toBool ( ) ; } ; if ( Forever ) { retry = true ; } else { if ( Parameters.contains("Retry") ) { if ( Parameters["Trying"].toInt()<Parameters["Retry"].toInt()) { retry = true ; } ; } ; } ; //////////////////////////////////////////////////////////////////// if ( retry ) { state = 101 ; setParameter ( "Trying" , Parameters["Trying"].toInt() + 1 ) ; Time :: msleep ( 500 ) ; } else { duty = false ; } ; } else { duty = false ; } ; setParameter ( "State" , state ) ; break ; default : break ; } ; SyncTime ( ) ; Intermediate ( sleeping , duty ) ; } ; //////////////////////////////////////////////////////////////////////////// if ( listening ) Close ( ) ; Finished ( 3 ) ; setParameter ( "Stopped" , true ) ; setParameter ( "ReadStopped" , true ) ; setParameter ( "WriteStopped" , true ) ; AutoDeletion ( ) ; //////////////////////////////////////////////////////////////////////////// return true ; } bool N::NetConnector::ReadChannel (void) { bool listening = false ; bool duty = false ; bool sleeping = true ; int state = 0 ; //////////////////////////////////////////////////////////////////////////// duty = Parameters [ "Running" ] . toBool ( ) ; setParameter ( "Stopped" , false ) ; setParameter ( "ReadStopped" , false ) ; //////////////////////////////////////////////////////////////////////////// if ( Parameters.contains("State" ) ) { state = Parameters [ "State" ] .toInt ( ) ; } else setParameter ( "State" , state ) ; ; //////////////////////////////////////////////////////////////////////////// AccessTime ( ) ; while ( duty ) { state = Parameters [ "State" ] .toInt ( ) ; switch ( state ) { case 0 : state = 101 ; sleeping = false ; setParameter ( "State" , state ) ; Prepend ( ) ; Prepared ( 1 ) ; AccessTime ( ) ; break ; case 101 : state = 102 ; sleeping = true ; AssignHost ( ) ; AccessTime ( ) ; setParameter ( "State" , state ) ; break ; case 102 : sleeping = true ; if ( Connect ( ) ) { state = 103 ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 103 : sleeping = true ; if ( isConnected ( 100 ) ) { state = 401 ; listening = true ; Started ( 1 ) ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 201 : sleeping = true ; if ( ReadChunk ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 202 : sleeping = true ; if ( ReadLine ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 203 : sleeping = true ; if ( ReadStructure ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 401 : sleeping = true ; if ( Interpreter -> contains ( "State" ) ) { Interpreter -> Actions ( ) ; state = Interpreter -> value ( "State" ) . toInt ( ) ; switch ( state ) { case 0 : state = 901 ; break ; case 1 : state = 201 ; break ; case 2 : state = 202 ; break ; case 3 : state = 203 ; break ; } ; } ; setParameter ( "State" , state ) ; break ; case 901 : sleeping = true ; listening = false ; Close ( ) ; state = 999 ; setParameter ( "State" , state ) ; break ; case 911 : Time :: msleep ( 10 ) ; break ; case 999 : if ( Parameters . contains ( "Running" ) && Parameters [ "Running" ] . toBool ( ) ) { bool retry = false ; bool Forever = false ; //////////////////////////////////////////////////////////////////// if ( Parameters . contains ( "Forever" ) ) { Forever = Parameters [ "Forever" ] . toBool ( ) ; } ; if ( Forever ) { retry = true ; } else { if ( Parameters.contains("Retry") ) { if ( Parameters["Trying"].toInt()<Parameters["Retry"].toInt()) { retry = true ; } ; } ; } ; //////////////////////////////////////////////////////////////////// if ( retry ) { state = 101 ; setParameter ( "Trying" , Parameters["Trying"].toInt() + 1 ) ; Time :: msleep ( 500 ) ; } else { duty = false ; } ; } else { duty = false ; } ; setParameter ( "State" , state ) ; break ; default : break ; } ; SyncTime ( ) ; Intermediate ( sleeping , duty ) ; } ; //////////////////////////////////////////////////////////////////////////// if ( listening ) Close ( ) ; Finished ( 1 ) ; setParameter ( "ReadStopped" , true ) ; if ( Parameters["WriteStopped"].toBool() ) setParameter("Stopped",true) ; AutoDeletion ( ) ; return true ; } bool N::NetConnector::WriteChannel (void) { bool listening = false ; bool duty = false ; bool sleeping = true ; int state = 0 ; //////////////////////////////////////////////////////////////////////////// duty = Parameters [ "Running" ] . toBool ( ) ; setParameter ( "Stopped" , false ) ; setParameter ( "WriteStopped" , false ) ; //////////////////////////////////////////////////////////////////////////// if ( Parameters.contains("State" ) ) { state = Parameters [ "State" ] .toInt ( ) ; } else setParameter ( "State" , state ) ; ; //////////////////////////////////////////////////////////////////////////// AccessTime ( ) ; while ( duty ) { state = Parameters [ "State" ] .toInt ( ) ; switch ( state ) { case 0 : state = 101 ; sleeping = false ; setParameter ( "State" , state ) ; Prepend ( ) ; Prepared ( 2 ) ; AccessTime ( ) ; break ; case 101 : state = 102 ; sleeping = true ; AssignHost ( ) ; AccessTime ( ) ; setParameter ( "State" , state ) ; break ; case 102 : sleeping = true ; if ( Connect ( ) ) { state = 103 ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 103 : sleeping = true ; if ( isConnected ( 100 ) ) { state = 401 ; listening = true ; Started ( 2 ) ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 301 : sleeping = true ; if ( WriteCommand ( ) ) { state = 302 ; } else { state = 303 ; } ; setParameter ( "State" , state ) ; break ; case 302 : sleeping = true ; Interpreter -> Actions ( ) ; AccessTime ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 303 : sleeping = true ; Interpreter -> Actions ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 304 : sleeping = true ; state = 401 ; setParameter ( "State" , state ) ; break ; case 401 : sleeping = true ; if ( Interpreter->Data(NetProtocol::Output).size() > 0 ) { state = 301 ; } ; setParameter ( "State" , state ) ; break ; case 901 : sleeping = true ; listening = false ; Close ( ) ; state = 999 ; setParameter ( "State" , state ) ; break ; case 911 : Time :: msleep ( 10 ) ; break ; case 999 : if ( Parameters . contains ( "Running" ) && Parameters [ "Running" ] . toBool ( ) ) { bool retry = false ; bool Forever = false ; //////////////////////////////////////////////////////////////////// if ( Parameters . contains ( "Forever" ) ) { Forever = Parameters [ "Forever" ] . toBool ( ) ; } ; if ( Forever ) { retry = true ; } else { if ( Parameters.contains("Retry") ) { if ( Parameters["Trying"].toInt()<Parameters["Retry"].toInt()) { retry = true ; } ; } ; } ; //////////////////////////////////////////////////////////////////// if ( retry ) { state = 101 ; setParameter ( "Trying" , Parameters["Trying"].toInt() + 1 ) ; Time :: msleep ( 500 ) ; } else { duty = false ; } ; } else { duty = false ; } ; setParameter ( "State" , state ) ; break ; default : break ; } ; SyncTime ( ) ; Intermediate ( sleeping , duty ) ; } ; //////////////////////////////////////////////////////////////////////////// if ( listening ) Close ( ) ; Finished ( 2 ) ; setParameter ( "WriteStopped" , true ) ; if ( Parameters["ReadStopped"].toBool() ) setParameter("Stopped",true) ; AutoDeletion ( ) ; return true ; } bool N::NetConnector::AtChannel(int channels) { switch ( channels ) { case 1: return ReadChannel ( ) ; case 2: return WriteChannel ( ) ; case 3: return BothChannels ( ) ; } ; return false ; }
72.766423
78
0.150717
Vladimir-Lin
801fd7729ffb61d163f981b2906d80d3ac47addc
2,111
cc
C++
npy/tests/NSliceTest.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
npy/tests/NSliceTest.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
npy/tests/NSliceTest.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 "NSlice.hpp" #include <cstdio> #include <vector> #include <string> #include <cassert> void test_slice(const char* arg) { NSlice* s = new NSlice(arg) ; printf("arg %s slice %s \n", arg, s->description()) ; } void test_margin() { NSlice s(0,10,1); assert( s.isHead(0,2) ); assert( s.isHead(1,2) ); assert( !s.isHead(2,2) ); assert( !s.isHead(3,2) ); assert( !s.isHead(4,2) ); assert( !s.isHead(5,2) ); assert( !s.isHead(6,2) ); assert( !s.isHead(7,2) ); assert( !s.isHead(8,2) ); assert( !s.isHead(9,2) ); assert( !s.isHead(10,2) ); assert( !s.isTail(0,2) ); assert( !s.isTail(1,2) ); assert( !s.isTail(2,2) ); assert( !s.isTail(3,2) ); assert( !s.isTail(4,2) ); assert( !s.isTail(5,2) ); assert( !s.isTail(6,2) ); assert( !s.isTail(7,2) ); assert( s.isTail(8,2) ); assert( s.isTail(9,2) ); assert( !s.isTail(10,2) ); assert( s.isMargin(0,2) ); assert( s.isMargin(1,2) ); assert( !s.isMargin(2,2) ); assert( !s.isMargin(3,2) ); assert( !s.isMargin(4,2) ); assert( !s.isMargin(5,2) ); assert( !s.isMargin(6,2) ); assert( !s.isMargin(7,2) ); assert( s.isMargin(8,2) ); assert( s.isMargin(9,2) ); assert( !s.isMargin(10,2) ); } int main() { test_slice("0:10"); test_slice("0:10:2"); test_margin(); return 0 ; }
24.835294
77
0.598295
hanswenzel
801fef50c23a6a0c2913d39e520a90f5ca9013fa
9,340
cpp
C++
src/bindings/Scriptdev2/scripts/northrend/naxxramas/boss_faerlina.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/bindings/Scriptdev2/scripts/northrend/naxxramas/boss_faerlina.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/scripts/northrend/naxxramas/boss_faerlina.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2011 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Faerlina SD%Complete: 50 SDComment: SDCategory: Naxxramas EndScriptData */ #include "precompiled.h" #include "naxxramas.h" enum { SAY_GREET = -1533009, SAY_AGGRO = -1533010, SAY_ENRAGE1 = -1533011, SAY_ENRAGE2 = -1533012, SAY_ENRAGE3 = -1533013, SAY_SLAY1 = -1533014, SAY_SLAY2 = -1533015, SAY_DEATH = -1533016, EMOTE_BOSS_GENERIC_FRENZY = -1000005, //SOUND_RANDOM_AGGRO = 8955, //soundId containing the 4 aggro sounds, we not using this SPELL_POSIONBOLT_VOLLEY = 28796, H_SPELL_POSIONBOLT_VOLLEY = 54098, SPELL_FRENZY = 28798, H_SPELL_FRENZY = 54100, SPELL_RAINOFFIRE = 28794, //Not sure if targeted AoEs work if casted directly upon a pPlayer H_SPELL_RAINOFFIRE = 58936, SPELL_FIREBALL = 54095, SPELL_FIREBALL_H = 54096, SPELL_WIDOWS_EMBRACE = 28732, NPC_NAXXRAMAS_WORSHIPPER = 16506, NPC_NAXXRAMAS_FOLLOWER = 16505, }; struct MANGOS_DLL_DECL boss_faerlinaAI : public ScriptedAI { boss_faerlinaAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); m_bHasTaunted = false; Reset(); } instance_naxxramas* m_pInstance; bool m_bIsRegularMode; uint32 m_uiPoisonBoltVolleyTimer; uint32 m_uiRainOfFireTimer; uint32 m_uiEnrageTimer; bool m_bHasTaunted; void Reset() { m_uiPoisonBoltVolleyTimer = urand(14000, 15000); m_uiRainOfFireTimer = urand(6000, 8000); m_uiEnrageTimer = urand(60000, 80000); std::list<Creature*> lUnitList; GetCreatureListWithEntryInGrid(lUnitList, m_creature, NPC_NAXXRAMAS_WORSHIPPER, 100.0f); if (!lUnitList.empty()) for(std::list<Creature*>::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) if ((*iter)->isDead()) (*iter)->Respawn(); lUnitList.clear(); GetCreatureListWithEntryInGrid(lUnitList, m_creature, NPC_NAXXRAMAS_FOLLOWER, 100.0f); if (!lUnitList.empty()) for(std::list<Creature*>::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) if ((*iter)->isDead()) (*iter)->Respawn(); } void Aggro(Unit* pWho) { DoScriptText(SAY_AGGRO, m_creature); m_creature->SetInCombatWithZone(); std::list<Creature*> lUnitList; GetCreatureListWithEntryInGrid(lUnitList, m_creature, NPC_NAXXRAMAS_WORSHIPPER, 100.0f); if (!lUnitList.empty()) for (std::list<Creature*>::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) (*iter)->AI()->AttackStart(pTarget); else (*iter)->AI()->AttackStart(pWho); m_creature->CallForHelp(20); if (m_pInstance) m_pInstance->SetData(TYPE_FAERLINA, IN_PROGRESS); } void MoveInLineOfSight(Unit* pWho) { if (!m_bHasTaunted && pWho->GetTypeId() == TYPEID_PLAYER && m_creature->IsWithinDistInMap(pWho, 80.0f)) { DoScriptText(SAY_GREET, m_creature); m_bHasTaunted = true; } ScriptedAI::MoveInLineOfSight(pWho); } void KilledUnit(Unit* pVictim) { DoScriptText(urand(0, 1)?SAY_SLAY1:SAY_SLAY2, m_creature); } void JustDied(Unit* pKiller) { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_FAERLINA, DONE); } void JustReachedHome() { if (m_pInstance) m_pInstance->SetData(TYPE_FAERLINA, FAIL); } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // Poison Bolt Volley if (m_uiPoisonBoltVolleyTimer < uiDiff) { if (!m_creature->HasAura(SPELL_WIDOWS_EMBRACE)) DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_POSIONBOLT_VOLLEY : H_SPELL_POSIONBOLT_VOLLEY); m_uiPoisonBoltVolleyTimer = urand(14000, 15000); } else m_uiPoisonBoltVolleyTimer -= uiDiff; // Rain Of Fire if (m_uiRainOfFireTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) DoCastSpellIfCan(pTarget, m_bIsRegularMode ? SPELL_RAINOFFIRE : H_SPELL_RAINOFFIRE); m_uiRainOfFireTimer = urand(6000, 8000); } else m_uiRainOfFireTimer -= uiDiff; //Enrage_Timer if (m_uiEnrageTimer < uiDiff) { switch (urand(0, 2)) { case 0: DoScriptText(SAY_ENRAGE1, m_creature); break; case 1: DoScriptText(SAY_ENRAGE2, m_creature); break; case 2: DoScriptText(SAY_ENRAGE3, m_creature); break; } m_creature->MonsterTextEmote("%s goes into a frenzy!", 0, true); DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_FRENZY : H_SPELL_FRENZY); m_uiEnrageTimer = urand(60000, 80000); } else m_uiEnrageTimer -= uiDiff; DoMeleeAttackIfReady(); } }; struct MANGOS_DLL_DECL mob_worshipperAI : public ScriptedAI { mob_worshipperAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_naxxramas* m_pInstance; bool m_bIsRegularMode; uint32 m_uiFireball_Timer; void Reset() { m_uiFireball_Timer = 0; } void Aggro(Unit *pWho) { if (m_pInstance) { if (Creature* pFaerlina = m_creature->GetMap()->GetCreature(m_pInstance->GetData64(NPC_FAERLINA))) if (pFaerlina->isAlive() && !pFaerlina->getVictim()) pFaerlina->AI()->AttackStart(pWho); } } void JustDied(Unit* pKiller) { if (m_pInstance) if (Creature* pFaerlina = m_creature->GetMap()->GetCreature(m_pInstance->GetData64(NPC_FAERLINA))) if ((pFaerlina->HasAura(SPELL_FRENZY) || pFaerlina->HasAura(H_SPELL_FRENZY)) && (m_creature->GetDistance2d(pFaerlina) <= 10.0f)) { pFaerlina->RemoveAurasDueToSpell(m_bIsRegularMode ? SPELL_FRENZY : H_SPELL_FRENZY); if (SpellEntry* pSpell = (SpellEntry*)GetSpellStore()->LookupEntry(SPELL_WIDOWS_EMBRACE)) { pSpell->EffectImplicitTargetA[0] = TARGET_SELF; pSpell->EffectImplicitTargetB[0] = 0; pSpell->EffectImplicitTargetA[1] = TARGET_SELF; pSpell->EffectImplicitTargetB[1] = 0; pFaerlina->CastSpell(pFaerlina, pSpell, true); pFaerlina->MonsterTextEmote("%s is affected by Widow's Embrace!", 0, true); } } } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiFireball_Timer < uiDiff) { DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_FIREBALL : SPELL_FIREBALL_H); m_uiFireball_Timer = 5000 + rand()%3000; } else m_uiFireball_Timer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_mob_worshipper(Creature* pCreature) { return new mob_worshipperAI(pCreature); } CreatureAI* GetAI_boss_faerlina(Creature* pCreature) { return new boss_faerlinaAI(pCreature); } void AddSC_boss_faerlina() { Script* NewScript; NewScript = new Script; NewScript->Name = "boss_faerlina"; NewScript->GetAI = &GetAI_boss_faerlina; NewScript->RegisterSelf(); NewScript = new Script; NewScript->Name = "mob_worshipper"; NewScript->GetAI = &GetAI_mob_worshipper; NewScript->RegisterSelf(); }
33.238434
144
0.611563
mfooo