blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
962d83fd00865010cc9f2d4401bdaffab269a05f | a8ca5c8fc67ff451481687530e793f64cdd9ecd2 | /src/winsys/window.hh | cfd6306d3949b0c3f380f3f877fe21087faa54bb | [
"BSD-2-Clause"
] | permissive | deurzen/kranewm | c002cfb4bf039be34d62f5eb7960249563a75f8e | be918e057c3b6f2199d23ce39d4334379165ff41 | refs/heads/master | 2022-06-23T19:33:04.951564 | 2022-06-19T21:57:39 | 2022-06-19T21:57:39 | 173,928,993 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | hh | #ifndef __WINSYS_WINDOW_H_GUARD__
#define __WINSYS_WINDOW_H_GUARD__
#include <cstdlib>
namespace winsys
{
typedef std::size_t Window;
enum class IcccmWindowState
{
Withdrawn,
Normal,
Iconic
};
enum class WindowState
{
Modal,
Sticky,
MaximizedVert,
MaximizedHorz,
Shaded,
SkipTaskbar,
SkipPager,
Hidden,
Fullscreen,
Above_,
Below_,
DemandsAttention
};
enum class WindowType
{
Desktop,
Dock,
Toolbar,
Menu,
Utility,
Splash,
Dialog,
DropdownMenu,
PopupMenu,
Tooltip,
Notification,
Combo,
Dnd,
Normal
};
}
#endif//__WINSYS_WINDOW_H_GUARD__
| [
"m.deurzen@tum.de"
] | m.deurzen@tum.de |
0397dd4fae70c2ee1943589f954e92da0841658b | 33fb5c834556b41512ae7ac3162c56022f981484 | /Queue/Queue using Stacks/Queue using Stacks.cpp | 698aa63c384b1bb0ad1ff1a64c1da1c9bdecd5a7 | [] | no_license | tips367/Data-Structures | 73a6915956213fbffbf075ed67469b1f9484eaec | a133511437228659b8646ffbed05f3fbffc9a0e6 | refs/heads/master | 2022-08-14T18:59:41.866085 | 2022-07-09T14:29:01 | 2022-07-09T14:29:01 | 232,938,786 | 1 | 0 | null | 2021-07-02T21:24:23 | 2020-01-10T01:20:27 | C++ | UTF-8 | C++ | false | false | 2,979 | cpp | /* We are given a stack data structure with push and pop operations, the task is to implement a queue using instances of stack data structure
and operations on them.
*/
#include <iostream>
#include <stack>
// Method 1. Enqueue operation costly
// This method makes sure that oldest entered element is always at the top of stack1, so that dequeue operation just pops from stack1.
// To put the element at top of stack1, stack2 is used.
/*
class Queue
{
public:
void enqueue(int item);
int dequeue();
private:
std::stack<int> s1, s2;
};
void Queue::enqueue(int item)
{
// Move all elements from s1 to s2
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
// Push item into s1
s1.push(item);
// Push everything back to s1
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
}
int Queue::dequeue()
{
// if first stack is empty
if (s1.empty())
{
std::cout << "Queue is Empty";
return INT_MIN;
}
// Return top of s1
int x = s1.top();
s1.pop();
return x;
} */
// Method 2. Dequeue operation costly
// In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation,
// if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.
/*
class Queue
{
public:
void enqueue(int item);
int dequeue();
private:
std::stack<int> s1, s2;
};
void Queue::enqueue(int item)
{
s1.push(item);
}
int Queue::dequeue()
{
// if both stacks are empty
if (s1.empty() && s2.empty())
{
std::cout << "Queue is Empty";
return INT_MIN;
}
// if s2 is empty, move elements from s1
if (s2.empty())
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
// return the top item from s2
int x = s2.top();
s2.pop();
return x;
} */
// Method 3. Implementation of method 2 using Function Call Stack
class Queue
{
public:
void enqueue(int item);
int dequeue();
private:
std::stack<int> s;
};
void Queue::enqueue(int item)
{
s.push(item);
}
int Queue::dequeue()
{
if (s.empty())
{
std::cout << "Queue is Empty";
return INT_MIN;
}
int item = s.top();
s.pop();
// if stack becomes empty, return the popped item
if (s.empty())
{
return item;
}
int x = dequeue();
// push popped item back to the stack
s.push(item);
// return the result of dequeue() call
return x;
}
int main()
{
Queue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
std::cout << q.dequeue() << '\n';
std::cout << q.dequeue() << '\n';
std::cout << q.dequeue() << '\n';
q.enqueue(6);
std::cout << q.dequeue() << '\n';
std::cout << q.dequeue() << '\n';
std::cout << q.dequeue() << '\n';
return 0;
}
| [
"Tipu.Khan@landisgyr.com"
] | Tipu.Khan@landisgyr.com |
12a0fdedf9d10535bc5a47f4089f2249257b3267 | 67f988dedfd8ae049d982d1a8213bb83233d90de | /external/chromium/v8/src/codegen.cc | 83ac854a079259b1aaceba57a06e5465fd5d61ac | [
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | opensourceyouthprogramming/h5vcc | 94a668a9384cc3096a365396b5e4d1d3e02aacc4 | d55d074539ba4555e69e9b9a41e5deb9b9d26c5b | refs/heads/master | 2020-04-20T04:57:47.419922 | 2019-02-12T00:56:14 | 2019-02-12T00:56:14 | 168,643,719 | 1 | 1 | null | 2019-02-12T00:49:49 | 2019-02-01T04:47:32 | C++ | UTF-8 | C++ | false | false | 6,531 | cc | // Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "bootstrapper.h"
#include "codegen.h"
#include "compiler.h"
#include "debug.h"
#include "prettyprinter.h"
#include "rewriter.h"
#include "runtime.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm_)
#ifdef DEBUG
Comment::Comment(MacroAssembler* masm, const char* msg)
: masm_(masm), msg_(msg) {
__ RecordComment(msg);
}
Comment::~Comment() {
if (msg_[0] == '[') __ RecordComment("]");
}
#endif // DEBUG
#undef __
void CodeGenerator::MakeCodePrologue(CompilationInfo* info) {
#ifdef DEBUG
bool print_source = false;
bool print_ast = false;
const char* ftype;
if (Isolate::Current()->bootstrapper()->IsActive()) {
print_source = FLAG_print_builtin_source;
print_ast = FLAG_print_builtin_ast;
ftype = "builtin";
} else {
print_source = FLAG_print_source;
print_ast = FLAG_print_ast;
ftype = "user-defined";
}
if (FLAG_trace_codegen || print_source || print_ast) {
PrintF("*** Generate code for %s function: ", ftype);
info->function()->name()->ShortPrint();
PrintF(" ***\n");
}
if (print_source) {
PrintF("--- Source from AST ---\n%s\n",
PrettyPrinter().PrintProgram(info->function()));
}
if (print_ast) {
PrintF("--- AST ---\n%s\n",
AstPrinter().PrintProgram(info->function()));
}
#endif // DEBUG
}
Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm,
Code::Flags flags,
CompilationInfo* info) {
Isolate* isolate = info->isolate();
// Allocate and install the code.
CodeDesc desc;
masm->GetCode(&desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, flags, masm->CodeObject());
if (!code.is_null()) {
isolate->counters()->total_compiled_code_size()->Increment(
code->instruction_size());
code->set_prologue_offset(info->prologue_offset());
}
return code;
}
void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) {
#ifdef ENABLE_DISASSEMBLER
bool print_code = Isolate::Current()->bootstrapper()->IsActive()
? FLAG_print_builtin_code
: (FLAG_print_code || (info->IsOptimizing() && FLAG_print_opt_code));
if (print_code) {
// Print the source code if available.
FunctionLiteral* function = info->function();
Handle<Script> script = info->script();
if (!script->IsUndefined() && !script->source()->IsUndefined()) {
PrintF("--- Raw source ---\n");
StringInputBuffer stream(String::cast(script->source()));
stream.Seek(function->start_position());
// fun->end_position() points to the last character in the stream. We
// need to compensate by adding one to calculate the length.
int source_len =
function->end_position() - function->start_position() + 1;
for (int i = 0; i < source_len; i++) {
if (stream.has_more()) PrintF("%c", stream.GetNext());
}
PrintF("\n\n");
}
if (info->IsOptimizing()) {
if (FLAG_print_unopt_code) {
PrintF("--- Unoptimized code ---\n");
info->closure()->shared()->code()->Disassemble(
*function->debug_name()->ToCString());
}
PrintF("--- Optimized code ---\n");
} else {
PrintF("--- Code ---\n");
}
code->Disassemble(*function->debug_name()->ToCString());
}
#endif // ENABLE_DISASSEMBLER
}
bool CodeGenerator::ShouldGenerateLog(Expression* type) {
ASSERT(type != NULL);
Isolate* isolate = Isolate::Current();
if (!isolate->logger()->is_logging() && !CpuProfiler::is_profiling(isolate)) {
return false;
}
Handle<String> name = Handle<String>::cast(type->AsLiteral()->handle());
if (FLAG_log_regexp) {
if (name->IsEqualTo(CStrVector("regexp")))
return true;
}
return false;
}
bool CodeGenerator::RecordPositions(MacroAssembler* masm,
int pos,
bool right_here) {
if (pos != RelocInfo::kNoPosition) {
masm->positions_recorder()->RecordStatementPosition(pos);
masm->positions_recorder()->RecordPosition(pos);
if (right_here) {
return masm->positions_recorder()->WriteRecordedPositions();
}
}
return false;
}
void ArgumentsAccessStub::Generate(MacroAssembler* masm) {
switch (type_) {
case READ_ELEMENT:
GenerateReadElement(masm);
break;
case NEW_NON_STRICT_FAST:
GenerateNewNonStrictFast(masm);
break;
case NEW_NON_STRICT_SLOW:
GenerateNewNonStrictSlow(masm);
break;
case NEW_STRICT:
GenerateNewStrict(masm);
break;
}
}
int CEntryStub::MinorKey() {
int result = (save_doubles_ == kSaveFPRegs) ? 1 : 0;
ASSERT(result_size_ == 1 || result_size_ == 2);
#ifdef _WIN64
return result | ((result_size_ == 1) ? 0 : 2);
#else
return result;
#endif
}
} } // namespace v8::internal
| [
"ddavenport@google.com"
] | ddavenport@google.com |
4eeb8f0a7af3ff33082133487b86467d5096c6b8 | 30038b35f96e2b2dfb9a0236b44b44fb7728e69a | /pup_stl.h | 89910eb936a9a5ee1df53935d0343cbd3fe3c246 | [] | no_license | guptaabhish/parallel-infosetgeneration-gametrees | 12316ec9d57d0f555c260863adab6625b397ae6f | 43e1867a85e42a8f5103c8d1eaaa9e76318c0490 | refs/heads/master | 2020-12-25T15:17:56.249130 | 2016-06-11T00:55:15 | 2016-06-11T00:55:15 | 60,884,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,467 | h | /*
Pup routines for STL classes.
After including this header, you can parameter-marshall
an variable consisting of STL vectors, lists, maps,
strings, or pairs.
This includes variables of type "std::list<int>", or even
"std::map<double, std::vector<std::string> >".
NOT included are the rarer types like valarray or slice,
vector<bool>, set or multiset, or deque.
Orion Sky Lawlor, olawlor@acm.org, 7/22/2002
*/
#ifndef _UIUC_CHARM_PUP_STL_H
#define _UIUC_CHARM_PUP_STL_H
/*It's kind of annoying that we have to drag all these headers in
just so the std:: parameter declarations will compile.
*/
#include <vector>
#include <list>
#include <map>
#include <string>
#include <complex>
#include <utility> /*for std::pair*/
#include <set>
#include "pup.h"
/*************** Simple classes ***************/
template <class A,class B>
inline void operator|(PUP::er &p,typename std::pair<const A,B> &v)
{
p.syncComment(PUP::sync_index);
p|*(A *)&v.first; /* cast away constness on A */
p.syncComment(PUP::sync_item);
p|v.second;
}
template <class T>
inline void operator|(PUP::er &p,std::complex<T> &v)
{
T re=v.real(), im=v.imag();
p|re; p|im;
v=std::complex<T>(re,im);
}
template <class charType>
inline void operator|(PUP::er &p,typename std::basic_string<charType> &v)
{
int nChar=v.length();
p|nChar;
if (p.isUnpacking()) { //Unpack to temporary buffer
charType *buf=new charType[nChar];
p(buf,nChar);
v=std::basic_string<charType>(buf,nChar);
delete[] buf;
}
else /*packing*/ { //Do packing in-place from data
//Have to cast away constness here
p((charType *)v.data(),nChar);
}
}
inline void operator|(PUP::er &p,std::string &v)
{
p.syncComment(PUP::sync_begin_object,"std::string");
int nChar=v.length();
p|nChar;
if (p.isUnpacking()) { //Unpack to temporary buffer
char *buf=new char[nChar];
p(buf,nChar);
v=std::basic_string<char>(buf,nChar);
delete[] buf;
}
else /*packing*/ { //Do packing in-place from data
//Have to cast away constness here
p((char *)v.data(),nChar);
}
p.syncComment(PUP::sync_end_object);
}
/**************** Containers *****************/
//Impl. util: pup the length of a container
template <class container>
inline int PUP_stl_container_size(PUP::er &p,container &c) {
int nElem=c.size();
p|nElem;
return nElem;
}
//Impl. util: pup each current item of a container (no allocation)
template <class container,class dtype>
inline void PUP_stl_container_items(PUP::er &p,container &c) {
for (typename container::iterator it=c.begin();
it!=c.end();
++it) {
p.syncComment(PUP::sync_item);
p|*(dtype *)&(*it);
}
}
template <class container,class dtype>
inline void PUP_stl_container(PUP::er &p,container &c) {
p.syncComment(PUP::sync_begin_array);
int nElem=PUP_stl_container_size(p,c);
if (p.isUnpacking())
{ //Unpacking: Extract each element and push_back:
c.resize(0);
for (int i=0;i<nElem;i++) {
p.syncComment(PUP::sync_item);
dtype n;
p|n;
c.push_back(n);
}
}
else PUP_stl_container_items<container, dtype>(p,c);
p.syncComment(PUP::sync_end_array);
}
//Map objects don't have a "push_back", while vector and list
// don't have an "insert", so PUP_stl_map isn't PUP_stl_container
template <class container,class dtype>
inline void PUP_stl_map(PUP::er &p,container &c) {
p.syncComment(PUP::sync_begin_list);
int nElem=PUP_stl_container_size(p,c);
if (p.isUnpacking())
{ //Unpacking: Extract each element and insert:
for (int i=0;i<nElem;i++) {
dtype n;
p|n;
c.insert(n);
}
}
else PUP_stl_container_items<container, dtype>(p,c);
p.syncComment(PUP::sync_end_list);
}
template <class T>
inline void operator|(PUP::er &p,typename std::vector<T> &v)
{ PUP_stl_container<std::vector<T>,T>(p,v); }
template <class T>
inline void operator|(PUP::er &p,typename std::list<T> &v)
{ PUP_stl_container<std::list<T>,T>(p,v); }
template <class V,class T,class Cmp>
inline void operator|(PUP::er &p,typename std::map<V,T,Cmp> &m)
{ PUP_stl_map<std::map<V,T,Cmp>,std::pair<const V,T> >(p,m); }
template <class T,class Cmp>
inline void operator|(PUP::er &p,typename std::set<T,Cmp> &m)
{ PUP_stl_map<std::set<T,Cmp>,T>(p,m); }
template <class V,class T,class Cmp>
inline void operator|(PUP::er &p,typename std::multimap<V,T,Cmp> &m)
{ PUP_stl_map<std::multimap<V,T,Cmp>,std::pair<const V,T> >(p,m); }
#endif
| [
"gupta59@illinois.edu"
] | gupta59@illinois.edu |
35691cc710e12587641081a070cf02c0490a503a | 53def63a6b7260b917d406fe00694ccc58442c1d | /WebCore/platform/ScrollbarTheme.h | 888ecc2ddce48336edc3a6474ae032f8199ff754 | [] | no_license | studiomobile/webcore | b3234992d7a160c915216519d75dce053543fe5f | 16f39479a01992f2066a9879de455028575d19d6 | refs/heads/master | 2021-01-10T03:07:14.237681 | 2012-02-22T17:37:55 | 2012-02-22T17:37:55 | 2,101,948 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,794 | h | /*
* Copyright (C) 2008 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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.
*/
#ifndef ScrollbarTheme_h
#define ScrollbarTheme_h
#include "GraphicsContext.h"
#include "IntRect.h"
#include "ScrollTypes.h"
namespace WebCore {
class PlatformMouseEvent;
class Scrollbar;
class ScrollView;
class ScrollbarTheme {
WTF_MAKE_NONCOPYABLE(ScrollbarTheme); WTF_MAKE_FAST_ALLOCATED;
public:
ScrollbarTheme() { }
virtual ~ScrollbarTheme() {};
virtual bool paint(Scrollbar*, GraphicsContext*, const IntRect& /*damageRect*/) { return false; }
virtual ScrollbarPart hitTest(Scrollbar*, const PlatformMouseEvent&) { return NoPart; }
virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) { return 0; }
virtual ScrollbarButtonsPlacement buttonsPlacement() const { return ScrollbarButtonsSingle; }
virtual bool supportsControlTints() const { return false; }
virtual bool usesOverlayScrollbars() const { return false; }
virtual void themeChanged() {}
virtual bool invalidateOnMouseEnterExit() { return false; }
void invalidateParts(Scrollbar* scrollbar, ScrollbarControlPartMask mask)
{
if (mask & BackButtonStartPart)
invalidatePart(scrollbar, BackButtonStartPart);
if (mask & ForwardButtonStartPart)
invalidatePart(scrollbar, ForwardButtonStartPart);
if (mask & BackTrackPart)
invalidatePart(scrollbar, BackTrackPart);
if (mask & ThumbPart)
invalidatePart(scrollbar, ThumbPart);
if (mask & ForwardTrackPart)
invalidatePart(scrollbar, ForwardTrackPart);
if (mask & BackButtonEndPart)
invalidatePart(scrollbar, BackButtonEndPart);
if (mask & ForwardButtonEndPart)
invalidatePart(scrollbar, ForwardButtonEndPart);
}
virtual void invalidatePart(Scrollbar*, ScrollbarPart) {}
virtual void paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect) { defaultPaintScrollCorner(context, cornerRect); }
static void defaultPaintScrollCorner(GraphicsContext* context, const IntRect& cornerRect) { context->fillRect(cornerRect, Color::white, ColorSpaceDeviceRGB); }
virtual bool shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent&) { return false; }
virtual bool shouldSnapBackToDragOrigin(Scrollbar*, const PlatformMouseEvent&) { return false; }
virtual bool shouldDragDocumentInsteadOfThumb(Scrollbar*, const PlatformMouseEvent&) { return false; }
virtual int thumbPosition(Scrollbar*) { return 0; } // The position of the thumb relative to the track.
virtual int thumbLength(Scrollbar*) { return 0; } // The length of the thumb along the axis of the scrollbar.
virtual int trackPosition(Scrollbar*) { return 0; } // The position of the track relative to the scrollbar.
virtual int trackLength(Scrollbar*) { return 0; } // The length of the track along the axis of the scrollbar.
virtual int maxOverlapBetweenPages() { return std::numeric_limits<int>::max(); }
virtual double initialAutoscrollTimerDelay() { return 0.25; }
virtual double autoscrollTimerDelay() { return 0.05; }
virtual void registerScrollbar(Scrollbar*) {}
virtual void unregisterScrollbar(Scrollbar*) {}
static ScrollbarTheme* nativeTheme() {
static ScrollbarTheme *theme = 0;
if (!theme) {
theme = new ScrollbarTheme();
}
return theme;
}; // Must be implemented to return the correct theme subclass.
};
}
#endif
| [
"hoha@Hohas-Mac-Pro.local"
] | hoha@Hohas-Mac-Pro.local |
4beb400f92dc2ff9083b9a9a3ef1841612830a26 | bb6ebff7a7f6140903d37905c350954ff6599091 | /cc/test/fake_output_surface.cc | 9c027eae60e99a14983618d636bbb3dbe7e6981f | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 4,311 | cc | // Copyright 2012 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 "cc/test/fake_output_surface.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "cc/output/compositor_frame_ack.h"
#include "cc/output/output_surface_client.h"
#include "cc/resources/returned_resource.h"
#include "cc/test/begin_frame_args_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cc {
FakeOutputSurface::FakeOutputSurface(
scoped_refptr<ContextProvider> context_provider,
bool delegated_rendering)
: OutputSurface(context_provider),
client_(NULL),
num_sent_frames_(0),
needs_begin_frame_(false),
has_external_stencil_test_(false),
fake_weak_ptr_factory_(this) {
if (delegated_rendering) {
capabilities_.delegated_rendering = true;
capabilities_.max_frames_pending = 1;
}
}
FakeOutputSurface::FakeOutputSurface(
scoped_ptr<SoftwareOutputDevice> software_device,
bool delegated_rendering)
: OutputSurface(software_device.Pass()),
client_(NULL),
num_sent_frames_(0),
has_external_stencil_test_(false),
fake_weak_ptr_factory_(this) {
if (delegated_rendering) {
capabilities_.delegated_rendering = true;
capabilities_.max_frames_pending = 1;
}
}
FakeOutputSurface::FakeOutputSurface(
scoped_refptr<ContextProvider> context_provider,
scoped_ptr<SoftwareOutputDevice> software_device,
bool delegated_rendering)
: OutputSurface(context_provider, software_device.Pass()),
client_(NULL),
num_sent_frames_(0),
has_external_stencil_test_(false),
fake_weak_ptr_factory_(this) {
if (delegated_rendering) {
capabilities_.delegated_rendering = true;
capabilities_.max_frames_pending = 1;
}
}
FakeOutputSurface::~FakeOutputSurface() {}
void FakeOutputSurface::SwapBuffers(CompositorFrame* frame) {
if (frame->software_frame_data || frame->delegated_frame_data ||
!context_provider()) {
frame->AssignTo(&last_sent_frame_);
if (last_sent_frame_.delegated_frame_data) {
resources_held_by_parent_.insert(
resources_held_by_parent_.end(),
last_sent_frame_.delegated_frame_data->resource_list.begin(),
last_sent_frame_.delegated_frame_data->resource_list.end());
}
++num_sent_frames_;
PostSwapBuffersComplete();
client_->DidSwapBuffers();
} else {
OutputSurface::SwapBuffers(frame);
frame->AssignTo(&last_sent_frame_);
++num_sent_frames_;
}
}
void FakeOutputSurface::SetNeedsBeginFrame(bool enable) {
needs_begin_frame_ = enable;
OutputSurface::SetNeedsBeginFrame(enable);
if (enable) {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeOutputSurface::OnBeginFrame,
fake_weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(16));
}
}
void FakeOutputSurface::OnBeginFrame() {
client_->BeginFrame(CreateBeginFrameArgsForTesting());
}
bool FakeOutputSurface::BindToClient(OutputSurfaceClient* client) {
if (OutputSurface::BindToClient(client)) {
client_ = client;
if (memory_policy_to_set_at_bind_) {
client_->SetMemoryPolicy(*memory_policy_to_set_at_bind_.get());
memory_policy_to_set_at_bind_.reset();
}
return true;
} else {
return false;
}
}
void FakeOutputSurface::SetTreeActivationCallback(
const base::Closure& callback) {
DCHECK(client_);
client_->SetTreeActivationCallback(callback);
}
void FakeOutputSurface::ReturnResource(unsigned id, CompositorFrameAck* ack) {
TransferableResourceArray::iterator it;
for (it = resources_held_by_parent_.begin();
it != resources_held_by_parent_.end();
++it) {
if (it->id == id)
break;
}
DCHECK(it != resources_held_by_parent_.end());
ack->resources.push_back(it->ToReturnedResource());
resources_held_by_parent_.erase(it);
}
bool FakeOutputSurface::HasExternalStencilTest() const {
return has_external_stencil_test_;
}
void FakeOutputSurface::SetMemoryPolicyToSetAtBind(
scoped_ptr<ManagedMemoryPolicy> memory_policy_to_set_at_bind) {
memory_policy_to_set_at_bind_.swap(memory_policy_to_set_at_bind);
}
} // namespace cc
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
e73ceace87422206339c28bbda6b487009214ed8 | bde4d419ec0d9bf3e53e8661c2272de34ec72566 | /OpenFlow/Messages/FlowRemovedDecoder.cpp | 80b71a8c66e203e908e561e5efb5d940c6de66ca | [
"BSD-3-Clause"
] | permissive | arnolmi/ROX | 0794606f13c923eef8e794249426c7a42a31766b | 96e585ea8072cc7c00c011eba14959c25948fdb0 | refs/heads/master | 2020-12-13T23:37:06.925969 | 2017-06-11T22:20:31 | 2017-06-11T22:20:31 | 53,295,720 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,193 | cpp | #include <stdint.h>
#include <arpa/inet.h>
#include "FlowRemovedDecoder.h"
namespace OpenFlow
{
namespace Messages
{
FlowRemovedDecoder::FlowRemovedDecoder(uint8_t *p_)
: HeaderDecoder(p_) {
}
FlowRemovedDecoder::FlowRemovedDecoder(FlowRemovedDecoder const &decoder) : HeaderDecoder(decoder.p)
{
}
uint64_t FlowRemovedDecoder::getCookie() const
{
uint64_t *temp = (uint64_t * )(p + HEADER_MINIMUM_LENGTH);
return htobe64(*temp);
}
uint16_t FlowRemovedDecoder::getPriority() const
{
uint16_t *temp = (uint16_t * )(p + HEADER_MINIMUM_LENGTH + 8);
return ntohs(*temp);
}
uint8_t FlowRemovedDecoder::getReason() const
{
return p[HEADER_MINIMUM_LENGTH + 8 + 2];
}
uint8_t FlowRemovedDecoder::getTableId() const
{
return p[HEADER_MINIMUM_LENGTH + 8 + 1 + 2];
}
uint32_t FlowRemovedDecoder::getDurationSec() const
{
uint32_t *temp = (uint32_t * )(p + HEADER_MINIMUM_LENGTH + 8 + 2 + 2);
return ntohl(*temp);
}
uint32_t FlowRemovedDecoder::getDurationNSec() const
{
uint32_t *temp = (uint32_t * )(p + HEADER_MINIMUM_LENGTH + 8 + 6 + 2);
return ntohl(*temp);
}
uint16_t FlowRemovedDecoder::getIdleTimeout() const
{
uint16_t *temp = (uint16_t * )(p + HEADER_MINIMUM_LENGTH + 8 + 10 + 2);
return ntohs(*temp);
}
uint16_t FlowRemovedDecoder::getHardTimeout() const
{
uint16_t *temp = (uint16_t * )(p + HEADER_MINIMUM_LENGTH + 8 + 12 + 2);
return ntohs(*temp);
}
uint64_t FlowRemovedDecoder::getPacketCount() const
{
uint64_t *temp = (uint64_t * )(p + HEADER_MINIMUM_LENGTH + 8 + 14 + 2);
return htobe64(*temp);
}
uint64_t FlowRemovedDecoder::getByteCount() const
{
uint64_t *temp = (uint64_t * )(p + HEADER_MINIMUM_LENGTH + 22 + 8 + 2);
return htobe64(*temp);
}
}
}
| [
"nim@shadowfire.org"
] | nim@shadowfire.org |
9771602c25fa3633245df5be15acff00247e4e29 | 47738096e1f57d6d7d59b0f6b54ba4bf76adf71d | /View.h | 708b3cc06a27e0d401aa444f130667b101879a7f | [] | no_license | KenleyChiu/CPECOG2Proj | eaba0fb0cd6ed97d2378528c734ed0a9886576be | 2f9277b31c1dc4f68277d7162e016a7f4f8c350f | refs/heads/master | 2023-07-27T20:24:39.500322 | 2021-09-07T06:10:03 | 2021-09-07T06:10:03 | 403,860,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | h | #pragma once
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "CImg.h"
#include "Ball.h"
#define WIDTH 1280
#define HEIGHT 720
#define COUNT 8
class View
{
public:
View(uint8_t* bg_mem);
uint32_t* getFrameBuffer();
uint32_t* loadSprite(uint8_t* sprite_data, int width, int height);
void displaySprite(uint32_t* sprite, int width, int height, int current_x, int current_y);
void moveBall(Ball* ball);
private:
static uint32_t bg_arr[WIDTH * HEIGHT];
static uint32_t frame[WIDTH * HEIGHT];
static const size_t sprite_mem_size = 1000000;
static uint32_t sprite_mem[sprite_mem_size];
static uint32_t* sprite_mem_tracker;
uint32_t* bgbuffer;
uint32_t* framebuffer;
};
| [
"kenley_chiu@dlsu.edu.ph"
] | kenley_chiu@dlsu.edu.ph |
de19126b9b38710aeb0d0f0b916d83a8cecd7a0d | 9472221ec7da4395f0cd3845e56fee58e785a2be | /main.cc | 25cb7130eb51c1715648637aa5ee7af55b40eb02 | [] | no_license | TraceBundy/leetcode | cf31cb1bb792ee07ab55c2bf659bf478a653343f | 5f44e97ccf4c2c36b412adc2a3410deb68fc0aa9 | refs/heads/master | 2020-06-29T03:04:22.254725 | 2015-06-28T14:23:12 | 2015-06-28T14:23:12 | 32,430,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,761 | cc | #include <vector>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
void search(string &A, int pos, int len, vector<string> &res){
int left = pos-1;
int right = pos+1;
res.push_back(string(A,pos, 1));
while (left >= 0 && right < len){
if (A[left] == A[right]){
int path = 0;
while (pos - left - path >= 0){
string sub;
for (int i = left; i <= right; ++i){
if (i <= pos-path || i >= pos+path){
sub += A[i];
}
}
res.push_back(sub);
++path;
}
}
++right;
--left;
}
left = pos-1;
right = pos+1;
if (right < len && A[pos] == A[right]){
res.push_back(string(A, pos, 2));
++right;
while (left >= 0 && right < len){
if (A[left] == A[right]){
int path = 0;
while (pos - left - path > 0){
string sub;
for (int i = left; i <= right; ++i){
if (i <= pos-path || i > pos+path+1 || !path){
sub += A[i];
}
}
++path;
res.push_back(sub);
}
}
++right;
--left;
}
}
}
int main(int argc, char *argv[]){
int len = strlen(argv[1]);
string str(argv[1]);
vector<string> res;
for (int i = 0; i < len; ++i){
search(str, i, len, res);
}
cout << "sum = " << res.size() << endl;
for (int i = 0; i < res.size(); ++i){
cout << res[i] << endl;
}
return 0;
}
| [
"yangzhou221@gmail.com"
] | yangzhou221@gmail.com |
f5372f418280ac228ef670e88a673d73446cc0d0 | e50c0b453477dca0589e2876fbc8921968e894de | /QtCodeV2/Submissions/roanne-caoile/testmain.cpp | b7a00b670828375f649926f501963065734c0ae2 | [] | no_license | umidah/CodeChecker | 6c7840a59e7acfbe6fa48b578e8df3885f229497 | eee6beeae121ae81aa9158c628fb8a2eb1ad8864 | refs/heads/master | 2020-12-19T10:36:18.866162 | 2020-03-05T01:10:25 | 2020-03-05T01:10:25 | 235,707,385 | 1 | 1 | null | 2020-02-09T03:47:10 | 2020-01-23T02:10:09 | Java | UTF-8 | C++ | false | false | 2,100 | cpp | //io/test1.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
//assign ung string sa isang variable then compare
//ano metric
int main(){
string line1[30];
string line2[30];
string line3[30];
string line4[30];
string line;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int total = 7;
ifstream inFile;
ifstream inFile2;
ifstream JavaFile1;
ifstream JavaFile2;
inFile.open("test1.cpp",ios::in);
cout <<"File: test1.cpp"<<'\n';
if(inFile.is_open()){
while(!inFile.eof()){
getline(inFile,line1[a],'\n');
cout<<line1[a]<<'\n';
a++;
}
inFile.close();
}
else cout<< "Wrong.";
///////////////////////////////////////////////
inFile2.open("test2.cpp",ios::in);
cout <<'\n';
cout <<"File: test2.cpp"<<'\n';
if(inFile2.is_open()){
while(!inFile2.eof()){
getline(inFile2,line2[b],'\n');
cout<<line2[b]<<'\n';
b++;
}
inFile2.close();
}
else cout<< "Wrong.";
///////////////////////////////////////////////////////
int totalsim = 100;
for(int i=0;i<total;i++){
if(line1[i]==line2[i])continue;
else{
totalsim = totalsim - 1;
}
}
cout << "Similarity Percentage: ";
cout << totalsim<<'\n';
cout <<'\n';
////////////////////////////////////////////////////////
////java//
JavaFile1.open("test_program1.java",ios::in);
cout <<"test_program1.java"<<'\n';
if(JavaFile1.is_open()){
while(!JavaFile1.eof()){
getline(JavaFile1,line3[c],'\n');
cout<<line3[c]<<'\n';
c++;
}
JavaFile1.close();
}
else cout<< "Wrong.";
cout <<'\n';
JavaFile2.open("test_program2.java",ios::in);
cout <<"test_program2.java"<<'\n';
if(JavaFile2.is_open()){
while(!JavaFile2.eof()){
getline(JavaFile2,line4[d],'\n');
cout<<line4[d]<<'\n';
d++;
}
JavaFile2.close();
}
else cout<< "Wrong.";
///////////////////////////////////////////////////////
int totalsim2 = 100;
int total2 = 5;
for(int i=0;i<total2;i++){
if(line3[i]==line4[i])continue;
else{
totalsim2 = totalsim2 - 1;
}
}
cout << "Similarity Percentage: ";
cout << totalsim2<<'\n';
cout <<'\n';
}
| [
"46555380+umidah@users.noreply.github.com"
] | 46555380+umidah@users.noreply.github.com |
d494c58657798919f98bf59d12d706673733392b | d2e8e2f7ac6d3b71056ea79d7413e7dd7188789f | /include/ast_opt/visitor/AvoidParamMismatchVisitor.h | e86a3dcd4a7c356da30cf7661265a3ca14e49148 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | moritzwinger/ABC | c92a5bfe4c3adce0fd2b453d1ef083d63a3223a0 | 2d1f507dc7188b13767cce8050b8aa9daa7c1625 | refs/heads/main | 2023-07-25T16:56:19.122849 | 2021-09-07T10:51:37 | 2021-09-07T10:51:40 | 354,754,349 | 0 | 0 | NOASSERTION | 2021-04-05T07:29:30 | 2021-04-05T07:29:29 | null | UTF-8 | C++ | false | false | 2,689 | h |
#ifndef AST_OPTIMIZER_INCLUDE_AST_OPT_VISITOR_AVOIDPARAMMISMATCHVISITOR_H_
#define AST_OPTIMIZER_INCLUDE_AST_OPT_VISITOR_AVOIDPARAMMISMATCHVISITOR_H_
#include <list>
#include <sstream>
#include <string>
#include <utility>
#include <seal/seal.h>
#include "ast_opt/runtime/RuntimeVisitor.h"
#include "ast_opt/ast/AbstractNode.h"
#include "ast_opt/utilities/Visitor.h"
/// Forward declaration of the class that will actually implement the Visitor's logic
class SpecialAvoidParamMismatchVisitor;
/// uses the Visitor<T> template to allow specifying default behaviour
typedef Visitor<SpecialAvoidParamMismatchVisitor> AvoidParamMismatchVisitor;
class SpecialAvoidParamMismatchVisitor : public ScopedVisitor {
/// map unique_node_id --> bool that indicates if a node has already been visited
std::unordered_map<std::string, bool> isVisited;
std::unordered_map<std::string, std::vector<seal::Modulus>> coeffmodulusmap;
std::unordered_map<std::string, std::vector<seal::Modulus>> coeffmodulusmap_vars;
std::vector<BinaryExpression *> modSwitchNodes;
public:
explicit SpecialAvoidParamMismatchVisitor( std::unordered_map<std::string, std::vector<seal::Modulus>> coeffmodulusmap,
std::unordered_map<std::string, std::vector<seal::Modulus>> coeffmodulusmap_vars);
/// Visits an AST and based on the coefficient modulus map identifies binary expressions
/// where a modswitch op needs to be inserted to avoid parameter mismatch. pushes them into the vector modSwitchNodes
/// \param node
void visit(BinaryExpression &elem);
/// insert modswittch as needed to fix the potential parameter mismatch caused by the InsertModSwitchVisitor
/// \param ast to rewrite
/// \param binary expression as ientified from the AvoidParamMismatch visitor (visit(BinaryExpression &elem))
/// \return a rewritten ast
std::unique_ptr<AbstractNode> insertModSwitchInAst(std::unique_ptr<AbstractNode> *ast, BinaryExpression *binaryExpression = nullptr);
/// getter function for BinaryExpressions where modswitches need to be inserted
/// \return modSwitch nodes: Binary expressions whose children need to be modswitched to ensure correctness of the circuit.
std::vector<BinaryExpression *> getModSwitchNodes();
/// getter for coeffmodulus map
/// \return coeffmodulusmap
std::unordered_map<std::string, std::vector<seal::Modulus>> getCoeffModulusMap();
/// getter for coeffmodulus map (key: variable identifier)
/// \return coeffmodulusmap_vars
std::unordered_map<std::string, std::vector<seal::Modulus>> getCoeffModulusMapVars();
};
#endif //AST_OPTIMIZER_INCLUDE_AST_OPT_VISITOR_AVOIDPARAMMISMATCHVISITOR_H_
| [
"moritzwinger1@gmail.com"
] | moritzwinger1@gmail.com |
66e86f643cbff06a97e07fcebb8b1b310e8f1d9b | 198788e3f399912074dae3882e02b2067450e289 | /Kame/src/Kame/Platform/DirectX12/Graphics/StructuredBuffer.cpp | 7d95268af4c681760ae062ac17b422c2319b5015 | [
"Apache-2.0"
] | permissive | keinich/Kame | c3da062591a693370c937afd4db007b00328f5da | 5fc6a15daf3d03d7bce2fd448697f323f55c3ada | refs/heads/master | 2020-07-20T07:29:49.276975 | 2020-02-29T17:37:34 | 2020-02-29T17:37:34 | 206,598,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,482 | cpp | #include "kmpch.h"
#include "StructuredBuffer.h"
#include "DX12Core.h"
#include "ResourceStateTracker.h"
#include <d3dx12.h>
namespace Kame {
StructuredBuffer::StructuredBuffer(const std::wstring& name)
: Buffer(name)
, m_CounterBuffer(
CD3DX12_RESOURCE_DESC::Buffer(4, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
1, 4, name + L" Counter")
, m_NumElements(0)
, m_ElementSize(0) {
m_SRV = DX12Core::Get().AllocateDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
m_UAV = DX12Core::Get().AllocateDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
StructuredBuffer::StructuredBuffer(const D3D12_RESOURCE_DESC& resDesc,
size_t numElements, size_t elementSize,
const std::wstring& name)
: Buffer(resDesc, numElements, elementSize, name)
, m_CounterBuffer(
CD3DX12_RESOURCE_DESC::Buffer(4, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
1, 4, name + L" Counter")
, m_NumElements(numElements)
, m_ElementSize(elementSize) {
m_SRV = DX12Core::Get().AllocateDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
m_UAV = DX12Core::Get().AllocateDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
void StructuredBuffer::CreateViews(size_t numElements, size_t elementSize) {
auto device = DX12Core::Get().GetDevice();
m_NumElements = numElements;
m_ElementSize = elementSize;
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srvDesc.Format = DXGI_FORMAT_UNKNOWN;
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Buffer.NumElements = static_cast<UINT>(m_NumElements);
srvDesc.Buffer.StructureByteStride = static_cast<UINT>(m_ElementSize);
srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
device->CreateShaderResourceView(m_d3d12Resource.Get(),
&srvDesc,
m_SRV.GetDescriptorHandle());
D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
uavDesc.Format = DXGI_FORMAT_UNKNOWN;
uavDesc.Buffer.CounterOffsetInBytes = 0;
uavDesc.Buffer.NumElements = static_cast<UINT>(m_NumElements);
uavDesc.Buffer.StructureByteStride = static_cast<UINT>(m_ElementSize);
uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
device->CreateUnorderedAccessView(m_d3d12Resource.Get(),
m_CounterBuffer.GetD3D12Resource().Get(),
&uavDesc,
m_UAV.GetDescriptorHandle());
}
} | [
"rafael.weschle@gmail.com"
] | rafael.weschle@gmail.com |
5988a458c7690b080916f4c8e6732925a35504c3 | 5ae3af1b2bee92fd62554776e5058c6bd42e41d6 | /glbcodebase/graphicslab/glb/scene/glbmodelfile.cpp | 4f33c2f07f5f6c72a80d6ae4a2cdf8176e2d7507 | [] | no_license | pyclyy/GraphicsLabtory | ce51d8fe1ee8d2ae153397aed703128af226fdeb | 016c5bf9ac29e5d20a0556e6d0b384758bb6e02d | refs/heads/master | 2020-03-19T16:18:35.336778 | 2018-06-09T08:15:22 | 2018-06-09T08:15:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,637 | cpp | //--------------------------------------------------------------------
// Declaration: Copyright (c), by i_dovelemon, 2016. All right reserved.
// Author: i_dovelemon[1322600812@qq.com]
// Date: 2016/06/19
// Brief: Define a interface to analysis the model file
//--------------------------------------------------------------------
#include "glbmodelfile.h"
#include <fstream>
#include <vector>
#include "math/glbvector.h"
#include "util/glbmacro.h"
namespace glb {
namespace scene {
//----------------------------------------------------------------------------------------
// CONSTANT VALUE
//----------------------------------------------------------------------------------------
const int32_t kMaxFilePostFixLength = 8;
const int32_t kVertexPerTri = 3;
const int32_t kObjFloatPerVertex = 3;
const int32_t kObjFloatPerTexcoord = 2;
const int32_t kObjFloatPerNormal = 3;
const int32_t kObjFloatPerTangent = 3;
const int32_t kObjFloatPerBinormal = 3;
const int32_t kObjMaxPrefixLength = 32;
const int32_t kObjMaxLineLength = 256;
//----------------------------------------------------------------------------------------
// CLASS DECLARATION
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
// ModelFileBase DECLARATION
//----------------------------------------------------------------------------------------
class ModelFileBase {
public:
ModelFileBase() {
}
virtual ~ModelFileBase() {
}
public:
virtual int32_t ExtractModelData(
const char* model_file_name,
ModelEffectParam& effect_param,
ModelMaterialParam& material_param,
float** vertex_buf,
float** texcoord_buf = NULL,
float** normal_buf = NULL,
float** tangent_buf = NULL,
float** binormal_buf = NULL
) = 0;
};
//----------------------------------------------------------------------------------------
// ObjModelFile DECLARATION
//----------------------------------------------------------------------------------------
class ObjModelFile:public ModelFileBase {
public:
ObjModelFile();
virtual ~ObjModelFile();
public:
int32_t ExtractModelData(
const char* model_file_name,
ModelEffectParam& effect_param,
ModelMaterialParam& material_param,
float** vertex_buf,
float** texcoord_buf = NULL,
float** normal_buf = NULL,
float** tangent_buf = NULL,
float** binormal_buf = NULL
);
protected:
void ExtractFaceData(const char* buffer, int32_t& vertex_index, int32_t& texcoord_index, int32_t& normal_index, int32_t& tangent_index, int32_t& binormal_index);
};
//----------------------------------------------------------------------------------------
// CLASS DEFINITION
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
// ObjModelFile DEFINITION
//----------------------------------------------------------------------------------------
class ObjFace {
public:
int32_t vertex_index[3];
int32_t texcoord_index[3];
int32_t normal_index[3];
int32_t tangent_index[3];
int32_t binormal_index[3];
ObjFace() {
memset(vertex_index, 0, sizeof(vertex_index));
memset(texcoord_index, 0, sizeof(texcoord_index));
memset(normal_index, 0, sizeof(normal_index));
memset(tangent_index, 0, sizeof(tangent_index));
memset(binormal_index, 0, sizeof(binormal_index));
}
};
ObjModelFile::ObjModelFile() {
}
ObjModelFile::~ObjModelFile() {
}
int32_t ObjModelFile::ExtractModelData(
const char* modelFileName,
ModelEffectParam& effectParam,
ModelMaterialParam& materialParam,
float** vertexBuf,
float** texcoordBuf,
float** normalBuf,
float** tangentBuf,
float** binormalBuf
) {
int32_t result = 0;
if (modelFileName != NULL && vertexBuf != NULL) {
std::ifstream input;
input.open(modelFileName);
if (!input.fail()) {
std::vector<math::Vector> vertexArray;
std::vector<math::Vector> texArray;
std::vector<math::Vector> normalArray;
std::vector<math::Vector> tangentArray;
std::vector<math::Vector> binormalArray;
std::vector<ObjFace> faceArray;
char prefix[kObjMaxPrefixLength];
char buffer[kObjMaxLineLength];
materialParam.boundboxMin.x = FLT_MAX;
materialParam.boundboxMin.y = FLT_MAX;
materialParam.boundboxMin.z = FLT_MAX;
materialParam.boundboxMax.x = 0.0f;
materialParam.boundboxMax.y = 0.0f;
materialParam.boundboxMax.z = 0.0f;
// Read the data from file
while (!input.eof()) {
input >> prefix;
if (!strcmp(prefix, "v")) {
// Vertex
math::Vector vertex;
input >> vertex.x >> vertex.y >> vertex.z;
vertexArray.push_back(vertex);
if (vertex.x < materialParam.boundboxMin.x) {
materialParam.boundboxMin.x = vertex.x;
} else if (vertex.x > materialParam.boundboxMax.x) {
materialParam.boundboxMax.x = vertex.x;
}
if (vertex.y < materialParam.boundboxMin.y) {
materialParam.boundboxMin.y = vertex.y;
} else if (vertex.y > materialParam.boundboxMax.y) {
materialParam.boundboxMax.y = vertex.y;
}
if (vertex.z < materialParam.boundboxMin.z) {
materialParam.boundboxMin.z = vertex.z;
} else if (vertex.z > materialParam.boundboxMax.z) {
materialParam.boundboxMax.z = vertex.z;
}
} else if (!strcmp(prefix, "vt")) {
// Texture Coordinate
math::Vector texcoord;
// input >> texcoord.x >> texcoord.y >> texcoord.z;
input >> texcoord.x >> texcoord.y; // .obj from blender do not have z value for texture coordinate
texArray.push_back(texcoord);
effectParam.hasTexcoord = true;
} else if (!strcmp(prefix, "vn")) {
// Normal
math::Vector normal;
input >> normal.x >> normal.y >> normal.z;
normalArray.push_back(normal);
effectParam.hasNormal = true;
} else if (!strcmp(prefix, "vtan")) {
// Tangent
math::Vector tanget;
input >> tanget.x >> tanget.y >> tanget.z;
tangentArray.push_back(tanget);
effectParam.hasTanget = true;
} else if (!strcmp(prefix, "vbi")) {
// Binormal
math::Vector binormal;
input >> binormal.x >> binormal.y >> binormal.z;
binormalArray.push_back(binormal);
effectParam.hasBinormal = true;
} else if (!strcmp(prefix, "f")) {
// Triangle
ObjFace face;
for (int32_t i = 0; i < kVertexPerTri; i++) {
input >> buffer;
ExtractFaceData(buffer, face.vertex_index[i], face.texcoord_index[i], face.normal_index[i], face.tangent_index[i], face.binormal_index[i]);
}
faceArray.push_back(face);
} else if (!strcmp(prefix, "talbedo")) {
// Albedo texture
input >> buffer;
effectParam.hasAlbedoTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.albedoTexName, buffer, len);
materialParam.albedoTexName[len] = '\0';
} else if (!strcmp(prefix, "troughness")) {
// Roughness texture
input >> buffer;
effectParam.hasRoughnessTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.roughnessTexName, buffer, len);
materialParam.roughnessTexName[len] = '\0';
} else if (!strcmp(prefix, "tmetallic")) {
// Metallic texture
input >> buffer;
effectParam.hasMetallicTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.metallicTexName, buffer, len);
materialParam.metallicTexName[len] = '\0';
} else if (!strcmp(prefix, "talpha")) {
// Alpha texture
input >> buffer;
effectParam.hasAlphaTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.alphaTexName, buffer, len);
materialParam.alphaTexName[len] = '\0';
} else if (!strcmp(prefix, "tnormal")) {
// Normal texture
input >> buffer;
effectParam.hasNormalTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.normalTexName, buffer, len);
materialParam.normalTexName[len] = '\0';
} else if (!strcmp(prefix, "temission")) {
// Emission texture
input >> buffer;
effectParam.hasEmissionTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.emissionTexName, buffer, len);
materialParam.emissionTexName[len] = '\0';
} else if (!strcmp(prefix, "tdiffusepfc")) {
// Diffuse Prefilter CubeMap texture
input >> buffer;
effectParam.hasDiffusePFCTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.diffusePFCTexName, buffer, len);
materialParam.diffusePFCTexName[len] = '\0';
} else if (!strcmp(prefix, "tspecularpfc")) {
// Specular Prefilter CubeMap texture
input >> buffer;
effectParam.hasSpecularPFCTex = true;
int32_t len = strlen(buffer);
memcpy(materialParam.specularPFCTexName, buffer, len);
materialParam.specularPFCTexName[len] = '\0';
} else if (!strcmp(prefix, "al")) {
// Accept light
int32_t temp = 0;
input >> temp;
if (temp != 0) {
effectParam.acceptLight = true;
} else {
effectParam.acceptLight = false;
}
} else if (!strcmp(prefix, "as")) {
// Accept shadow
int32_t temp = 0;
input >> temp;
if (temp != 0) {
effectParam.acceptShadow = true;
} else {
effectParam.acceptShadow = false;
}
} else if (!strcmp(prefix, "ao")) {
// Use AO
int32_t temp = 0;
input >> temp;
if (temp != 0) {
effectParam.useAO = true;
} else {
effectParam.useAO = false;
}
} else if (!strcmp(prefix, "cs")) {
// Cast shadow
int32_t temp = 0;
input >> temp;
if (temp != 0) {
effectParam.castShadow = true;
} else {
effectParam.castShadow = false;
}
} else if (!strcmp(prefix, "ma")) {
// Material ambient
math::Vector ambient;
input >> ambient.x >> ambient.y >> ambient.z;
materialParam.ambient = ambient;
} else if (!strcmp(prefix, "md")) {
// Material diffuse
math::Vector diffuse;
input >> diffuse.x >> diffuse.y >> diffuse.z;
materialParam.diffuse = diffuse;
} else if (!strcmp(prefix, "ms")) {
// Material specular
math::Vector specular;
input >> specular.x >> specular.y >> specular.z;
materialParam.specular = specular;
} else if (!strcmp(prefix, "me")) {
// Material emission
math::Vector emission;
input >> emission.x >> emission.y >> emission.z;
materialParam.emission = emission;
} else if (!strcmp(prefix, "mp")) {
// Material pow
float pow = 0.0f;
input >> pow;
materialParam.pow = pow;
} else if (!strcmp(prefix, "malbedo")) {
// Material base color(or reflectance for metal)
math::Vector albedo;
input >> albedo.x;
input >> albedo.y;
input >> albedo.z;
materialParam.albedo = albedo;
} else if (!strcmp(prefix, "mroughness")) {
// Material roughness
float roughness = 0.0f;
input >> roughness;
materialParam.roughness = roughness;
} else if (!strcmp(prefix, "mmetallic")) {
// Material metallic
float metallic = 0.0f;
input >> metallic;
materialParam.metallic = metallic;
} else {
input.getline(buffer, sizeof(buffer));
memset(buffer, 0, sizeof(buffer));
}
}
input.close();
// Generate the buffer
int32_t triangle_num = faceArray.size();
*vertexBuf = new float[kVertexPerTri * triangle_num * kObjFloatPerVertex];
for (int32_t i = 0; i < triangle_num; i++) {
for (int32_t j = 0; j < kVertexPerTri; j++) {
(*vertexBuf)[i * kVertexPerTri * kObjFloatPerVertex + j * kObjFloatPerVertex + 0] = vertexArray[faceArray[i].vertex_index[j] - 1].x;
(*vertexBuf)[i * kVertexPerTri * kObjFloatPerVertex + j * kObjFloatPerVertex + 1] = vertexArray[faceArray[i].vertex_index[j] - 1].y;
(*vertexBuf)[i * kVertexPerTri * kObjFloatPerVertex + j * kObjFloatPerVertex + 2] = vertexArray[faceArray[i].vertex_index[j] - 1].z;
}
}
if (texArray.size() > 0 && texcoordBuf != NULL) {
*texcoordBuf = new float[kVertexPerTri * triangle_num * kObjFloatPerTexcoord];
for (int32_t i = 0; i < triangle_num; i++) {
for (int32_t j = 0; j < kVertexPerTri; j++) {
(*texcoordBuf)[i * kVertexPerTri * kObjFloatPerTexcoord + j * kObjFloatPerTexcoord + 0] = texArray[faceArray[i].texcoord_index[j] - 1].x;
(*texcoordBuf)[i * kVertexPerTri * kObjFloatPerTexcoord + j * kObjFloatPerTexcoord + 1] = texArray[faceArray[i].texcoord_index[j] - 1].y;
}
}
}
if (normalArray.size() > 0 && normalBuf != NULL) {
*normalBuf = new float[kVertexPerTri * triangle_num * kObjFloatPerNormal];
for (int32_t i = 0; i < triangle_num; i++) {
for (int32_t j = 0; j < kVertexPerTri; j++) {
(*normalBuf)[i * kVertexPerTri * kObjFloatPerNormal + j * kObjFloatPerNormal + 0] = normalArray[faceArray[i].normal_index[j] - 1].x;
(*normalBuf)[i * kVertexPerTri * kObjFloatPerNormal + j * kObjFloatPerNormal + 1] = normalArray[faceArray[i].normal_index[j] - 1].y;
(*normalBuf)[i * kVertexPerTri * kObjFloatPerNormal + j * kObjFloatPerNormal + 2] = normalArray[faceArray[i].normal_index[j] - 1].z;
}
}
}
if (tangentArray.size() > 0 && tangentBuf != NULL) {
*tangentBuf = new float[kVertexPerTri * triangle_num * kObjFloatPerTangent];
for (int32_t i = 0; i < triangle_num; i++) {
for (int32_t j = 0; j < kVertexPerTri; j++) {
(*tangentBuf)[i * kVertexPerTri * kObjFloatPerTangent + j * kObjFloatPerTangent + 0] = tangentArray[faceArray[i].tangent_index[j] - 1].x;
(*tangentBuf)[i * kVertexPerTri * kObjFloatPerTangent + j * kObjFloatPerTangent + 1] = tangentArray[faceArray[i].tangent_index[j] - 1].y;
(*tangentBuf)[i * kVertexPerTri * kObjFloatPerTangent + j * kObjFloatPerTangent + 2] = tangentArray[faceArray[i].tangent_index[j] - 1].z;
}
}
}
if (binormalArray.size() > 0 && binormalBuf != NULL) {
*binormalBuf = new float[kVertexPerTri * triangle_num * kObjFloatPerBinormal];
for (int32_t i = 0; i < triangle_num; i++) {
for (int32_t j = 0; j < kVertexPerTri; j++) {
(*binormalBuf)[i * kVertexPerTri * kObjFloatPerBinormal + j * kObjFloatPerBinormal + 0] = binormalArray[faceArray[i].binormal_index[j] - 1].x;
(*binormalBuf)[i * kVertexPerTri * kObjFloatPerBinormal + j * kObjFloatPerBinormal + 1] = binormalArray[faceArray[i].binormal_index[j] - 1].y;
(*binormalBuf)[i * kVertexPerTri * kObjFloatPerBinormal + j * kObjFloatPerBinormal + 2] = binormalArray[faceArray[i].binormal_index[j] - 1].z;
}
}
}
// Save the number of triangles
result = faceArray.size();
} else {
input.close();
GLB_SAFE_ASSERT(false);
}
} else {
GLB_SAFE_ASSERT(false);
}
return result;
}
void ObjModelFile::ExtractFaceData(const char* buffer, int32_t& vertex_index, int32_t& texcoord_index, int32_t& normal_index, int32_t& tanget_index, int32_t& binormal_index) {
if (buffer != NULL) {
// Extract vertex index
vertex_index = atoi(buffer);
// Has texture coordinate index ?
int32_t index = 0;
int32_t buf_len = strlen(buffer);
for (index = 0; index < buf_len; index++) {
if (buffer[index] == '/') {
break;
}
}
if (index < buf_len - 1) {
if (buffer[index + 1] != '/') {
const char* tex_index_buf = reinterpret_cast<const char*>(buffer + index + 1);
texcoord_index = atoi(tex_index_buf);
}
}
// Has normal index ?
for (index = index + 1; index < buf_len; index++) {
if (buffer[index] == '/') {
break;
}
}
if (index < buf_len - 1) {
const char* normal_index_buf = reinterpret_cast<const char*>(buffer + index + 1);
normal_index = atoi(normal_index_buf);
}
// Has tanget index ?
for (index = index + 1; index < buf_len; index++) {
if (buffer[index] == '/') {
break;
}
}
if (index < buf_len - 1) {
const char* tanget_index_buf = reinterpret_cast<const char*>(buffer + index + 1);
tanget_index = atoi(tanget_index_buf);
}
// Has binormal index ?
for (index = index + 1; index < buf_len; index++) {
if (buffer[index] == '/') {
break;
}
}
if (index < buf_len - 1) {
const char* binormal_index_buf = reinterpret_cast<const char*>(buffer + index + 1);
binormal_index = atoi(binormal_index_buf);
}
} else {
GLB_SAFE_ASSERT(false);
}
}
//----------------------------------------------------------------------------------------
// ModelFile DEFINITION
//----------------------------------------------------------------------------------------
int32_t ModelFile::ExtractModelData(const char* model_file_name,
ModelEffectParam& effect_param,
ModelMaterialParam& material_param,
float** vertex_buf,
float** texcoord_buf,
float** normal_buf,
float** tanget_buf,
float** binormal_buf) {
int32_t result = 0;
if (model_file_name != NULL && vertex_buf != NULL) {
char postfix[kMaxFilePostFixLength];
int32_t len = strlen(model_file_name);
int32_t dot_index = 0;
for (; dot_index < len; dot_index++) {
if (model_file_name[dot_index] == '.') {
break;
}
}
// Has dot?
if (dot_index < len - 1) {
memcpy(postfix, model_file_name + dot_index, len - dot_index);
postfix[len - dot_index] = 0;
if (!strcmp(postfix, ".obj")) {
ObjModelFile obj_model;
result = obj_model.ExtractModelData(
model_file_name,
effect_param,
material_param,
vertex_buf,
texcoord_buf,
normal_buf,
tanget_buf,
binormal_buf);
} else {
GLB_SAFE_ASSERT(false);
}
}
} else {
GLB_SAFE_ASSERT(false);
}
return result;
}
void ModelFile::RelaseBuf(float** vertex_buf, float** texcoord_buf, float** normal_buf, float** tanget_buf, float** binormal_buf) {
if (vertex_buf != NULL) {
float* buf = *vertex_buf;
if (buf != NULL) {
delete[] buf;
buf = NULL;
}
*vertex_buf = NULL;
}
if (texcoord_buf != NULL) {
float* buf = *texcoord_buf;
if (buf != NULL) {
delete[] buf;
buf = NULL;
}
*texcoord_buf = NULL;
}
if (normal_buf != NULL) {
float* buf = *normal_buf;
if (buf != NULL) {
delete[] buf;
buf = NULL;
}
*normal_buf = NULL;
}
if (tanget_buf != NULL) {
float* buf = *tanget_buf;
if (buf != NULL) {
delete[] buf;
buf = NULL;
}
*tanget_buf = NULL;
}
if (binormal_buf != NULL) {
float* buf = *binormal_buf;
if (buf != NULL) {
delete[] buf;
buf = NULL;
}
*binormal_buf = NULL;
}
}
}; // namespace scene
}; // namespace glb | [
"1322600812@qq.com"
] | 1322600812@qq.com |
b05d214360db8179c89dda9fa5cda25333ea10d4 | 196f8f99d6e6348a5ee24f827db1d3a09a74c6e6 | /EASYPROB/main.cpp | ad26188f91ee58ae0c4ea80a5fcd42d66f2ac344 | [] | no_license | gagan86nagpal/SPOJ-200 | a8259cb5b9eb6392589b25580ecc32c265f44736 | b7ac87787a9ec89fbf9db86493398d309efe103f | refs/heads/master | 2021-09-06T16:13:38.141265 | 2018-02-08T12:10:47 | 2018-02-08T12:10:47 | 111,628,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | #include <iostream>
using namespace std;
int main()
{
string _1 = "2(0)";
string _2 = "2";
string _4 = "2(2)";
string _8 = "2(2+2(0))";
string _16= "2(2(2))";
string _32 = "2(2(2)+2(0))";
string _64 = "2(2(2)+2)";
string _128 ="2(2(2)+2+2(0))";
string _256="2(2(2+2(0)))";
string _1024 = "2(2(2+2(0))+2)";
string _16384="2(2(2+2(0))+2(2)+2)";
cout<<"137="<<_128+"+"+_8+"+"+_1<<"\n";
cout<<"1315="<<_1024+"+"+_256+"+"+_32+"+"+_2+"+"+_1<<"\n";
cout<<"73="<<_64+"+"+_8+"+"+_1<<"\n";
cout<<"136="<<_128+"+"+_8<<"\n";
cout<<"255="<<_128+"+"+_64+"+"+_32+"+"+_16+"+"+_8+"+"+_4+"+"+_2+"+"+_1<<"\n";
cout<<"1384="<<_1024+"+"+_256+"+"+_64+"+"+_32+"+"+_8<<"\n";
cout<<"16385="<<_16384+"+"+_1<<"\n";
return 0;
}
| [
"gagannagpal68@gmail.com"
] | gagannagpal68@gmail.com |
a92510f82996fdd16785314d9e10cabaa9c2299a | 24ed54bc1c0f2a6cec444192d2a32cf751bcafc1 | /2020_07/2020_07_21/src/epoll_loop.cpp | 219cdb0978687b816ba4d2010e97b0d80cbf72b7 | [] | no_license | CodeHina/MyLearn | 4c0a5b8d421ad274988a35cc6a27ef1a0be6c19e | 6ae37f8c956ff3904f5144961fd0b32e10e502f8 | refs/heads/master | 2022-11-23T16:56:20.930156 | 2020-07-29T08:39:34 | 2020-07-29T08:39:34 | 268,450,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,837 | cpp | #include <iostream>
#include <cstring>
#include <cctype>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <unistd.h>
#include "../include/wrap_sock.h"
#define MAX_EVENTS 1024 //监听上限
#define SEVR_PORT 1234
void recv_data(int, int, void*);
void send_data(int, int, void*);
struct myevents
{
int fd; //要监听的文件描述符
int event; //所对应的监听事件
void *arg; //回调函数参数
void (*call_back)(int fd, int evt, void* arg); //事件触发时的回调函数
int moni_status; //监听状态 - 是否在红黑树上 - 0/1
char buf[BUFSIZ];
size_t len;
long last_active; //记录每次在红黑树上操作的时间
};
int g_efd; //全局变量 - 保存epoll_create返回的文件描述符
myevents g_myevts[MAX_EVENTS + 1]; //监听事件数组
/* 将当前文件描述符对应的epoll_event::data.ptr进行设定 */
void event_set(myevents* ev, int fd, void(*call_back)(int, int, void*), void* arg)
{
ev->fd = fd;
ev->event = 0;
ev->arg = arg;
ev->call_back = call_back;
ev->moni_status = 0;
//memset(ev->buf, 0, sizeof(ev->buf));
//ev->len = 0;
ev->last_active = time(nullptr); //更新当前时间
}
/* 将当前的文件描述符添加到红黑树上 */
void event_add(int efd, int event, myevents* ev/*I/O*/)
{
epoll_event epv = {0, {0}}; //此文件描述符对应的epoll_event
int op;//对此文件描述符的操作方式
epv.data.ptr = ev; //构造此事件
epv.events = ev->event = event;
if(ev->moni_status == true)
op = EPOLL_CTL_MOD; //此文件描述符已经在监听树上 - 修改即可
else
op = EPOLL_CTL_ADD; //不在则添加
if(epoll_ctl(efd, op, ev->fd, &epv) < 0)
{
std::cout << "-----\nevent ctl(add/mod) failed at fd : " << ev->fd;
switch(epv.events)
{
case EPOLLIN:
std::cout << " at EPOLLIN\n-----" << std::endl; break;
case EPOLLOUT:
std::cout << " at EPOLLOUT\n-----" << std::endl; break;
}
perror("epoll_ctl_add err");
}
else
{
ev->moni_status = 1;
std::cout << "-----\nevent ctl(add/mod) success at fd : " << ev->fd;
switch(epv.events)
{
case EPOLLIN:
std::cout << " at EPOLLIN\n-----" << std::endl; break;
case EPOLLOUT:
std::cout << " at EPOLLOUT\n-----" << std::endl; break;
}
}
return;
}
void event_del(int efd, myevents* ev)
{
epoll_event epv = {0, {0}};
if(ev->moni_status == 0)//已经不在树上
return;
epv.data.ptr = ev;
epv.events = ev->event;
ev->moni_status = 0; //将要操作的epoll_event是将的参数进行填充 - 更改此事件的监听状态(从监听树上取下)
int op = EPOLL_CTL_DEL;
if(epoll_ctl(efd, op, ev->fd, &epv) < 0)
{
std::cout << "-----\nevent ctl(del/mod) failed at fd : " << ev->fd;
switch(epv.events)
{
case EPOLLIN:
std::cout << " at EPOLLIN\n-----" << std::endl; break;
case EPOLLOUT:
std::cout << " at EPOLLOUT\n-----" << std::endl; break;
}
perror("epoll_ctl_del");
}
else
{
std::cout << "-----\nevent ctl(del/mod) success at fd : " << ev->fd;
switch(epv.events)
{
case EPOLLIN:
std::cout << " at EPOLLIN\n-----" << std::endl; break;
case EPOLLOUT:
std::cout << " at EPOLLOUT\n-----" << std::endl; break;
}
}
}
//evt->call_back(evt->fd, ready_evts[i].events, evt->arg);
void accept_conn(int fd, int evt, void* arg) //lfd的回调函数 - 每当有客户端连接触发此事件
{
//fd == lfd - evt == EPOLLIN - arg(lfd对应的myevents)
sockaddr_in link_client_addr;
socklen_t addr_len = sizeof(link_client_addr);
int cfd = -1;//与指定客户端进行通信socket
if( (cfd = Accept(fd, (sockaddr*)&link_client_addr, &addr_len)) < 0 )
{
if(errno != EAGAIN || errno != EINTR) //非阻塞的lfd - 未收到连接请求则返回-1并设置errno 或者 被信号中断
{
}
//Accept()已经封装其他出错处理 - in wrap_sock.cpp
}
//成功建立一个连接
int avai_client_pos;//g_myevts中的一个可用位置
do
{
for(avai_client_pos = 0; avai_client_pos < MAX_EVENTS; ++avai_client_pos)
{
if(g_myevts[avai_client_pos].moni_status == 0)//当前位置的事件还未被监听
break; //故可以被使用作为当前连接客户端的一个监听事件
}
if(avai_client_pos == MAX_EVENTS) //无可用位置
{
std::cerr << "too many connect,max connect client is " << MAX_EVENTS << std::endl;
break; //跳出循环 - 不执行下边代码 - do while(0)相当于一个goto语句
}
int flag = 0; //将监听已连接客户端请求的cfd的设置为非阻塞
if( (flag = fcntl(cfd, F_SETFL, SOCK_NONBLOCK)) < 0)
{
perror("fcntl err - set SOCK_NONBLOCK failed");
}
//设置此cfd的事件 - myevents - 其回调函数为recv_data - 监听cfd的可读事件 - 即客户端向服务端的写事件
event_set(&g_myevts[avai_client_pos], cfd, recv_data, &g_myevts[avai_client_pos]);
event_add(g_efd, EPOLLIN, &g_myevts[avai_client_pos]);
}while(0);
//打印此客户端的相关信息 - 以及自动向客户端回写欢迎语句
char client_addr[INET_ADDRSTRLEN];
const char* addr = inet_ntop(AF_INET, &link_client_addr.sin_addr, client_addr, sizeof(client_addr));
std::cout << "client:" << addr << " - port:" << ntohs(link_client_addr.sin_port) << " log in" << std::endl;
send(cfd, "****welcome to log in server****", sizeof("****welcome to log in server****"), MSG_DONTWAIT);
}
void init_lisent_socket(int efd, int port)
{
int lfd = Socket(AF_INET, SOCK_STREAM, 0);
fcntl(lfd, F_SETFL, SOCK_NONBLOCK); //设置为非阻塞
/* void event_set(myevents*, int, void(*call_back)(int, int, void*), void*) */
//设置lfd对应事件的结构体 - 初始化其各项指标 - 对g_myevts[MAX_EVENTS]对应的myevents进行初始化
event_set(&g_myevts[MAX_EVENTS], lfd, accept_conn, &g_myevts[MAX_EVENTS]);
/* void event_add(int, int, myevents*) */
//将当前的文件描述符添加到红黑树上 -
event_add(efd, EPOLLIN, &g_myevts[MAX_EVENTS]);
sockaddr_in sevr_addr; //服务器地址地址参数
memset(&sevr_addr, 0, sizeof(sevr_addr));
sevr_addr.sin_family = AF_INET;
sevr_addr.sin_port = htons(port);
sevr_addr.sin_addr.s_addr = htonl(INADDR_ANY);
Bind(lfd, (sockaddr*)&(sevr_addr), sizeof(sevr_addr));//将socket和服务器端口ip地址等信息进行绑定
Listen(lfd, 128); //同时建立连接的客户端个数
}
int main(int argc, char* argv[])
{
unsigned short port = SEVR_PORT;
if(argc == 2)
port = atoi(argv[1]); //用户自定义端口
g_efd = epoll_create(MAX_EVENTS + 1);
if(g_efd == -1)
{ perror("epoll_create err"); exit(-1); }
memset(g_myevts, 0, sizeof(g_myevts));//全部数据置为0
init_lisent_socket(g_efd, port); //初始化监听socket
epoll_event ready_evts[MAX_EVENTS + 1]; //保存就绪的文件描述符
std::cout << "sever wait client to link........" << std::endl;
while(1)
{
/* 超时验证 - 每次检测100个连接的客户端 - 当客户端60s内和服务器无数据通信 - 即关闭客户端连接 */
/* 监听红黑树g_efd - 将满足事件的文件描述符加入到ready_evts,只阻塞1s - 无事件满足即返回 - 轮询即可 */
int ready_fds = epoll_wait(g_efd, ready_evts, MAX_EVENTS + 1, 1000);
if(ready_fds == -1)
{ perror("epoll_wait err"); exit(-1); }
for(int i = 0; i < ready_fds; ++i)
{
/* epoll_event - event/data */
/* 接收就绪事件中的data.ptr - 泛型指针 */
myevents* evt = (myevents*)ready_evts[i].data.ptr;
if(ready_evts[i].events & EPOLLIN && (evt->event) & EPOLLIN) //都满足且为读就绪事件
{
evt->call_back(evt->fd, ready_evts[i].events, evt->arg);
}
if(ready_evts[i].events & EPOLLOUT && (evt->event) & EPOLLOUT)
{
evt->call_back(evt->fd, ready_evts[i].events, evt->arg);
}
}
}
/* 注意释放所有资源 */
return 0;
}
void recv_data(int fd, int evt, void* arg)
{
myevents* recv_evt = (myevents*)arg; //将满足事件的描述符所对应的事件结构体取出
/* 读取文件描述符中数据 - 将其写入此文件描述符事件的myevents的缓冲区中 */
int rdbytes = recv(fd, recv_evt->buf, sizeof(recv_evt->buf), 0);
/* 由于本服务器的特性是读取客户端数据后便向客户端发送一个消息 */
/* 由于滑动窗口的限制 - 若客户端的接收窗口内的数据是满的,即服务器向客户端写数据可能会阻塞 - */
event_del(g_efd, recv_evt); //将此文件描述符节点摘除
if(rdbytes > 0)
{
recv_evt->len = rdbytes; //本次读到的字节数
recv_evt->buf[recv_evt->len] = '\0';
for(int i = 0; i < rdbytes; ++i)//依次转为大写
toupper(recv_evt->buf[i]);
//std::cout << " the msg in recv_evt->buf is " << recv_evt->buf
// << " recv from fd : " << fd << std::endl;
event_set(recv_evt, recv_evt->fd, send_data, recv_evt); //将当前文件描述符的监听事件改为写并加到监听树上
event_add(g_efd, EPOLLOUT, recv_evt);
}
else if(rdbytes == 0) //客户端关闭 - 读到的数据为0
{
shutdown(recv_evt->fd, SHUT_RDWR);
std::cout << "\n##pos: " << recv_evt - g_myevts << " fd: " << recv_evt->fd << " closed" << std::endl;
}
else //其他错误 - EINTR/EWOULDBLOCK
{
shutdown(recv_evt->fd, SHUT_RDWR);
std::cout << "\n##pos: " << recv_evt - g_myevts << " fd: " << recv_evt->fd << " err" << std::endl;
perror("recv err");
}
}
void send_data(int fd, int evt, void* arg)
{
myevents* send_evt = (myevents*)arg;
//std::cout << "send_evt_addr is " << send_evt << std::endl;
//std::cout << "---wait send buf is " << send_evt->buf << " len is " << send_evt->len << std::endl;
int wrbytes = send(fd, &send_evt->buf, send_evt->len, 0);
event_del(g_efd, send_evt);
if(wrbytes >= 0)
{
//std::cout << "send to " << "fd:" << send_evt->fd << " " << wrbytes << "bytes" << std::endl;
/* 满足可写后调用此函数 - 然后重写监听可读事件 */
event_set(send_evt, fd, recv_data, send_evt);
event_add(g_efd, EPOLLIN, send_evt);
}
else //读取错误 - EINTR/EAGAIN等错误需要特殊处理
{
shutdown(send_evt->fd, SHUT_RDWR);
std::cout << " send to " << "fd: " << send_evt->fd << " err" << " wrbytes: " << wrbytes << std::endl;
perror("send err");
}
}
| [
"1398869163@qq.com"
] | 1398869163@qq.com |
a071e4d96d4d909acbd97b2baf85f0999368f1c3 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /TypeShield Source/old/dyninst-pass/ignore/patching.cpp | 1e1c129966226358714594139ab09b4e40f0d926 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,942 | cpp | #include "patching.h"
#include "BPatch_basicBlock.h"
#include "BPatch_function.h"
#include "BPatch_point.h"
#include "BPatch_process.h"
#include "BPatch_snippet.h"
#include "Command.h"
#include "Instrumenter.h"
#include "PatchMgr.h"
#include "PatchMgr.h"
#include "Snippet.h"
#include "Snippet.h"
#include "dynC.h"
#include "ca_defines.h"
#include "instrumentation.h"
#include "logging.h"
#include <unordered_set>
#define ENABLE_DEBUG_OUTPUT 0
using Dyninst::PatchAPI::Patcher;
using Dyninst::PatchAPI::PushBackCommand;
// For now this is the offset, as it is unlikely that something is outside of a disp32
// range ...
static const uint32_t ANNOTATION_OFFSET = 5;
// Create and insert a printf snippet
bool create_and_insert_snippet_callsite(BPatch_image *image,
std::vector<BPatch_point *> &points,
std::vector<char> label, uint32_t address,
Patcher &patcher)
{
auto as = image->getAddressSpace();
// auto snippet_ptr = Dyninst::PatchAPI::Snippet::create(new CallsiteCheck(image,
// ANNOTATION_OFFSET, label, address));
// Insert the snippet
#if ENABLE_DEBUG_OUTPUT == 1
{
std::vector<BPatch_function *> print_func;
image->findFunction("printf", print_func);
if (print_func.size() < 1)
{
LOG_ERROR(LOG_FILTER_GENERAL, "COULD NOT FIND PRINTF");
return false;
}
auto snippet_target = BPatch_dynamicTargetExpr();
std::vector<BPatch_snippet *> args;
auto pattern = BPatch_constExpr("Calling Address %lx\n");
args.push_back(&pattern);
args.push_back(&snippet_target);
auto snippet_call = BPatch_funcCallExpr(*print_func[0], args);
for (auto const &point : points)
{
patcher.add(PushBackCommand::create(
Dyninst::PatchAPI::convert(point, BPatch_callBefore),
Dyninst::PatchAPI::convert(&snippet_call)));
}
}
#endif
auto snippet_target = BPatch_dynamicTargetExpr();
auto snippet_off = BPatch_constExpr(ANNOTATION_OFFSET);
auto snippet_target_off = BPatch_arithExpr(BPatch_plus, snippet_off, snippet_target);
auto snippet = new BPatch_arithExpr(BPatch_deref, snippet_target_off);
for (auto const &point : points)
{
patcher.add(
PushBackCommand::create(Dyninst::PatchAPI::convert(point, BPatch_callBefore),
Dyninst::PatchAPI::convert(snippet)));
}
// LOG_DEBUG(LOG_FILTER_BINARY_PATCHING, "insertSnippet: SUCCESS");
return true;
}
class LabelBuilder
{
public:
virtual std::vector<char> generate_label(CallSite &) const = 0;
virtual std::vector<char> generate_label(CallTarget &) const = 0;
};
class AddressTakenLabelBuilder : public LabelBuilder
{
private:
std::unordered_set<uint64_t> at_addresses;
protected:
template <typename struct_has_function>
bool is_address_taken(struct_has_function const &data) const
{
std::vector<char> label;
auto function = data.function;
Dyninst::Address start, end;
function->getAddressRange(start, end);
return (at_addresses.count(start) > 0);
}
public:
AddressTakenLabelBuilder(TakenAddresses const &taken_addresses)
{
for (auto at : taken_addresses)
at_addresses.insert(at.first);
}
virtual std::vector<char> generate_label(CallSite &) const override
{
std::vector<char> label(4);
label[3] = 0x3F;
label[2] = 0x3F;
label[1] = 0x3F;
label[0] = 0x3F;
return label;
}
virtual std::vector<char> generate_label(CallTarget &call_target) const override
{
std::vector<char> label(4);
if (is_address_taken(call_target))
{
label[3] = 0x3F;
label[2] = 0x3F;
label[1] = 0x3F;
label[0] = 0x3F;
}
return label;
}
};
class ParamCountLabelBuilder : public AddressTakenLabelBuilder
{
protected:
template <int min, int max, typename struct_has_parameters, typename function_t>
char param_to_bitmask(struct_has_parameters const &data, function_t pred) const
{
unsigned char bitmask = 0;
auto const ¶meters = data.parameters;
for (int i = min; i < max; ++i)
{
if (pred(parameters[i]))
bitmask |= (0x1 << i);
}
return static_cast<char>(bitmask);
}
public:
ParamCountLabelBuilder(TakenAddresses const &taken_addresses)
: AddressTakenLabelBuilder(taken_addresses)
{
}
virtual std::vector<char> generate_label(CallSite &call_site) const override
{
std::vector<char> label(4);
label[1] = param_to_bitmask<0, 6>(call_site, [](char val) { return val == 'x'; });
label[0] = (0x1 << 6) - 1;
return label;
}
virtual std::vector<char> generate_label(CallTarget &call_target) const override
{
std::vector<char> label(4);
if (is_address_taken(call_target))
{
auto bitmask =
param_to_bitmask<0, 6>(call_target, [](char val) { return val == 'x'; });
label[0] = ((0x1 << 6) - 1) ^ bitmask;
label[1] = bitmask;
}
return label;
}
};
class ParamCountRetLabelBuilder : public ParamCountLabelBuilder
{
public:
ParamCountRetLabelBuilder(TakenAddresses const &taken_addresses)
: ParamCountLabelBuilder(taken_addresses)
{
}
virtual std::vector<char> generate_label(CallSite &call_site) const override
{
std::vector<char> label = ParamCountLabelBuilder::generate_label(call_site);
auto ret_bitmask =
param_to_bitmask<6, 7>(call_site, [](char val) { return val == 'x'; });
label[0] |= (0x1 << 6) ^ ret_bitmask;
label[1] |= (0x1 << 6);
return label;
}
virtual std::vector<char> generate_label(CallTarget &call_target) const override
{
std::vector<char> label = ParamCountLabelBuilder::generate_label(call_target);
if (is_address_taken(call_target))
{
auto ret_bitmask =
param_to_bitmask<6, 7>(call_target, [](char val) { return val == 'x'; });
label[0] |= (0x1 << 6);
label[1] |= ret_bitmask;
}
return label;
}
};
class ParamTypeLabelBuilder : public ParamCountLabelBuilder
{
protected:
template <int min, int max, typename struct_has_parameters>
void apply_provided(std::vector<char> &label, struct_has_parameters const &data) const
{
/* 8 byte width */
auto width_8byte = [](char val) { return (val == '8'); };
label[4] |= param_to_bitmask<min, max>(data, width_8byte);
/* 4 byte width */
auto width_4byte = [&](char val) { return (val == '4') || width_8byte(val); };
label[3] |= param_to_bitmask<min, max>(data, width_4byte);
/* 2 byte width */
auto width_2byte = [&](char val) { return (val == '2') || width_4byte(val); };
label[2] |= param_to_bitmask<min, max>(data, width_2byte);
/* 1 byte width */
auto width_1byte = [&](char val) { return (val == '1') || width_2byte(val); };
label[1] |= param_to_bitmask<min, max>(data, width_1byte);
/* 0 byte width */
auto width_0byte = [&](char val) { return (val == '0') || width_1byte(val); };
label[0] |= param_to_bitmask<min, max>(data, width_0byte);
}
template <int min, int max, typename struct_has_parameters>
void apply_required(std::vector<char> &label, struct_has_parameters const &data) const
{
/* 0 byte width */
auto width_0byte = [](char val) { return (val == '0'); };
label[0] = param_to_bitmask<min, max>(data, width_0byte);
/* 1 byte width */
auto width_1byte = [&](char val) { return (val == '1') || width_0byte(val); };
label[1] = param_to_bitmask<min, max>(data, width_1byte);
/* 2 byte width */
auto width_2byte = [&](char val) { return (val == '2') || width_1byte(val); };
label[2] = param_to_bitmask<min, max>(data, width_2byte);
/* 4 byte width */
auto width_4byte = [&](char val) { return (val == '4') || width_2byte(val); };
label[3] = param_to_bitmask<min, max>(data, width_4byte);
/* 8 byte width */
auto width_8byte = [&](char val) { return (val == '8') || width_4byte(val); };
label[4] = param_to_bitmask<min, max>(data, width_8byte);
}
public:
ParamTypeLabelBuilder(TakenAddresses const &taken_addresses)
: ParamCountLabelBuilder(taken_addresses)
{
}
virtual std::vector<char> generate_label(CallSite &call_site) const override
{
std::vector<char> label(5);
apply_provided<0, 6>(label, call_site);
return label;
}
virtual std::vector<char> generate_label(CallTarget &call_target) const override
{
std::vector<char> label(5);
if (is_address_taken(call_target))
{
apply_required<0, 6>(label, call_target);
}
return label;
}
};
class ParamTypeRetLabelBuilder : public ParamTypeLabelBuilder
{
public:
ParamTypeRetLabelBuilder(TakenAddresses const &taken_addresses)
: ParamTypeLabelBuilder(taken_addresses)
{
}
virtual std::vector<char> generate_label(CallSite &call_site) const override
{
std::vector<char> label(5);
apply_required<6, 7>(label, call_site);
return label;
}
virtual std::vector<char> generate_label(CallTarget &call_target) const override
{
std::vector<char> label(5);
if (is_address_taken(call_target))
{
apply_provided<6, 7>(label, call_target);
}
return label;
}
};
void patch_callsites(BPatch_object *object, BPatch_image *image, CADecoder *decoder,
CallSites call_sites, LabelBuilder const &label_builder)
{
auto as = image->getAddressSpace();
auto mgr = Dyninst::PatchAPI::convert(as);
Dyninst::PatchAPI::Patcher patcher(mgr);
for (auto call_site : call_sites)
{
LOG_INFO(LOG_FILTER_BINARY_PATCHING, "Patching CallSite %s",
to_string(call_site).c_str());
std::vector<BPatch_point *> patch_points;
auto instr_address = call_site.address;
std::vector<BPatch_point *> points;
object->findPoints(instr_address, points);
for (auto point : points)
patch_points.push_back(point);
auto label = label_builder.generate_label(call_site);
create_and_insert_snippet_callsite(image, patch_points, label, call_site.address,
patcher);
}
patcher.commit();
}
void patch_calltargets(BPatch_object *object, BPatch_image *image, CADecoder *decoder,
CallTargets call_targets, LabelBuilder const &label_builder)
{
std::vector<BPatch_point *> patch_points;
for (auto call_target : call_targets)
{
// if (!call_target.plt)
{
LOG_INFO(LOG_FILTER_BINARY_PATCHING, "Patching CallTarget %s",
to_string(call_target).c_str());
auto function = call_target.function;
function->annotateFunction(label_builder.generate_label(call_target));
}
}
}
std::unique_ptr<LabelBuilder> get_label_for_policy(PatchingPolicy policy,
TakenAddresses const &taken_addresses)
{
switch (policy)
{
case POLICY_ADDRESS_TAKEN:
return std::unique_ptr<LabelBuilder>(
new AddressTakenLabelBuilder(taken_addresses));
case POLICY_PARAM_COUNT:
return std::unique_ptr<LabelBuilder>(new ParamCountLabelBuilder(taken_addresses));
case POLICY_PARAM_COUNT_EXT:
return std::unique_ptr<LabelBuilder>(
new ParamCountRetLabelBuilder(taken_addresses));
case POLICY_PARAM_TYPE:
return std::unique_ptr<LabelBuilder>(new ParamTypeLabelBuilder(taken_addresses));
case POLICY_PARAM_TYPE_EXT:
return std::unique_ptr<LabelBuilder>(
new ParamTypeRetLabelBuilder(taken_addresses));
case POLICY_NONE:
default:
assert(false); // not implemented label
}
}
static std::vector<BPatch_basicBlock *> getEntryBasicBlocks(BPatch_function *function)
{
BPatch_flowGraph *cfg = function->getCFG();
std::vector<BPatch_basicBlock *> entry_blocks;
if (!cfg->getEntryBasicBlock(entry_blocks))
{
char funcname[BUFFER_STRING_LEN];
function->getName(funcname, BUFFER_STRING_LEN);
LOG_FATAL(LOG_FILTER_BINARY_PATCHING,
"Could not find entry blocks for function %s", funcname);
}
return entry_blocks;
}
void binary_patching(BPatch_object *object, BPatch_image *image, CADecoder *decoder,
CallTargets const &call_targets, CallSites const &call_sites,
TakenAddresses const &taken_addresses)
{
auto const is_system = [&]() {
std::vector<BPatch_module *> modules;
object->modules(modules);
if (modules.size() != 1)
return false;
return modules[0]->isSystemLib();
}();
// for now we do not want to touch system libraries !!
if (is_system)
return;
#if ENABLE_DEBUG_OUTPUT == 1
auto as = image->getAddressSpace();
as->loadLibrary("libc.so.6", true);
#endif
LOG_INFO(LOG_FILTER_BINARY_PATCHING, "Touching %s", object->pathName().c_str());
auto label_builder = get_label_for_policy(POLICY_ADDRESS_TAKEN, taken_addresses);
patch_callsites(object, image, decoder, call_sites, *label_builder);
patch_calltargets(object, image, decoder, call_targets, *label_builder);
}
| [
"dev.mor1bon@gmail.com"
] | dev.mor1bon@gmail.com |
080a2db68f4d93e80aa2b7561a8f9f0e84bd812a | a6b0a3a0f4fae5d7073af87314bbfaf1f5872690 | /include/instr/parsers/syscall_parser.hpp | e6c00aaa60c935f8ba9df9716bc9f0723741d738 | [
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jaller200/mips-simulator | f74e7db6b3c1339e9ef3fd3f7218d7777e519c1e | f2106f6acaf44a84b3cb305b7c8f345bf037efae | refs/heads/master | 2023-01-24T21:16:53.172652 | 2020-12-03T05:16:09 | 2020-12-03T05:16:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 988 | hpp | #pragma once
#include <string>
#include <vector>
#include "instr/instruction.hpp"
#include "instr/instruction_parser.hpp"
#include "types.hpp"
/**
* A parser for the SYSCALL (system call) instruction (opcode 0, funct 12).
*/
class SyscallParser: public InstructionParser {
public:
// MARK: -- Construction
SyscallParser() = default;
~SyscallParser() = default;
// MARK: -- Parse Methods
/**
* Parses a line with the SYSCALL (system call) instruction (opcode 0, funct 12)
*
* The format for this instruction is as follows:
*
* SYSCALL
*
* The type of syscall is stored in register $v0 (2).
*
* A syntax error will be thrown if any of the registers are invalid or
* out of bounds.
*
* @param line The line to parse
* @throw SyntaxError If there is a syntax error
* @return A vector with the instructions
*/
std::vector<Instruction> parse(const std::string& line) const;
}; | [
"jonathanhart3000@gmail.com"
] | jonathanhart3000@gmail.com |
59d32a9b64263686677d8ec5f11d4ed780683dd3 | 3748404daeafc106dc210044041bee09d6482359 | /src/engine/shared/datafile.h | eddce611495463894af4ce956964c58ca2adab60 | [
"Zlib",
"LicenseRef-scancode-other-permissive"
] | permissive | chi1/twmaps | 8981447eb07a40e19313e51ae0739f62fb670c37 | 5418317b4116b3ff66f3d589f99f4e774609e495 | refs/heads/master | 2021-01-18T09:18:53.822750 | 2010-09-05T14:02:05 | 2010-09-05T14:02:05 | 889,331 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | h | #ifndef ENGINE_SHARED_DATAFILE_H
#define ENGINE_SHARED_DATAFILE_H
// raw datafile access
class CDataFileReader
{
class CDatafile *m_pDataFile;
void *GetDataImpl(int Index, int Swap);
public:
CDataFileReader() : m_pDataFile(0) {}
~CDataFileReader() { Close(); }
bool IsOpen() const { return m_pDataFile != 0; }
bool Open(class IStorage *pStorage, const char *pFilename);
bool Close();
void *GetData(int Index);
void *GetDataSwapped(int Index); // makes sure that the data is 32bit LE ints when saved
int GetDataSize(int Index);
void UnloadData(int Index);
void *GetItem(int Index, int *pType, int *pId);
int GetItemSize(int Index);
void GetType(int Type, int *pStart, int *pNum);
void *FindItem(int Type, int Id);
int NumItems();
int NumData();
void Unload();
unsigned Crc();
};
// write access
class CDataFileWriter
{
struct CDataInfo
{
int m_UncompressedSize;
int m_CompressedSize;
void *m_pCompressedData;
} ;
struct CItemInfo
{
int m_Type;
int m_Id;
int m_Size;
int m_Next;
int m_Prev;
void *m_pData;
};
struct CItemTypeInfo
{
int m_Num;
int m_First;
int m_Last;
};
IOHANDLE m_File;
int m_NumItems;
int m_NumDatas;
int m_NumItemTypes;
CItemTypeInfo m_aItemTypes[0xffff];
CItemInfo m_aItems[1024];
CDataInfo m_aDatas[1024];
public:
bool Open(class IStorage *pStorage, const char *Filename);
int AddData(int Size, void *pData);
int AddDataSwapped(int Size, void *pData);
int AddItem(int Type, int Id, int Size, void *pData);
int Finish();
};
#endif
| [
"magnus.auvinen@gmail.com"
] | magnus.auvinen@gmail.com |
3e110b271695c0f259b857c2ef9ead5e9af551a5 | 77a893efca58e9668eea24b07a6d04a27b4e7662 | /game.cpp | e3da05371358c3187f85e67f11a3781ebce8b0d7 | [] | no_license | PixelRetroGames-org/Jump | 69573c9579adeb41f3986241ac93cc9891840d8b | 71ea05bbae3c29896224f3ba1b7553f3a7eab007 | refs/heads/master | 2021-01-10T16:01:20.173980 | 2016-02-09T10:03:59 | 2016-02-09T10:03:59 | 48,488,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #ifndef game_CPP
#define game_CPP
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"
#include "SDL/SDL_image.h"
#define MAX_LIN 720
#define MAX_COL 1280
#define LEVELL 100
#define LEVELC 100
#define GRIDL 40
#define GRIDC 1280
#include "game.h"
void BigScreen::initialize()
{
SDL_Init(SDL_INIT_EVERYTHING);
screen=SDL_SetVideoMode(MAX_COL,MAX_LIN,32,SDL_SWSURFACE);
SDL_WM_SetCaption("Jump!","PixelRetroGames");
TTF_Init();
}
#endif
| [
"pixelretrogames@github.com"
] | pixelretrogames@github.com |
9b36ec19d42c81b44564e2b2b7738d766a91d18d | 60597b6b2139312d73a6e087107f55f028d145e8 | /AdaBoostAlgorithm.h | f811fca00839cc245e9070ebfd121a9ce2f15cd3 | [] | no_license | MichalKonradSulek/PSZT2CPP | 7f1ebed28e84f08408a800502db8ae7a8d6b6589 | 5cfb73f9166418cef006b7fa69a296a82fcebd68 | refs/heads/master | 2020-12-21T22:51:16.677133 | 2020-01-30T12:23:41 | 2020-01-30T12:23:41 | 236,590,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | h | //
// Created by michalsulek on 29.01.2020.
//
#ifndef PSZT2_ADABOOSTALGORITHM_H
#define PSZT2_ADABOOSTALGORITHM_H
#include "Stump.h"
/** \file Stump.h
* Plik zawierający klasę z algorytmem AdaBoost.
*/
/** \class AdaBoostAlgorithm
* Klasa realizuje działanie algorytmu AdaBoost opartego na drzewach decyzyjnych o głębokości 1.
* Wybór drzew dokonywany jest na podstawie minimalizacji ważonych ilości błędnych decyzji. Każde kolejne krzewo tworzone jest
* z uwzględnieniem błędów popełnionych przez drzewo poprzednie. W tym celu każdemu przykładowi, wykorzystywanemu do
* trenowania algorytmu przypisywana jest waga, która jest zwiększana, gdy przykład został sklasyfikowany źle
* i zmniejszana, gdy został sklasyfikowany dobrze. Następnie, przy wyborze kolejnego drzewa, przypadki z większą
* wagą mają większy wpływ na jego kształt
*/
class AdaBoostAlgorithm {
private:
StumpCreator createStump(const Samples& samples, const std::vector<double>& weightsOfSamples) const; ///<metoda tworząca kolejne drzewo decyzyjne, zwracająca kreatora tego drzewa. Drzewo jest tworzone w następujący sposób: dla każdej cechy tworzone jest drzewo, a następnie wybierane takie o najmniejszym współczynniku Giniego
double calculateAmountOfSay(const std::vector<double>& weightsOfSamples, const std::vector<bool>& tableOfCorrectClassification) const; ///<metoda licząca wpływ drzewa na ostateczną decyzję algorytmu (wagę drzewa), na podstawie ilości podejmowanych poprawnych decyzji
void recalculateWeights(std::vector<double>& weightsOfSamples, const std::vector<bool>& tableOfCorrectClassification, double amountOfSay) const; ///<metoda aktualizując wagi przykładów
void normalizeWeights(std::vector<double>& weightsOfSamples) const; ///<metoda ormalizująca wagi przykładów tak, by ich suma była równa 1
std::vector<DecisionStump> stumps_; ///<drzewa decyzyjne
std::vector<double> amountOfSay_; ///<wagi drzew
double dividingValueOfPredictedAttribute_ = 0; ///<zmienna przechhowująca liczbę, dzielącą szukaną cechę na dwie klasy
public:
void trainAlgorithm(const Samples& samples, size_t numberOfStumps, double dividingValueOfPredictedAttribute); ///<metoda trenująca algorytm
double prediction(const RecordWithoutResult& record) const; ///<metoda zwracająca predykcję algorytmu
};
#endif //PSZT2_ADABOOSTALGORITHM_H
| [
"michal2sulek@gmail.com"
] | michal2sulek@gmail.com |
a22f6944ff80858c779193e194b633c6b7260ced | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/CompositeExtentBasedOn/UNIX_CompositeExtentBasedOn_VMS.hxx | 0b336a3ea5c964ea79bf1e2d148b6cfc33c00e88 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_VMS
#ifndef __UNIX_COMPOSITEEXTENTBASEDON_PRIVATE_H
#define __UNIX_COMPOSITEEXTENTBASEDON_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
9e892542d47ace4c8bd414ec1eba46277fd4105f | 89b399a7d553d115612850e9eaa81904677730db | /pinghengche/bsp_SysTick.cpp | e5f5bba0165363d7a7147131511619eba13a7a32 | [] | no_license | CVQ1/self-balance-vehicle | 858223bae87ed5b9fcd8c06f151e9917edb01f6d | 73884b35c18e077117058cf6e1023cfb3088cb05 | refs/heads/master | 2020-03-09T01:19:47.199820 | 2018-04-07T08:51:49 | 2018-04-07T08:51:49 | 128,511,377 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,548 | cpp | /**
******************************************************************************
* @file bsp_SysTick.c
* @author fire
* @version V1.0
* @date 2013-xx-xx
* @brief SysTick 系统滴答时钟10us中断函数库,中断时间可自由配置,
* 常用的有 1us 10us 1ms 中断。
******************************************************************************
* @attention
*
* 实验平台:野火 iSO STM32 开发板
* 论坛 :http://www.firebbs.cn
* 淘宝 :https://fire-stm32.taobao.com
*
******************************************************************************
*/
//SysTick_Config主要用来配置中端向量,重置STK_VAL寄存器,配置SysTick时钟为AHB
#include "bsp_SysTick.h"
/**
* @brief 启动系统滴答定时器 SysTick
* @param 无
* @retval 无
*/
void SysTick_Init(void)
{
/* SystemFrequency / 1000 1ms中断一次
* SystemFrequency / 100000 10us中断一次
* SystemFrequency / 1000000 1us中断一次
*/
// if (SysTick_Config(SystemFrequency / 100000)) // ST3.0.0库版本
if (SysTick_Config(SystemCoreClock/1000)) // ST3.5.0库版本SystemCoreClock/10不能超过16777216
{
/* Capture error */
while (1);
}
// 关闭滴答定时器
SysTick->CTRL &= ~ SysTick_CTRL_ENABLE_Msk;
}
//void SysTick_Handler(void)
//{
// unsigned char i;
// for (i = 0; i < NumOfTask; i++)
// {
// if (Task_Delay[i])
// {
// Task_Delay[i]--;
// }
// }
//}
/*********************************************END OF FILE**********************/
| [
"32217689+CVQ1@users.noreply.github.com"
] | 32217689+CVQ1@users.noreply.github.com |
da54fcefff2846ecc20fbc475737b6f2cf8b194f | c6a98b8e273e69533009e5073a505508e3a0c2c5 | /Problems/SPOJ/QTREE2.cpp | 71586a0b47358126c366514a7c0c5eccef709c58 | [] | no_license | BenjaminRubio/CompetitiveProgramming | 5c72a9b803e66e194fd7fe8a26d0d81d14a7fc5c | 33ba1125a2eb5ba4d6f9cbc8522c92432bc92b0d | refs/heads/master | 2023-06-08T19:43:44.069793 | 2023-05-27T18:53:32 | 2023-05-27T18:53:32 | 176,643,093 | 16 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,151 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)n; i++)
#define ff first
#define ss second
int T, N, u, v, w, k;
vector<vector<pair<int, int>>> G;
string s;
struct LCA
{
int n, maxe;
vector<int> A, D, DD;
int& anc(int u, int e) { return A[e * n + u]; }
void dfs(int u, int p, int dist, int depth)
{
anc(u,0) = p;
D[u] = depth; DD[u] = dist;
for (auto &e : G[u]) if (D[e.ff] == -1) dfs(e.ff, u, dist + e.ss, depth + 1);
}
LCA(int root)
{
n = G.size();
maxe = 31 - __builtin_clz(n);
D.assign(n, -1); DD.assign(n, -1);
A.resize(n * (maxe + 1));
dfs(root, -1, 0, 0);
rep(e, maxe) rep(u, n)
{
int a = anc(u, e);
anc(u, e + 1) = (a == -1 ? -1 : anc(a, e));
}
}
int raise(int u, int k)
{
for (int e = 0; k; e++, k >>= 1) if (k & 1) u = anc(u, e);
return u;
}
int lca(int u, int v)
{
if (D[u] < D[v]) swap(u, v);
u = raise(u, D[u] - D[v]);
if (u == v) return u;
for (int e = maxe; e >= 0; e--) if (anc(u, e) != anc(v, e))
u = anc(u, e), v = anc(v, e);
return anc(u, 0);
}
int dist(int u, int v) { return DD[u] + DD[v] - 2 * DD[lca(u, v)]; }
int nodes(int u, int v) { return D[u] + D[v] - 2 * D[lca(u, v)]; }
int kth_in_path(int u, int v, int k)
{
int l = lca(u, v);
if (D[u] - D[l] >= k) return raise(u, k);
return raise(v, nodes(u, v) - k);
}
};
int main()
{
cin >> T;
while (T--)
{
cin >> N;
G.assign(N, {});
rep(i, N - 1)
{
cin >> u >> v >> w; u--, v--;
G[u].emplace_back(v, w), G[v].emplace_back(u, w);
}
LCA lca(0);
while (cin >> s && s != "DONE")
{
cin >> u >> v; u--, v--;
if (s == "DIST") cout << lca.dist(u, v) << '\n';
if (s == "KTH")
{
cin >> k;
cout << lca.kth_in_path(u, v, k - 1) + 1 << '\n';
}
}
}
} | [
"berubio@uc.cl"
] | berubio@uc.cl |
a7bcc51dec5c3117802b15caffd10d6428e2d31c | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /v8_7_5/src/profiler/tick-sample.cc | dca3e2d04504bf0bda47522c2af7e006d6e70f2c | [
"Apache-2.0",
"bzip2-1.0.6",
"BSD-3-Clause",
"SunPro"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 11,975 | cc | // Copyright 2013 the V8 project 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 "src/profiler/tick-sample.h"
#include "include/v8-profiler.h"
#include "src/asan.h"
#include "src/counters.h"
#include "src/frames-inl.h"
#include "src/heap/heap-inl.h" // For MemoryAllocator::code_range.
#include "src/msan.h"
#include "src/simulator.h"
#include "src/vm-state-inl.h"
namespace v8 {
namespace {
bool IsSamePage(i::Address ptr1, i::Address ptr2) {
const uint32_t kPageSize = 4096;
i::Address mask = ~static_cast<i::Address>(kPageSize - 1);
return (ptr1 & mask) == (ptr2 & mask);
}
// Check if the code at specified address could potentially be a
// frame setup code.
bool IsNoFrameRegion(i::Address address) {
struct Pattern {
int bytes_count;
i::byte bytes[8];
int offsets[4];
};
static Pattern patterns[] = {
#if V8_HOST_ARCH_IA32
// push %ebp
// mov %esp,%ebp
{3, {0x55, 0x89, 0xE5}, {0, 1, -1}},
// pop %ebp
// ret N
{2, {0x5D, 0xC2}, {0, 1, -1}},
// pop %ebp
// ret
{2, {0x5D, 0xC3}, {0, 1, -1}},
#elif V8_HOST_ARCH_X64
// pushq %rbp
// movq %rsp,%rbp
{4, {0x55, 0x48, 0x89, 0xE5}, {0, 1, -1}},
// popq %rbp
// ret N
{2, {0x5D, 0xC2}, {0, 1, -1}},
// popq %rbp
// ret
{2, {0x5D, 0xC3}, {0, 1, -1}},
#endif
{0, {}, {}}
};
i::byte* pc = reinterpret_cast<i::byte*>(address);
for (Pattern* pattern = patterns; pattern->bytes_count; ++pattern) {
for (int* offset_ptr = pattern->offsets; *offset_ptr != -1; ++offset_ptr) {
int offset = *offset_ptr;
if (!offset || IsSamePage(address, address - offset)) {
MSAN_MEMORY_IS_INITIALIZED(pc - offset, pattern->bytes_count);
if (!memcmp(pc - offset, pattern->bytes, pattern->bytes_count))
return true;
} else {
// It is not safe to examine bytes on another page as it might not be
// allocated thus causing a SEGFAULT.
// Check the pattern part that's on the same page and
// pessimistically assume it could be the entire pattern match.
MSAN_MEMORY_IS_INITIALIZED(pc, pattern->bytes_count - offset);
if (!memcmp(pc, pattern->bytes + offset, pattern->bytes_count - offset))
return true;
}
}
}
return false;
}
} // namespace
namespace internal {
namespace {
#if defined(USE_SIMULATOR)
class SimulatorHelper {
public:
// Returns true if register values were successfully retrieved
// from the simulator, otherwise returns false.
static bool FillRegisters(Isolate* isolate, v8::RegisterState* state);
};
bool SimulatorHelper::FillRegisters(Isolate* isolate,
v8::RegisterState* state) {
Simulator* simulator = isolate->thread_local_top()->simulator_;
// Check if there is active simulator.
if (simulator == nullptr) return false;
#if V8_TARGET_ARCH_ARM
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::r11));
#elif V8_TARGET_ARCH_ARM64
state->pc = reinterpret_cast<void*>(simulator->pc());
state->sp = reinterpret_cast<void*>(simulator->sp());
state->fp = reinterpret_cast<void*>(simulator->fp());
#elif V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#elif V8_TARGET_ARCH_PPC
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#elif V8_TARGET_ARCH_S390
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#endif
if (state->sp == 0 || state->fp == 0) {
// It possible that the simulator is interrupted while it is updating
// the sp or fp register. ARM64 simulator does this in two steps:
// first setting it to zero and then setting it to the new value.
// Bailout if sp/fp doesn't contain the new value.
//
// FIXME: The above doesn't really solve the issue.
// If a 64-bit target is executed on a 32-bit host even the final
// write is non-atomic, so it might obtain a half of the result.
// Moreover as long as the register set code uses memcpy (as of now),
// it is not guaranteed to be atomic even when both host and target
// are of same bitness.
return false;
}
return true;
}
#endif // USE_SIMULATOR
} // namespace
} // namespace internal
//
// StackTracer implementation
//
DISABLE_ASAN void TickSample::Init(Isolate* v8_isolate,
const RegisterState& reg_state,
RecordCEntryFrame record_c_entry_frame,
bool update_stats,
bool use_simulator_reg_state) {
this->update_stats = update_stats;
SampleInfo info;
RegisterState regs = reg_state;
if (!GetStackSample(v8_isolate, ®s, record_c_entry_frame, stack,
kMaxFramesCount, &info, use_simulator_reg_state)) {
// It is executing JS but failed to collect a stack trace.
// Mark the sample as spoiled.
pc = nullptr;
return;
}
state = info.vm_state;
pc = regs.pc;
frames_count = static_cast<unsigned>(info.frames_count);
has_external_callback = info.external_callback_entry != nullptr;
if (has_external_callback) {
external_callback_entry = info.external_callback_entry;
} else if (frames_count) {
// sp register may point at an arbitrary place in memory, make
// sure sanitizers don't complain about it.
ASAN_UNPOISON_MEMORY_REGION(regs.sp, sizeof(void*));
MSAN_MEMORY_IS_INITIALIZED(regs.sp, sizeof(void*));
// Sample potential return address value for frameless invocation of
// stubs (we'll figure out later, if this value makes sense).
// TODO(petermarshall): This read causes guard page violations on Windows.
// Either fix this mechanism for frameless stubs or remove it.
// tos =
// i::ReadUnalignedValue<void*>(reinterpret_cast<i::Address>(regs.sp));
tos = nullptr;
} else {
tos = nullptr;
}
}
bool TickSample::GetStackSample(Isolate* v8_isolate, RegisterState* regs,
RecordCEntryFrame record_c_entry_frame,
void** frames, size_t frames_limit,
v8::SampleInfo* sample_info,
bool use_simulator_reg_state) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
sample_info->frames_count = 0;
sample_info->vm_state = isolate->current_vm_state();
sample_info->external_callback_entry = nullptr;
if (sample_info->vm_state == GC) return true;
i::Address js_entry_sp = isolate->js_entry_sp();
if (js_entry_sp == 0) return true; // Not executing JS now.
#if defined(USE_SIMULATOR)
if (use_simulator_reg_state) {
if (!i::SimulatorHelper::FillRegisters(isolate, regs)) return false;
}
#else
USE(use_simulator_reg_state);
#endif
DCHECK(regs->sp);
// Check whether we interrupted setup/teardown of a stack frame in JS code.
// Avoid this check for C++ code, as that would trigger false positives.
if (regs->pc &&
isolate->heap()->memory_allocator()->code_range().contains(
reinterpret_cast<i::Address>(regs->pc)) &&
IsNoFrameRegion(reinterpret_cast<i::Address>(regs->pc))) {
// The frame is not setup, so it'd be hard to iterate the stack. Bailout.
return false;
}
i::ExternalCallbackScope* scope = isolate->external_callback_scope();
i::Address handler = i::Isolate::handler(isolate->thread_local_top());
// If there is a handler on top of the external callback scope then
// we have already entrered JavaScript again and the external callback
// is not the top function.
if (scope && scope->scope_address() < handler) {
i::Address* external_callback_entry_ptr =
scope->callback_entrypoint_address();
sample_info->external_callback_entry =
external_callback_entry_ptr == nullptr
? nullptr
: reinterpret_cast<void*>(*external_callback_entry_ptr);
}
i::SafeStackFrameIterator it(isolate, reinterpret_cast<i::Address>(regs->fp),
reinterpret_cast<i::Address>(regs->sp),
js_entry_sp);
if (it.done()) return true;
size_t i = 0;
if (record_c_entry_frame == kIncludeCEntryFrame &&
(it.top_frame_type() == internal::StackFrame::EXIT ||
it.top_frame_type() == internal::StackFrame::BUILTIN_EXIT)) {
frames[i++] = reinterpret_cast<void*>(isolate->c_function());
}
i::RuntimeCallTimer* timer =
isolate->counters()->runtime_call_stats()->current_timer();
for (; !it.done() && i < frames_limit; it.Advance()) {
while (timer && reinterpret_cast<i::Address>(timer) < it.frame()->fp() &&
i < frames_limit) {
frames[i++] = reinterpret_cast<void*>(timer->counter());
timer = timer->parent();
}
if (i == frames_limit) break;
if (it.frame()->is_interpreted()) {
// For interpreted frames use the bytecode array pointer as the pc.
i::InterpretedFrame* frame =
static_cast<i::InterpretedFrame*>(it.frame());
// Since the sampler can interrupt execution at any point the
// bytecode_array might be garbage, so don't actually dereference it. We
// avoid the frame->GetXXX functions since they call BytecodeArray::cast,
// which has a heap access in its DCHECK.
i::Address bytecode_array = i::Memory<i::Address>(
frame->fp() + i::InterpreterFrameConstants::kBytecodeArrayFromFp);
i::Address bytecode_offset = i::Memory<i::Address>(
frame->fp() + i::InterpreterFrameConstants::kBytecodeOffsetFromFp);
// If the bytecode array is a heap object and the bytecode offset is a
// Smi, use those, otherwise fall back to using the frame's pc.
if (HAS_HEAP_OBJECT_TAG(bytecode_array) && HAS_SMI_TAG(bytecode_offset)) {
frames[i++] = reinterpret_cast<void*>(
bytecode_array + i::Internals::SmiValue(bytecode_offset));
continue;
}
}
frames[i++] = reinterpret_cast<void*>(it.frame()->pc());
}
sample_info->frames_count = i;
return true;
}
namespace internal {
void TickSample::Init(Isolate* isolate, const v8::RegisterState& state,
RecordCEntryFrame record_c_entry_frame, bool update_stats,
bool use_simulator_reg_state) {
v8::TickSample::Init(reinterpret_cast<v8::Isolate*>(isolate), state,
record_c_entry_frame, update_stats,
use_simulator_reg_state);
if (pc == nullptr) return;
timestamp = base::TimeTicks::HighResolutionNow();
}
void TickSample::print() const {
PrintF("TickSample: at %p\n", this);
PrintF(" - state: %s\n", StateToString(state));
PrintF(" - pc: %p\n", pc);
PrintF(" - stack: (%u frames)\n", frames_count);
for (unsigned i = 0; i < frames_count; i++) {
PrintF(" %p\n", stack[i]);
}
PrintF(" - has_external_callback: %d\n", has_external_callback);
PrintF(" - %s: %p\n",
has_external_callback ? "external_callback_entry" : "tos", tos);
PrintF(" - update_stats: %d\n", update_stats);
PrintF("\n");
}
} // namespace internal
} // namespace v8
| [
"22249030@qq.com"
] | 22249030@qq.com |
aad0ff918ac02b691097b57364359b4f417d45c0 | cd416734b3ed2ce14e28bb342b8ddf3cad992f74 | /tests/oeedger8r/host/teststring.cpp | 7e15c755a20cddc43b69ba7872bc301e0d91e07c | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | kernullist/openenclave | 261b030ce36dde3cc065e45a58ad49e3a472f81f | c7c3edf41e7fcbfd6528a36eb0e06b4257979679 | refs/heads/master | 2020-03-31T20:19:28.489012 | 2018-10-11T00:39:41 | 2018-10-11T00:39:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,868 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "../edltestutils.h"
#include <openenclave/host.h>
#include <openenclave/internal/tests.h>
#include <wchar.h>
#include "string_u.c"
void test_string_edl_ecalls(oe_enclave_t* enclave)
{
const char* str_value = "Hello, World\n";
char str[50];
sprintf(str, "%s", str_value);
// char*
OE_TEST(ecall_string_fun1(enclave, str) == OE_OK);
OE_TEST(strcmp(str, str_value) == 0);
// const char*. (char* is passed in)
OE_TEST(ecall_string_fun2(enclave, str) == OE_OK);
OE_TEST(strcmp(str, str_value) == 0);
// char* in/out
OE_TEST(ecall_string_fun3(enclave, str) == OE_OK);
OE_TEST(strcmp(str, "Goodbye\n") == 0);
// Restore value.
sprintf(str, "%s", str_value);
// char* user check.
OE_TEST(ecall_string_fun5(enclave, str) == OE_OK);
OE_TEST(strcmp(str, "Hello") == 0);
// char* user check.
OE_TEST(ecall_string_fun6(enclave, str) == OE_OK);
OE_TEST(strcmp(str, "Hello") == 0);
// Multiple string params. One null.
OE_TEST(ecall_string_fun7(enclave, str, NULL) == OE_OK);
printf("=== test_string_edl_ecalls passed\n");
}
void ocall_string_fun1(char* s)
{
ocall_string_fun1_args_t args;
check_type<char*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(strcmp(s, "Hello, World\n") == 0);
}
void ocall_string_fun2(const char* s)
{
ocall_string_fun2_args_t args;
// constness is discarded when marshaling.
check_type<char*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(strcmp(s, "Hello, World\n") == 0);
}
void ocall_string_fun3(char* s)
{
ocall_string_fun3_args_t args;
check_type<char*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(strcmp(s, "Hello, World\n") == 0);
// Write to s. Check on enclave side for new value.
const char* new_s = "Goodbye\n";
memcpy(s, new_s, strlen(new_s) + 1);
}
void ocall_string_fun5(char* s)
{
ocall_string_fun5_args_t args;
check_type<char*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_string_fun5_args_t>();
// Change value to Hello.
s[5] = '\0';
}
void ocall_string_fun6(const char* s)
{
ocall_string_fun6_args_t args;
// constness is discarded when marshaling.
check_type<char*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_string_fun6_args_t>();
}
void ocall_string_fun7(char* s1, char* s2)
{
ocall_string_fun7_args_t args;
check_type<char*>(args.s1);
check_type<size_t>(args.s1_len);
check_type<char*>(args.s2);
check_type<size_t>(args.s2_len);
OE_TEST(s1 != NULL);
OE_TEST(s2 == NULL);
}
void test_wstring_edl_ecalls(oe_enclave_t* enclave)
{
const wchar_t* str_value = L"Hello, World\n";
wchar_t str[50];
swprintf(str, 50, L"%S", str_value);
// wchar_t*
OE_TEST(ecall_wstring_fun1(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, str_value) == 0);
// const wchar_t*. (wchar_t* is passed in)
OE_TEST(ecall_wstring_fun2(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, str_value) == 0);
// wchar_t* in/out
OE_TEST(ecall_wstring_fun3(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, L"Goodbye\n") == 0);
// Restore value.
swprintf(str, 50, L"%S", str_value);
// wchar_t* user check.
OE_TEST(ecall_wstring_fun5(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, L"Hello") == 0);
// wchar_t* user check.
OE_TEST(ecall_wstring_fun6(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, L"Hello") == 0);
// Multiple wstring params. One null.
OE_TEST(ecall_wstring_fun7(enclave, str, NULL) == OE_OK);
printf("=== test_string_edl_ecalls passed\n");
}
void ocall_wstring_fun1(wchar_t* s)
{
ocall_wstring_fun1_args_t args;
check_type<wchar_t*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(wcscmp(s, L"Hello, World\n") == 0);
}
void ocall_wstring_fun2(const wchar_t* s)
{
ocall_wstring_fun2_args_t args;
// constness is discarded when marshaling.
check_type<wchar_t*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(wcscmp(s, L"Hello, World\n") == 0);
}
void ocall_wstring_fun3(wchar_t* s)
{
ocall_wstring_fun3_args_t args;
check_type<wchar_t*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(wcscmp(s, L"Hello, World\n") == 0);
// Write to s. Check on enclave side for new value.
const wchar_t* new_s = L"Goodbye\n";
memcpy(s, new_s, (wcslen(new_s) + 1) * sizeof(wchar_t));
}
void ocall_wstring_fun5(wchar_t* s)
{
ocall_wstring_fun5_args_t args;
check_type<wchar_t*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_wstring_fun5_args_t>();
// Change value to Hello.
s[5] = L'\0';
}
void ocall_wstring_fun6(const wchar_t* s)
{
ocall_wstring_fun6_args_t args;
// constness is discarded when marshaling.
check_type<wchar_t*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_wstring_fun6_args_t>();
}
void ocall_wstring_fun7(wchar_t* s1, wchar_t* s2)
{
ocall_wstring_fun7_args_t args;
check_type<wchar_t*>(args.s1);
check_type<size_t>(args.s1_len);
check_type<wchar_t*>(args.s2);
check_type<size_t>(args.s2_len);
OE_TEST(s1 != NULL);
OE_TEST(s2 == NULL);
}
| [
"anakrish@microsoft.com"
] | anakrish@microsoft.com |
fcc1ba4a88f5d5c2b10ab1b1bfe859d95a76a3e4 | dd629803899abbb8b6d8b4503b3591bb7eae6e73 | /include/forge/imaging/hio/types.h | 1a0fead3334f84b80357918df1b8ffa3e0c88074 | [] | no_license | furby-tm/Winggverse | 8d78bb691d2e5eecc5197845e9cbfb98f45c58bd | 0dc9db7057f52fca3e52e73491e24f298d108106 | refs/heads/main | 2023-04-21T17:32:20.350636 | 2021-04-30T04:24:30 | 2021-04-30T04:24:30 | 362,732,238 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,597 | h | #line 1 "C:/Users/tyler/dev/WINGG/forge/imaging/hio/types.h"
/*
* Copyright 2021 Forge. All Rights Reserved.
*
* The use of this software is subject to the terms of the
* Forge license agreement provided at the time of installation
* or download, or which otherwise accompanies this software in
* either electronic or hard copy form.
*
* Portions of this file are derived from original work by Pixar
* distributed with Universal Scene Description, a project of the
* Academy Software Foundation (ASWF). https://www.aswf.io/
*
* Original Copyright (C) 2016-2021 Pixar.
* Modifications copyright (C) 2020-2021 ForgeXYZ LLC.
*
* Forge. The Animation Software & Motion Picture Co.
*/
#ifndef FORGE_IMAGING_HIO_TYPES_H
#define FORGE_IMAGING_HIO_TYPES_H
#include "forge/forge.h"
#include "forge/imaging/hio/api.h"
#include <stdlib.h>
#include <cinttypes>
FORGE_NAMESPACE_BEGIN
class GfVec3i;
/// \enum HioFormat
///
/// HioFormat describes the memory format of image buffers used in Hio.
///
/// For reference, see:
/// https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#VkFormat
enum HioFormat
{
HioFormatInvalid=-1,
// UNorm8 - a 1-byte value representing a float between 0 and 1.
// float value = (unorm / 255.0f);
HioFormatUNorm8=0,
HioFormatUNorm8Vec2,
HioFormatUNorm8Vec3,
HioFormatUNorm8Vec4,
// SNorm8 - a 1-byte value representing a float between -1 and 1.
// float value = max(snorm / 127.0f, -1.0f);
HioFormatSNorm8,
HioFormatSNorm8Vec2,
HioFormatSNorm8Vec3,
HioFormatSNorm8Vec4,
// Float16 - a 2-byte IEEE half-precision float.
HioFormatFloat16,
HioFormatFloat16Vec2,
HioFormatFloat16Vec3,
HioFormatFloat16Vec4,
// Float32 - a 4-byte IEEE float.
HioFormatFloat32,
HioFormatFloat32Vec2,
HioFormatFloat32Vec3,
HioFormatFloat32Vec4,
// Double64 - a 8-byte IEEE double.
HioFormatDouble64,
HioFormatDouble64Vec2,
HioFormatDouble64Vec3,
HioFormatDouble64Vec4,
// UInt16 - a 2-byte unsigned short integer.
HioFormatUInt16,
HioFormatUInt16Vec2,
HioFormatUInt16Vec3,
HioFormatUInt16Vec4,
// Int16 - a 2-byte signed short integer.
HioFormatInt16,
HioFormatInt16Vec2,
HioFormatInt16Vec3,
HioFormatInt16Vec4,
// UInt32 - a 4-byte unsigned integer.
HioFormatUInt32,
HioFormatUInt32Vec2,
HioFormatUInt32Vec3,
HioFormatUInt32Vec4,
// Int32 - a 4-byte signed integer.
HioFormatInt32,
HioFormatInt32Vec2,
HioFormatInt32Vec3,
HioFormatInt32Vec4,
// UNorm8 SRGB - a 1-byte value representing a float between 0 and 1.
HioFormatUNorm8srgb,
HioFormatUNorm8Vec2srgb,
HioFormatUNorm8Vec3srgb,
HioFormatUNorm8Vec4srgb,
// BPTC compressed. 3-component, 4x4 blocks, signed floating-point
HioFormatBC6FloatVec3,
// BPTC compressed. 3-component, 4x4 blocks, unsigned floating-point
HioFormatBC6UFloatVec3,
// BPTC compressed. 4-component, 4x4 blocks, unsigned byte.
// Representing a float between 0 and 1.
HioFormatBC7UNorm8Vec4,
// BPTC compressed. 4-component, 4x4 blocks, unsigned byte, sRGB.
// Representing a float between 0 and 1.
HioFormatBC7UNorm8Vec4srgb,
// S3TC/DXT compressed. 4-component, 4x4 blocks, unsigned byte
// Representing a float between 0 and 1.
HioFormatBC1UNorm8Vec4,
// S3TC/DXT compressed. 4-component, 4x4 blocks, unsigned byte
// Representing a float between 0 and 1.
HioFormatBC3UNorm8Vec4,
HioFormatCount
};
/// \enum HioAddressDimension
///
/// Available texture sampling dimensions.
///
enum HioAddressDimension
{
HioAddressDimensionU,
HioAddressDimensionV,
HioAddressDimensionW
};
/// \enum HioAddressMode
///
/// Various modes used during sampling of a texture.
///
enum HioAddressMode
{
HioAddressModeClampToEdge = 0,
HioAddressModeMirrorClampToEdge,
HioAddressModeRepeat,
HioAddressModeMirrorRepeat,
HioAddressModeClampToBorderColor
};
/// \enum HioColorChannelType
///
/// Various color channel representation formats.
///
enum HioType
{
HioTypeUnsignedByte,
HioTypeUnsignedByteSRGB,
HioTypeSignedByte,
HioTypeUnsignedShort,
HioTypeSignedShort,
HioTypeUnsignedInt,
HioTypeInt,
HioTypeHalfFloat,
HioTypeFloat,
HioTypeDouble,
HioTypeCount
};
/// Returns the HioFormat of containing nChannels of HioType type.
HIO_API
HioFormat HioGetFormat(uint32_t nchannels,
HioType type,
bool isSRGB);
/// Return the HioType corresponding to the given HioFormat
HIO_API
HioType HioGetHioType(HioFormat);
/// Return the count of components (channels) in the given HioFormat.
HIO_API
int HioGetComponentCount(HioFormat format);
/// Return the size in bytes for a component (channel) in the given HioFormat.
HIO_API
size_t HioGetDataSizeOfType(HioFormat hioFormat);
/// Return the size in bytes for a component (channel) in the given HioType.
HIO_API
size_t HioGetDataSizeOfType(HioType type);
/// Returns the size of bytes per pixel for the given HioFormat
HIO_API
size_t HioGetDataSizeOfFormat(HioFormat format,
size_t *blockWidth = nullptr,
size_t *blockHeight = nullptr);
/// Return if the given format is compressed.
HIO_API
bool HioIsCompressed(HioFormat format);
/// Calculate the byte size of texture. If compressed, takes block size
/// into account.
HIO_API
size_t HioGetDataSize(const HioFormat hioFormat, const GfVec3i &dimensions);
FORGE_NAMESPACE_END
#endif
| [
"tyler@tylerfurby.com"
] | tyler@tylerfurby.com |
e44f11158a8db2ee8bd163f32a6ad20479c3c83a | e7babe1b4a743eac59ca64c581cec584498fd652 | /chap.4-10/sample11.cpp | 10ef8a03312490dfadcf6979053bed7954ffbdb2 | [] | no_license | originalhumanbeing/cpp_basic | e66f3d03657f7e3c7dffa05ed1db156b7ae543a9 | ca84f40732d6fea9d472ae78433c562ca6e5bfb5 | refs/heads/master | 2020-05-29T08:54:20.945068 | 2016-09-30T12:59:46 | 2016-09-30T12:59:46 | 69,268,897 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 191 | cpp | #include <iostream>
using namespace std;
int main()
{
int num1=5;
int num2=4;
double div;
div=(double)num1/(double)num2;
cout << "5/4´Â " << div << "ÀÔ´Ï´Ù. \n";
return 0;
} | [
"han.hyunjung17@gmail.com"
] | han.hyunjung17@gmail.com |
c25c26e4a8b39df8d596953f37f0c58e2b196734 | 2297fdd397a5a4571cd8272263b6cafbb1cd4b8b | /Contributor Corner/Himanshi/RomanToInteger.cpp | a25820e6edbbf8e704a9e8ba0ebd16bae686e7b1 | [
"MIT"
] | permissive | Ayonijakaushik19/Algorithmic-Treasure-Original | b331c2499a37f95d751b4803930a68e6b6ac286a | ae299d6188ee75439d140a354828164c416d6e21 | refs/heads/master | 2023-02-12T20:46:59.616385 | 2021-01-17T14:32:03 | 2021-01-17T14:32:03 | 385,998,572 | 2 | 0 | MIT | 2021-07-14T16:04:56 | 2021-07-14T16:04:55 | null | UTF-8 | C++ | false | false | 1,080 | cpp | //Question Link
//https://practice.geeksforgeeks.org/problems/roman-number-to-integer/0
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int value(char c)
{
if(c == 'I')
return 1;
else if(c == 'V')
return 5;
else if(c == 'X')
return 10;
else if(c == 'L')
return 50;
else if(c == 'C')
return 100;
else if(c == 'D')
return 500;
else if(c == 'M')
return 1000;
else
return -1;
}
int getRoman(string s)
{
int n = s.length();
int r = 0, x, y;
for(int i=0; i<n; i++)
{
if(i == n-1)
{
x = value(s[i]);
r += x;
return r;
}
else
{
x = value(s[i]);
y = value(s[i+1]);
if(x >= y)
r += x;
else
r -= x;
}
}
}
int main()
{
int t;
cin >> t;
while(t--)
{
string s;
cin >> s;
cout << getRoman(s) << endl;
}
return 0;
}
| [
"abhijittripathy99@gmail.com"
] | abhijittripathy99@gmail.com |
fca4e54a36ddb510133087c3cc89ca8cedb84eae | c14dc51c2ca9095d5c2281cef66fb52e89e2ed37 | /Inc/Instruction.h | a7a1d342c37b6cec471891998ca99a9406dd769d | [] | no_license | houssemba/M1If12-Compilation | 01aba3f43ca6b477f88f6df700c9105dd226fe06 | d9aa362ea6071591daa6c8bcbb16471f01c65ecd | refs/heads/master | 2020-05-17T23:03:20.960996 | 2013-06-27T13:48:25 | 2013-06-27T13:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | h | #ifndef __INSTRUCTION_H
#define __INSTRUCTION_H
#include "Code3ad.hpp"
#include "Operande.hpp"
class Instruction
{
private:
int etiquetteIdent;
bool _hasEtiquette;
CodeInstruction operation;
Operande oRes;
Operande o1;
Operande o2;
public:
Instruction(CodeInstruction operation, Operande oRes, Operande o1, Operande o2);// sans etiquette
Instruction(CodeInstruction operation, Operande oRes, Operande o1, Operande o2, int etiquette); // avec etiquette
void printToStd();
};
#endif
| [
"houssem@belhadjahmed.com"
] | houssem@belhadjahmed.com |
0d578ce304d99810003a29463e2cf74917a90177 | b8d116c857b13991366b58674a4dd1a96412b5bf | /src/materialsystem/stdshaders/BlurFilterX.cpp | 6962cc7f0d49686008966842692ef80c4b406e13 | [
"MIT"
] | permissive | SCell555/hl2-asw-port | 6eaa2a4f1f68f1dfb603657d469c42c85b2d9d1a | 16441f599c6b2d3fd051ee2805cc08680dedbb03 | refs/heads/master | 2021-01-17T18:21:59.547507 | 2016-05-12T17:09:21 | 2016-05-12T17:09:21 | 49,386,904 | 3 | 1 | null | 2016-01-10T21:45:46 | 2016-01-10T21:45:44 | null | WINDOWS-1252 | C++ | false | false | 3,104 | cpp | //===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "BaseVSShader.h"
#include "blurfilter_vs20.inc"
#include "blurfilter_ps20b.inc"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_VS_SHADER_FLAGS( BlurFilterX, "Help for BlurFilterX", SHADER_NOT_EDITABLE )
BEGIN_SHADER_PARAMS
SHADER_PARAM( KERNEL, SHADER_PARAM_TYPE_INTEGER, "0", "Kernel type" )
END_SHADER_PARAMS
SHADER_INIT
{
if( params[BASETEXTURE]->IsDefined() )
{
LoadTexture( BASETEXTURE );
}
if ( !( params[ KERNEL ]->IsDefined() ) )
{
params[ KERNEL ]->SetIntValue( 0 );
}
}
SHADER_FALLBACK
{
return 0;
}
SHADER_DRAW
{
SHADOW_STATE
{
pShaderShadow->EnableDepthWrites( false );
pShaderShadow->EnableAlphaWrites( true );
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->VertexShaderVertexFormat( VERTEX_POSITION, 1, 0, 0 );
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, false );
pShaderShadow->EnableSRGBWrite( false );
DECLARE_STATIC_VERTEX_SHADER( blurfilter_vs20 );
SET_STATIC_VERTEX_SHADER_COMBO( KERNEL, params[ KERNEL ]->GetIntValue() ? 1 : 0 );
SET_STATIC_VERTEX_SHADER( blurfilter_vs20 );
DECLARE_STATIC_PIXEL_SHADER( blurfilter_ps20b );
SET_STATIC_PIXEL_SHADER_COMBO( KERNEL, params[ KERNEL ]->GetIntValue() );
SET_STATIC_PIXEL_SHADER_COMBO( CLEAR_COLOR, false );
SET_STATIC_PIXEL_SHADER( blurfilter_ps20b );
if ( IS_FLAG_SET( MATERIAL_VAR_ADDITIVE ) )
EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE );
}
DYNAMIC_STATE
{
BindTexture( SHADER_SAMPLER0, BASETEXTURE, -1 );
float v[4];
// The temp buffer is 1/4 back buffer size
ITexture *src_texture = params[BASETEXTURE]->GetTextureValue();
int width = src_texture->GetActualWidth();
float dX = 1.0f / width;
// Tap offsets
v[0] = 1.3366f * dX;
v[1] = 0.0f;
v[2] = 0;
v[3] = 0;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, v, 1 );
v[0] = 3.4295f * dX;
v[1] = 0.0f;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_1, v, 1 );
v[0] = 5.4264f * dX;
v[1] = 0.0f;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, v, 1 );
v[0] = 7.4359f * dX;
v[1] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 0, v, 1 );
v[0] = 9.4436f * dX;
v[1] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 1, v, 1 );
v[0] = 11.4401f * dX;
v[1] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 2, v, 1 );
v[0] = v[1] = v[2] = v[3] = 1.0;
pShaderAPI->SetPixelShaderConstant( 3, v, 1 );
v[0] = v[1] = v[2] = v[3] = 0.0;
v[0] = dX;
pShaderAPI->SetPixelShaderConstant( 4, v, 1 );
DECLARE_DYNAMIC_VERTEX_SHADER( blurfilter_vs20 );
SET_DYNAMIC_VERTEX_SHADER( blurfilter_vs20 );
DECLARE_DYNAMIC_PIXEL_SHADER( blurfilter_ps20b );
SET_DYNAMIC_PIXEL_SHADER( blurfilter_ps20b );
}
Draw();
}
END_SHADER
| [
"kubci.rusnk645@gmail.com"
] | kubci.rusnk645@gmail.com |
3b783d6244bf8b6a44741f6f987b2405fe6741aa | a7d1b1158f5b8ffdfc7e2b6f1a24dfd234bcded6 | /C_expedtion/inheritance/3_4/Infantry.h | 135bb813f03b13c70205cbdde997beff7196109c | [] | no_license | Ferrymania/Cplusplus_learning | 56f44c4dc47b66deea3319275a122fbda4e66930 | 99cd1451075b57aa125931e40e9f2d2aaa6d98eb | refs/heads/master | 2020-03-22T02:35:10.849423 | 2018-07-05T12:39:00 | 2018-07-05T12:39:00 | 139,380,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | h | #include <iostream>
#include "Soldier.h"
class Infantry:public Soldier
{
public:
void attack();
};
| [
"904655716@qq.com"
] | 904655716@qq.com |
f303c40ad4deb9acbc38ebddd9dd754fcef71018 | b957ed321f7594340e2d455f807da856e411e18f | /laser/LaserDef.h | 57d22044b81c54f254504f415ce772454a97b1d6 | [] | no_license | yrewzjs/SADS | a4d7fe8b2637fabae68976ddb43119fd438cc000 | 77ede95518af1b3ab3564cb8339c14487a2445a9 | refs/heads/master | 2020-05-17T09:55:33.004304 | 2019-04-26T15:15:21 | 2019-04-26T15:15:21 | 175,948,504 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,453 | h | #ifndef _LASERDEF_H_
#define _LASERDEF_H_
#define SENSOR_REQ_ERROR _T("")
#define SENSOR_GROUP_REQ_ERROR _T("")
#define SENSOR_REQ_ERROR_DATA -999.98
/************ 激光传感器安装位置与其id的对应关系 ****************
激光传感器 General布局
D1(10) | D0(09) E0(11) | E1(12)
| |
| C0(06) B0(03) A0(00) |
————————————————
C1(07) B1(04) A1(01)
C2(08) B2(05) A2(02)
激光传感器 Roof布局
———————————
F1(14) | F0(13) G0(15) | G1(16)
H1(18) | H0(17) J0(19) | J1(20)
*************************************/
#define SENSOR_NUMBER 21
/************ 激光传感器 SensorMark ****************
1、传感器编号是和配置文件强相关的,强烈不同意更改
2、增加传感器或删除传感器,注意对应的配置文件需对应变化。
**/
enum SensorMark
{ //General
A0 = 0, //A0,传感器id=0
A1 = 1, //A1 传感器id=1
A2 = 2, //A2
B0 = 3, //B0
B1 = 4, //B1
B2 = 5, //B2
C0 = 6, //C0
C1 = 7, //C1
C2 = 8, //C2
D0 = 9, //D0
D1 = 10, //D1
E0 = 11, //E0
E1 = 12, //E1
//Roof
F0 = 13, //F0
F1 = 14, //F1
G0 = 15, //G0
G1 = 16, //G1
H0 = 17,
H1 = 18,
J0 = 19,
J1 = 20
};
/************ 激光传感器 DeltaMark ****************
1、DeltaMark编号与Calculate::UpdataDeltaArr()方法强耦合在一起的,强烈不同意更改
2、若发生更改,注意该方法的更改,该方法是数据运算的核心,若出现对应错误等逻辑问题,很难发现弥补。
**/
#define DELTA_NUMBER 18
enum DeltaMark
{ //General
A2_A0 = 0, //A2-A0,传感器A2 与 传感器A0 测量值做差 被减数在前面
B2_B0 = 1,
C2_C0 = 2,
A2_A1 = 3,
B2_B1 = 4,
C2_C1 = 5,
D1_D0 = 6,
E1_E0 = 7,
D0_E0 = 8,
C0_A0 = 9,
D0_C0 = 10,
E0_A0 = 11,
//Roof
F1_F0 = 12,
G1_G0 = 13,
F0_G0 = 14,
H0_J0 = 15,
F0_H0 = 16,
G0_J0 = 17,
};
enum LaserState
{
STOPPED, //关闭
EMITTING, //开启
PARTSTOPPED, //部分关闭
};
enum SensorBrand
{
SICK, //sick
KEYENCE, //keyence
};
struct ranging_struct
{
double cali_v[SENSOR_NUMBER]; // 标定值数组
double meas_v[SENSOR_NUMBER]; // 测量值数组
double real_v[SENSOR_NUMBER]; // 真实值数组
};
class LaserDef
{
public:
static CString ParseDeltaMark(DeltaMark mark);
static CString ParseSensorMark(int mark);
};
#endif
| [
"zhangjstj@163.com"
] | zhangjstj@163.com |
e6723f4e35f526982035267b583331febf95d097 | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mameppk/src/emu/bus/c64/dela_ep7x8.h | d1deb8a2da01ffe6ea58742214ed0d1580c307a2 | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | h | // license:BSD-3-Clause
// copyright-holders:Curt Coder
/**********************************************************************
Dela 7x8K EPROM cartridge emulation
**********************************************************************/
#pragma once
#ifndef __DELA_EP7X8__
#define __DELA_EP7X8__
#include "emu.h"
#include "bus/generic/slot.h"
#include "bus/generic/carts.h"
#include "exp.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> c64_dela_ep7x8_cartridge_device
class c64_dela_ep7x8_cartridge_device : public device_t,
public device_c64_expansion_card_interface
{
public:
// construction/destruction
c64_dela_ep7x8_cartridge_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// optional information overrides
virtual machine_config_constructor device_mconfig_additions() const;
protected:
// device-level overrides
virtual void device_start();
virtual void device_reset();
// device_c64_expansion_card_interface overrides
virtual UINT8 c64_cd_r(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2);
virtual void c64_cd_w(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2);
private:
required_device<generic_slot_device> m_eprom1;
required_device<generic_slot_device> m_eprom2;
required_device<generic_slot_device> m_eprom3;
required_device<generic_slot_device> m_eprom4;
required_device<generic_slot_device> m_eprom5;
required_device<generic_slot_device> m_eprom6;
required_device<generic_slot_device> m_eprom7;
UINT8 m_bank;
};
// device type definition
extern const device_type C64_DELA_EP7X8;
#endif
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
adf6bc1e166398acfc662a2edb03bcdb076ac833 | 2997b79fdeeb2d8a03ef7ec713a15338ffb3dd74 | /Idle/Idle.cpp | 1a8ac4691aed8e39893d275e9cf44567215e46f6 | [] | no_license | goodpaperman/gallery | bc3d9d0d00530fdb495dc93d5ce7aeb0a9486f6a | 75da45e9254522c412ce1ad63a195e417fc336e0 | refs/heads/master | 2020-05-30T11:00:05.886882 | 2019-06-01T03:40:15 | 2019-06-01T03:40:15 | 189,686,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,978 | cpp | // Idle.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "Idle.h"
#include "IdleDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CIdleApp
BEGIN_MESSAGE_MAP(CIdleApp, CWinApp)
//{{AFX_MSG_MAP(CIdleApp)
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CIdleApp construction
CIdleApp::CIdleApp()
{
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CIdleApp object
CIdleApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CIdleApp initialization
BOOL CIdleApp::InitInstance()
{
// Standard initialization
CIdleDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
}
else if (nResponse == IDCANCEL)
{
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
BOOL CIdleApp::OnIdle(LONG lCount)
{
// CG: The following code inserted by 'Idle Time Processing' component.
// Note: Do not perform lengthy tasks during OnIdle because your
// application cannot process user input until OnIdle returns.
// call the base class
BOOL bBaseIdle = CWinApp::OnIdle(lCount);
BOOL bMoreIdle = TRUE;
if (lCount == 0)
{
// TODO: add code to perform important idle time processing
TRACE("Idle: %d", lCount);
}
else if (lCount == 100)
{
// TODO: add code to perform less important tasks during idle
TRACE("Idle: %d", lCount);
}
else if (lCount == 1000)
{
// TODO: add code to perform occasional tasks during idle
bMoreIdle = bBaseIdle;
TRACE("Idle: %d", lCount);
}
// return FALSE when there is no more idle processing to do
return bMoreIdle;
}
| [
"haihai107@126.com"
] | haihai107@126.com |
d332b870a9d64952ed4da28fc0d5ecea8158252e | 5ffe39f3e7c42e77423dbadd8297329d41b5ce53 | /codeforces/A. Filling Diamonds.cpp | b80140a91f831951699ac5775c3b341ad9b36120 | [] | no_license | MnSakibOvi/competitive-programming | dd521b1e13926858a59ed9685cc29e734b1537ba | dd5918c7fd4333fc0acb957f84502a89d075d1cb | refs/heads/main | 2023-08-15T22:42:17.445947 | 2021-10-23T11:06:47 | 2021-10-23T11:06:47 | 376,104,374 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | cpp |
#include<bits/stdc++.h>
using namespace std;
void solve();
void multipleTestCase()
{
int t;
cin>>t;
while(t--)
solve();
}
int main()
{
multipleTestCase();
return 0;
}
void solve()
{
long long int n;
cin>>n;
cout<<n<<endl;
}
| [
"mnsakib1812@gmail.com"
] | mnsakib1812@gmail.com |
7e071e770c6f893c5d7ad7a448c6e7eedcf6fc7c | 3e2a2e96c22b18c669d7d8816db3c2c73d9f46f3 | /src/zsbp/accumulatorcheckpoints.h | 3cc5a17424ee419e348fa7f837802612a53325a9 | [
"MIT"
] | permissive | sbpaycoin/sbpay | d433e96ac580031352b644a80b15cd2532e7cc2b | d2865a73c01d46245bbfe64bf4c01b7fc3cbf962 | refs/heads/master | 2022-11-12T13:54:37.647900 | 2020-07-13T05:00:56 | 2020-07-13T05:00:56 | 275,895,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | h | // Copyright (c) 2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SBPay_ACCUMULATORCHECKPOINTS_H
#define SBPay_ACCUMULATORCHECKPOINTS_H
#include <libzerocoin/bignum.h>
#include <univalue/include/univalue.h>
namespace AccumulatorCheckpoints
{
typedef std::map<libzerocoin::CoinDenomination, CBigNum> Checkpoint;
extern std::map<int, Checkpoint> mapCheckpoints;
UniValue read_json(const std::string& jsondata);
bool LoadCheckpoints(const std::string& strNetwork);
Checkpoint GetClosestCheckpoint(const int& nHeight, int& nHeightCheckpoint);
}
#endif //SBPay_ACCUMULATORCHECKPOINTS_H
| [
"67603068+sbpaycoin@users.noreply.github.com"
] | 67603068+sbpaycoin@users.noreply.github.com |
db30d76108c9bf11d8bdf40e0320df748d0b0ded | a234f3a0a996e922e8bd3da10116777dc1c34866 | /lrm_wrappers/src/zigzag_filter.cpp | e098ba8bae57e7eb212ca6473443279123949c5e | [] | no_license | Aand1/lrm_carina | d3cccbc5f78c37643ccd6e232f5e147d797ccffe | 76de955e3f2349f24436196c8a82d38340028225 | refs/heads/master | 2021-01-20T14:28:51.725555 | 2014-06-17T02:34:05 | 2014-06-17T02:34:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,768 | cpp | /*
* Copyright (C) 2012, Laboratorio de Robotica Movel - ICMC/USP
* Rafael Luiz Klaser <rlklaser@gmail.com>
* http://lrm.icmc.usp.br
*
* Apoio FAPESP: 2012/04555-4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file zigzag_filter.cpp
* @brief
* @author Rafael Luiz Klaser <rlklaser@gmail.com>
* @date Sep 30, 2013
*
*/
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/ros/conversions.h>
#include <pcl_ros/transforms.h>
#include <tf/transform_listener.h>
#include <tf/message_filter.h>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/assign.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <math.h>
using namespace boost::accumulators;
typedef pcl::PointCloud<pcl::PointXYZRGB>::iterator itrtor;
ros::Publisher pc_pub;
ros::Publisher pc_rem_pub;
sensor_msgs::PointCloud2 cloud_out;
void pointcloudCallback(const sensor_msgs::PointCloud2::ConstPtr& msg) {
if (pc_pub.getNumSubscribers() == 0)// && pc_rem_pub.getNumSubscribers())
return;
pcl::PointCloud<pcl::PointXYZRGB> cloud;
pcl::PointCloud<pcl::PointXYZRGB> cloud_out;
pcl::PointCloud<pcl::PointXYZRGB> cloud_rem_out;
sensor_msgs::PointCloud2 msg_out;
pcl::fromROSMsg(*msg, cloud);
double min_x = 99999999;
double max_x = 0;
long qtd = 0;
double x;
double tot = 0;
double mean = 0;
double var = 0;
double stdev = 0;
double centered_x;
itrtor end = cloud.points.end();
for (itrtor itr = cloud.points.begin(); itr != end; ++itr )
{
qtd++;
x = itr->x;
tot += x;
if(x>max_x) max_x = x;
if(x<min_x) min_x = x;
}
tot = tot - (min_x * qtd);
mean = tot / qtd;
tot = 0;
for (itrtor itr = cloud.points.begin(); itr != end; ++itr )
{
x = itr->x;
centered_x = x-min_x;
tot += (centered_x-mean)*(centered_x-mean);
}
var = tot / qtd;
stdev = sqrt(var);
qtd = 0;
for (itrtor itr = cloud.points.begin(); itr != end; ++itr )
{
x = itr->x;
centered_x = x-min_x;
if( centered_x > (mean-stdev) && centered_x < (mean+stdev)) {
cloud_out.points.push_back(*itr);
}
else {
cloud_rem_out.points.push_back(*itr);
qtd++;
}
}
pcl::toROSMsg(cloud_out, msg_out);
msg_out.header = msg->header;
pc_pub.publish(msg_out);
pcl::toROSMsg(cloud_rem_out, msg_out);
msg_out.header = msg->header;
pc_rem_pub.publish(msg_out);
//std::cout << "removed " << qtd << std::endl;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "zigzag_filter_node");
ros::NodeHandle nh;
ros::NodeHandle nh_priv("~");
ros::Subscriber pc_sub = nh.subscribe("points_in", 100, pointcloudCallback);
//ros::Subscriber pc_sub = nh.subscribe("/cloud/points_cluster", 1, pointcloudCallback);
pc_pub = nh.advertise<sensor_msgs::PointCloud2>(nh_priv.getNamespace() + "/points_out", 1);
pc_rem_pub = nh.advertise<sensor_msgs::PointCloud2>(nh_priv.getNamespace() + "/points_out_removed", 1);
ros::spin();
return 0;
}
| [
"rlklaser@icmc.usp.br"
] | rlklaser@icmc.usp.br |
12d1eaa6aee813976fbf9dd2c881c26f8f498926 | cafe801758da2ab7df15f2b3b37d311bc6db02f7 | /iron/udp_proxy/test/rrm_test.cc | 1d33e26f6ea7f295222efee48e9d4bf0f6881e2f | [
"MIT"
] | permissive | raytheonbbn/IRON | a79da13afe8c2752407cdd82773ef3988c2959b1 | 7c4fcb15622d8029efc48e9323efbf385cbf2e63 | refs/heads/master | 2023-04-03T23:45:24.356042 | 2021-03-31T14:50:35 | 2021-03-31T14:50:35 | 275,175,579 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,680 | cc | // IRON: iron_headers
/*
* Distribution A
*
* Approved for Public Release, Distribution Unlimited
*
* EdgeCT (IRON) Software Contract No.: HR0011-15-C-0097
* DCOMP (GNAT) Software Contract No.: HR0011-17-C-0050
* Copyright (c) 2015-20 Raytheon BBN Technologies Corp.
*
* This material is based upon work supported by the Defense Advanced
* Research Projects Agency under Contracts No. HR0011-15-C-0097 and
* HR0011-17-C-0050. Any opinions, findings and conclusions or
* recommendations expressed in this material are those of the author(s)
* and do not necessarily reflect the views of the Defense Advanced
* Research Project Agency.
*
* 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.
*/
/* IRON: end */
#include <cppunit/extensions/HelperMacros.h>
#include "rrm.h"
#include "four_tuple.h"
#include "log.h"
#include "packet_pool_heap.h"
#include "unused.h"
using ::iron::Log;
using ::iron::Rrm;
namespace
{
const char* UNUSED(kClassName) = "RrmTester";
}
//============================================================================
class RrmTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(RrmTest);
CPPUNIT_TEST(TestRrmCreation);
CPPUNIT_TEST(TestRrmFill);
CPPUNIT_TEST(TestRrmGetFlowFourTuple);
CPPUNIT_TEST(TestRrmGetFlowDstPort);
CPPUNIT_TEST_SUITE_END();
private:
iron::PacketPoolHeap pkt_pool_;
iron::Packet* rrm_;
iron::FourTuple four_tuple_;
public:
//==========================================================================
void setUp()
{
Log::SetDefaultLevel("FEWIA");
CPPUNIT_ASSERT(pkt_pool_.Create(8));
uint32_t saddr = htonl(10);
uint32_t daddr = htonl(100);
uint16_t sport = htons(4500);
uint16_t dport = htons(5500);
four_tuple_.Set(saddr, sport, daddr, dport);
rrm_ = Rrm::CreateNewRrm(pkt_pool_, four_tuple_);
}
//==========================================================================
void tearDown()
{
pkt_pool_.Recycle(rrm_);
Log::SetDefaultLevel("FE");
}
//==========================================================================
void TestRrmCreation()
{
LogD(kClassName, __func__,
"Testing RRM creation.\n");
CPPUNIT_ASSERT(rrm_->GetLengthInBytes() == sizeof(struct iphdr) +
sizeof(struct udphdr) + 4);
// Check the src/dst addresses are flipped in RRM.
uint32_t addr;
rrm_->GetIpSrcAddr(addr);
CPPUNIT_ASSERT(addr == four_tuple_.dst_addr_nbo());
rrm_->GetIpDstAddr(addr);
CPPUNIT_ASSERT(addr == four_tuple_.src_addr_nbo());
uint16_t port;
rrm_->GetSrcPort(port);
CPPUNIT_ASSERT(port == four_tuple_.src_port_nbo());
rrm_->GetDstPort(port);
CPPUNIT_ASSERT(port == htons(Rrm::kDefaultRrmPort));
uint8_t* buf = rrm_->GetBuffer(rrm_->GetIpPayloadOffset());
memcpy(&port, buf, sizeof(port));
CPPUNIT_ASSERT(port == four_tuple_.dst_port_nbo());
}
//==========================================================================
void TestRrmFill()
{
LogD(kClassName, __func__,
"Testing RRM fill.\n");
CPPUNIT_ASSERT(rrm_->GetLengthInBytes() == sizeof(struct iphdr) +
sizeof(struct udphdr) + 4);
uint64_t tot_bytes = 100000;
uint64_t rel_bytes = 2000;
uint32_t tot_pkts = 300;
uint32_t rel_pkts = 3;
uint32_t loss_rate = 5;
Rrm::FillReport(rrm_, tot_bytes, tot_pkts, rel_bytes, rel_pkts, loss_rate);
uint64_t this_tot_bytes;
uint64_t this_rel_bytes;
uint32_t this_tot_pkts;
uint32_t this_rel_pkts;
uint32_t this_loss_rate;
Rrm::GetReport(rrm_, this_tot_bytes, this_tot_pkts, this_rel_bytes,
this_rel_pkts, this_loss_rate);
CPPUNIT_ASSERT(this_tot_bytes == tot_bytes);
CPPUNIT_ASSERT(this_rel_bytes == rel_bytes);
CPPUNIT_ASSERT(this_tot_pkts == tot_pkts);
CPPUNIT_ASSERT(this_rel_pkts == rel_pkts);
CPPUNIT_ASSERT(this_loss_rate == loss_rate);
}
//==========================================================================
void TestRrmGetFlowFourTuple()
{
LogD(kClassName, __func__,
"Testing RRM getting flow four tuple.\n");
iron::FourTuple four_tuple(0, 0, 0, 0);
Rrm::GetFlowFourTuple(rrm_, four_tuple);
CPPUNIT_ASSERT(four_tuple == four_tuple_);
}
//==========================================================================
void TestRrmGetFlowDstPort()
{
LogD(kClassName, __func__,
"Testing RRM getting dst port.\n");
uint16_t flow_dst_port = 0;
flow_dst_port = ntohs(Rrm::GetFlowDstPort(rrm_));
CPPUNIT_ASSERT(flow_dst_port == 5500);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(RrmTest);
| [
"greg.lauer@raytheon.com"
] | greg.lauer@raytheon.com |
dc0d2f154f2997c2eb1828622cbbfc778b1b4e19 | 7c919da550660351db4d269651d269c9765a9d36 | /src/primitives/block.h | 41fc319bb4b365b4f3add1125a1a9020e7a5b053 | [
"MIT"
] | permissive | wyh136/innoket | f7673b8a1fd885598db949bd1bf7ac871beef005 | 27efcc929371de0eb8ea16420e2e6c63e207bcb5 | refs/heads/master | 2021-04-15T14:24:51.482275 | 2018-03-25T11:16:12 | 2018-03-25T11:16:12 | 126,707,143 | 0 | 0 | null | 2018-03-25T14:42:21 | 2018-03-25T14:42:20 | null | UTF-8 | C++ | false | false | 5,643 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2015-2017 The IKT developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_BLOCK_H
#define BITCOIN_PRIMITIVES_BLOCK_H
#include "primitives/transaction.h"
#include "keystore.h"
#include "serialize.h"
#include "uint256.h"
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE_CURRENT = 2000000;
static const unsigned int MAX_BLOCK_SIZE_LEGACY = 1000000;
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int32_t CURRENT_VERSION=4;
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
uint256 nAccumulatorCheckpoint;
CBlockHeader()
{
SetNull();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
//zerocoin active, header changes to include accumulator checksum
if(nVersion > 3)
READWRITE(nAccumulatorCheckpoint);
}
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
nTime = 0;
nBits = 0;
nNonce = 0;
nAccumulatorCheckpoint = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const;
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable CScript payee;
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
if(vtx.size() > 1 && vtx[1].IsCoinStake())
READWRITE(vchBlockSig);
}
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
payee = CScript();
vchBlockSig.clear();
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
return block;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
bool SignBlock(const CKeyStore& keystore);
bool CheckBlockSignature() const;
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// Build the in-memory merkle tree for this block and return the merkle root.
// If non-NULL, *mutated is set to whether mutation was detected in the merkle
// tree (a duplication of transactions in the block leading to an identical
// merkle root).
uint256 BuildMerkleTree(bool* mutated = NULL) const;
std::vector<uint256> GetMerkleBranch(int nIndex) const;
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
std::string ToString() const;
void print() const;
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
struct CBlockLocator
{
std::vector<uint256> vHave;
CBlockLocator() {}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
}
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
};
#endif // BITCOIN_PRIMITIVES_BLOCK_H
| [
"36470139+Innoket@users.noreply.github.com"
] | 36470139+Innoket@users.noreply.github.com |
5b2dfa55b168e13518e420bccb0872fe26998351 | e217eaf05d0dab8dd339032b6c58636841aa8815 | /Ifc2x3/src/OpenInfraPlatform/Ifc2x3/entity/include/IfcSurfaceStyleRefraction.h | 3fdfe5fe82b008298a37c0a6f98c07b7b8608093 | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | UTF-8 | C++ | false | false | 1,678 | h | /*! \verbatim
* \copyright Copyright (c) 2014 Julian Amann. All rights reserved.
* \date 2014-04-26 17:30
* \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann)
* \brief This file is part of the BlueFramework.
* \endverbatim
*/
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "../../model/shared_ptr.h"
#include "../../model/Ifc2x3Object.h"
#include "IfcSurfaceStyleElementSelect.h"
namespace OpenInfraPlatform
{
namespace Ifc2x3
{
class IfcReal;
//ENTITY
class IfcSurfaceStyleRefraction : public IfcSurfaceStyleElementSelect, public Ifc2x3Entity
{
public:
IfcSurfaceStyleRefraction();
IfcSurfaceStyleRefraction( int id );
~IfcSurfaceStyleRefraction();
// method setEntity takes over all attributes from another instance of the class
virtual void setEntity( shared_ptr<Ifc2x3Entity> other );
virtual void getStepLine( std::stringstream& stream ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<Ifc2x3Entity> >& map );
virtual void setInverseCounterparts( shared_ptr<Ifc2x3Entity> ptr_self );
virtual void unlinkSelf();
virtual const char* classname() const { return "IfcSurfaceStyleRefraction"; }
// IfcSurfaceStyleRefraction -----------------------------------------------------------
// attributes:
shared_ptr<IfcReal> m_RefractionIndex; //optional
shared_ptr<IfcReal> m_DispersionFactor; //optional
};
} // end namespace Ifc2x3
} // end namespace OpenInfraPlatform
| [
"planung.cms.bv@tum.de"
] | planung.cms.bv@tum.de |
83e4cf94f804db581b53b15f11a9593368d1fdf9 | ae956d4076e4fc03b632a8c0e987e9ea5ca89f56 | /SDK/MRMesh_structs.h | 39da9de9154ebf672b68cbf6fa4763e45d1bc2a5 | [] | no_license | BrownBison/Bloodhunt-BASE | 5c79c00917fcd43c4e1932bee3b94e85c89b6bc7 | 8ae1104b748dd4b294609717142404066b6bc1e6 | refs/heads/main | 2023-08-07T12:04:49.234272 | 2021-10-02T15:13:42 | 2021-10-02T15:13:42 | 638,649,990 | 1 | 0 | null | 2023-05-09T20:02:24 | 2023-05-09T20:02:23 | null | UTF-8 | C++ | false | false | 1,115 | h | #pragma once
// Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Enums
//---------------------------------------------------------------------------
// Enum MRMesh.EMeshTrackerVertexColorMode
enum class MRMesh_EMeshTrackerVertexColorMode : uint8_t
{
EMeshTrackerVertexColorMode__None = 0,
EMeshTrackerVertexColorMode__Confidence = 1,
EMeshTrackerVertexColorMode__Block = 2,
EMeshTrackerVertexColorMode__EMeshTrackerVertexColorMode_MAX = 3,
};
//---------------------------------------------------------------------------
// Script Structs
//---------------------------------------------------------------------------
// ScriptStruct MRMesh.MRMeshConfiguration
// 0x0001
struct FMRMeshConfiguration
{
unsigned char UnknownData_Y2GW[0x1]; // 0x0000(0x0001) MISSED OFFSET (PADDING)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"69031575+leoireo@users.noreply.github.com"
] | 69031575+leoireo@users.noreply.github.com |
f7b4c5b4626d7af6da51efd8a2fee75d903a5510 | b71136d14603e25a0637de413d2316f96272e148 | /cpsc3200/RockyMountain2015/FlippingCards.cpp | fa70335f1168bc08d424192fe28260680f96876d | [] | no_license | JSwidinsky/CompetitiveProgramming | 34df380b26fad53191a07c692298d68394b4fd48 | 3742a1c5f9b422f2957ad7d67fed4fbfb6981455 | refs/heads/master | 2020-09-24T07:48:34.797284 | 2020-05-21T17:45:29 | 2020-05-21T17:45:29 | 225,705,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,986 | cpp | #include <bits/stdc++.h>
using namespace std;
#define debug(a) cerr << #a << " = " << (a) << endl;
#define fst first
#define snd second
#define sz(x) (int)(x).size()
#define all(X) begin(X), end(X)
typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int, int> pii;
template<typename T, typename U> ostream& operator<<(ostream& o, const pair<T, U>& x) {
o << "(" << x.fst << ", " << x.snd << ")"; return o;
}
template<typename T> ostream& operator<<(ostream& o, const vector<T>& x) {
o << "["; int b = 0; for (auto& a : x) o << (b++ ? ", " : "") << a; o << "]"; return o;
}
template<typename T> ostream& operator<<(ostream& o, const set<T>& x) {
o << "{"; int b = 0; for (auto& a : x) o << (b++ ? ", " : "") << a; o << "}"; return o;
}
template<typename T, typename U> ostream& operator<<(ostream& o, const map<T, U>& x) {
o << "{"; int b = 0; for (auto& a : x) o << (b++ ? ", " : "") << a; o << "}"; return o;
}
struct UF {
int n; vector<int> A;
UF (int n) : n(n), A(n) { iota(begin(A), end(A), 0); }
int find (int a) { return a == A[a] ? a : A[a] = find(A[a]); }
bool connected (int a, int b) { return find(a) == find(b); }
void merge (int a, int b) { A[find(b)] = find(a); }
};
/*
In this problem, we want to find each strongly connected component
and then count the number of cycles in each of the components
If the number of cycles is < 2, then it is possible, else it is not
*/
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t; cin >> t;
while(t--) {
int n; cin >> n;
UF uf(2*n);
vector<int> cnt(2*n, 0);
for(int i = 0; i < n; ++i) {
int a, b; cin >> a >> b;
--a; --b;
if(uf.connected(a,b)) {
cnt[uf.find(a)]++;
}
else {
cnt[uf.find(a)] += cnt[uf.find(b)];
uf.merge(a,b);
}
}
bool b = true;
for(int i = 0; i < 2*n; ++i) {
b = b && (cnt[uf.find(i)] < 2);
}
cout << (b ? "possible" : "impossible") << endl;
}
}
| [
"swidinjo@gmail.com"
] | swidinjo@gmail.com |
120cf1acc95aa93d5eb40d24fbdce9d5e6f424ef | e48c6ed286669dab8471c653c001c5d91bbf59e0 | /hackerblocks1/ARRAYS-WAVE PRINT ROW WISE.cpp | 2ac9135ce8333a96e456076c184409e9159f74fe | [] | no_license | bdugersuren/Launchpad | 55565e9e039385b4ce2ed39718a7f1c1a9a9e643 | e93f32d200917b10568a2bd8dbc3b73c72bb6ee0 | refs/heads/master | 2023-04-14T17:44:37.766974 | 2021-05-03T15:55:04 | 2021-05-03T15:55:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | /*
Take as input a two-d array. Wave print it row-wise.
Input Format:
Two integers M(row) and N(column) and further M * N integers(2-d array numbers).
Constraints:
Both M and N are between 1 to 10.
Output Format:
All M * N integers are seperated by commas with 'END' written in the end(as shown in example).
Sample Input:
4 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
Sample Output:
11, 12, 13, 14, 24, 23, 22, 21, 31, 32, 33, 34, 44, 43, 42, 41, END
*/
#include<iostream>
using namespace std;
int main()
{
int m,n;
cin>>m;
cin>>n;
int a[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i%2==0)
{
cout<<a[i][j]<<", ";
}
else
{
cout<<a[i][n-1-j]<<", ";
}
}
}
cout<<"END";
return 0;
}
| [
"ishaansharma1998@gmail.com"
] | ishaansharma1998@gmail.com |
865c6b323941d9f85a0867eba854331316643217 | 075a7009c123d9a282b476577d20f75a24a8aed8 | /torch/csrc/jit/runtime/register_ops_utils.h | 495dcc8698b97abb226868cd8b59b7a3cea9690a | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | waldow90/pytorch | b98c17f11b117e8b6bb17ea909529f8d8a9a0f90 | d0f2079b5e0247c38e731f5e7e7dba835aef644f | refs/heads/master | 2022-11-15T04:10:03.825667 | 2020-07-03T09:44:32 | 2020-07-03T09:52:14 | 276,874,185 | 0 | 1 | NOASSERTION | 2020-07-03T10:35:07 | 2020-07-03T10:35:06 | null | UTF-8 | C++ | false | false | 21,024 | h | #pragma once
#include <aten/src/ATen/Context.h>
#include <c10/core/DeviceType.h>
#include <torch/csrc/autograd/autograd.h>
#include <torch/csrc/autograd/edge.h>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/generated/variable_factories.h>
#include <torch/csrc/autograd/profiler.h>
#include <torch/csrc/autograd/variable.h>
#include <torch/csrc/jit/api/compilation_unit.h>
#include <torch/csrc/jit/codegen/fuser/interface.h>
#include <torch/csrc/jit/frontend/error_report.h>
#include <torch/csrc/jit/ir/ir.h>
#include <torch/csrc/jit/runtime/custom_operator.h>
#include <torch/csrc/jit/runtime/graph_executor.h>
#include <torch/csrc/jit/runtime/jit_exception.h>
#include <torch/csrc/jit/runtime/logging.h>
#include <torch/csrc/jit/runtime/operator.h>
#include <torch/csrc/jit/runtime/print_handler.h>
#include <torch/csrc/jit/runtime/profiling_record.h>
#include <torch/csrc/jit/runtime/vararg_functions.h>
#include <torch/csrc/jit/serialization/pickle.h>
#include <ATen/ExpandUtils.h>
#include <ATen/Parallel.h>
#include <ATen/WrapDimUtils.h>
#include <ATen/core/Dict.h>
#include <ATen/core/ivalue.h>
#include <c10/core/thread_pool.h>
#include <c10/util/SmallVector.h>
#include <c10/util/math_compat.h>
#include <c10/util/string_utils.h>
namespace torch {
namespace jit {
inline c10::AliasAnalysisKind aliasAnalysisFromSchema() {
return c10::AliasAnalysisKind::FROM_SCHEMA;
}
inline c10::AliasAnalysisKind aliasAnalysisConservative() {
return c10::AliasAnalysisKind::CONSERVATIVE;
}
inline c10::AliasAnalysisKind aliasAnalysisSpecialCase() {
return c10::AliasAnalysisKind::INTERNAL_SPECIAL_CASE;
}
template <class T>
c10::List<T> make_result_list(const TypePtr& elemType) {
return c10::List<T>();
}
template <>
c10::impl::GenericList make_result_list<IValue>(const TypePtr& elemType);
inline void noop(Stack* n) {}
// using the rules from python_arg_parser FunctionParameter::check
// tensor cannot have grad set, tensor must be 0 dim,
// and if the dest is an int the source must be integral type
void checkImplicitTensorToNum(const at::Tensor& t, bool toInt);
// Convert the tensor pointed to by \p data to a nested list. \p dim is the
// number of dimensions in the tensor and \p cur_dim is the dimension being
// processed by the current invocation. \p ty is the expected output IR type of
// the operation. \p is the scalar type of \p data. \p sizes and \p strides are
// the sizes and strides of the tensor operand and \p element_size is the size
// in bytes of one tensor element.
IValue tensorToListRecursive(
char* data,
int64_t cur_dim,
int64_t num_tensor_dims,
TypePtr ty,
at::ScalarType scalar_ty,
at::IntArrayRef sizes,
at::IntArrayRef strides,
size_t element_size);
static int64_t floordiv(int64_t a, int64_t b) {
if (b == 0) {
throw std::runtime_error("division by 0");
}
if ((a > 0) == (b > 0)) {
// simple case, both have same sign
return a / b;
} else {
// in python division rounds down, it doesn't not truncate like in c++
auto r = lldiv(a, b);
return (r.rem) ? r.quot - 1 : r.quot;
}
}
TORCH_API void checkDoubleInRange(double a);
static int64_t floor(double a) {
checkDoubleInRange(a);
return std::floor(a);
}
static int64_t ceil(double a) {
checkDoubleInRange(a);
return std::ceil(a);
}
static int64_t gcd(int64_t a, int64_t b) {
while (b != 0) {
int64_t r = a % b;
a = b;
b = r;
}
// in python gcd returns non-negative values
return std::abs(a);
}
int64_t partProduct(int n, int m);
void loop(int n, int64_t& p, int64_t& r);
int nminussumofbits(int v);
int64_t factorial(int n);
static const double degToRad = std::acos(-1.0) / 180.0;
static const double radToDeg = 180.0 / std::acos(-1.0);
double degrees(double x);
double radians(double x);
// reference function THPVariable_to in python_variable_methods.cpp
static at::Tensor to_dispatch(
at::Tensor self,
c10::optional<at::Device> device,
c10::optional<at::ScalarType> scalarType,
bool non_blocking,
bool copy) {
if (device && device->is_cuda()) {
at::globalContext().lazyInitCUDA();
}
if (!device && !scalarType && !copy) {
return self;
} else if (!device) {
return self.to(*scalarType, non_blocking, copy);
} else if (!scalarType) {
return self.to(*device, non_blocking, copy);
} else {
return self.to(*device, *scalarType, non_blocking, copy);
}
}
// Convert an python index (which may be negative) into an index usable for a
// C++ container
int64_t normalizeIndex(int64_t idx, int64_t list_size);
// Equivalent to list.at(idx)
template <typename T>
T getItem(const c10::List<T>& list, int64_t idx) {
const int64_t list_size = list.size();
const int64_t normalized_idx = normalizeIndex(idx, list_size);
if (normalized_idx < 0 || normalized_idx >= list_size) {
throw std::out_of_range("list index out of range");
}
return list.get(normalized_idx);
}
template <typename T>
void setItem(const c10::List<T>& list, int64_t idx, T&& value) {
const int64_t list_size = list.size();
const int64_t normalized_idx = normalizeIndex(idx, list_size);
if (normalized_idx < 0 || normalized_idx >= list_size) {
throw std::out_of_range("list index out of range");
}
list.set(normalized_idx, std::move(value));
}
void listAppend(Stack* stack);
void listReverse(Stack* stack);
template <typename T>
void minList(Stack* stack) {
c10::List<T> a = pop(stack).to<c10::List<T>>();
c10::List<T> b = pop(stack).to<c10::List<T>>();
size_t min_size = std::min(a.size(), b.size());
for (size_t i = 0; i < min_size; i++) {
if (a[i] == b[i]) {
continue;
}
push(stack, a[i] < b[i] ? a : b);
return;
}
push(stack, b.size() < a.size() ? b : a);
}
template <typename T>
void maxList(Stack* stack) {
c10::List<T> a = pop(stack).to<c10::List<T>>();
c10::List<T> b = pop(stack).to<c10::List<T>>();
size_t min_size = std::min(a.size(), b.size());
for (size_t i = 0; i < min_size; i++) {
if (a[i] == b[i]) {
continue;
}
push(stack, a[i] > b[i] ? a : b);
return;
}
push(stack, b.size() > a.size() ? b : a);
}
void listPopImpl(Stack* stack, const char* empty_message);
void listPop(Stack* stack);
void listClear(Stack* stack);
void listDelete(Stack* stack);
void listInsert(Stack* stack);
template <typename T>
void listRemove(Stack* stack) {
T elem = pop(stack).to<T>();
c10::List<T> list = pop(stack).to<c10::List<T>>();
auto pos = std::find(list.begin(), list.end(), elem);
if (pos != list.end()) {
list.erase(pos);
} else {
AT_ERROR("list.remove(x): x not in list");
}
}
template <typename T>
void listMin(Stack* stack) {
c10::List<T> list = pop(stack).to<c10::List<T>>();
size_t list_size = list.size();
if (list_size == 0) {
throw std::runtime_error("min() arg is an empty sequence");
}
T min_elem = list[0];
for (size_t i = 1; i < list_size; ++i) {
T elem = list[i];
min_elem = elem < min_elem ? elem : min_elem;
}
stack->push_back(min_elem);
}
template <typename T>
void listMax(Stack* stack) {
c10::List<T> list = pop(stack).to<c10::List<T>>();
size_t list_size = list.size();
if (list_size == 0) {
throw std::runtime_error("max() arg is an empty sequence");
}
T max_elem = list[0];
for (size_t i = 1; i < list_size; ++i) {
T elem = list[i];
max_elem = elem > max_elem ? elem : max_elem;
}
stack->push_back(max_elem);
}
template <>
void listRemove<at::Tensor>(Stack* stack);
template <typename T>
void listIndex(Stack* stack) {
T elem = pop(stack).to<T>();
c10::List<T> list = pop(stack).to<c10::List<T>>();
auto pos = std::find(list.begin(), list.end(), elem);
if (pos != list.end()) {
push(stack, static_cast<int64_t>(std::distance(list.begin(), pos)));
} else {
AT_ERROR("'", elem, "' is not in list");
}
}
template <>
void listIndex<at::Tensor>(Stack* stack);
template <typename T>
void listCount(Stack* stack) {
T elem = pop(stack).to<T>();
c10::List<T> list = pop(stack).to<c10::List<T>>();
const int64_t count = std::count(list.begin(), list.end(), elem);
push(stack, count);
}
template <>
void listCount<at::Tensor>(Stack* stack);
void listExtend(Stack* stack);
void listCopy(Stack* stack);
void listSelect(Stack* stack);
void listLen(Stack* stack);
template <typename T>
void listEq(Stack* stack) {
c10::List<T> b = pop(stack).to<c10::List<T>>();
c10::List<T> a = pop(stack).to<c10::List<T>>();
push(stack, a == b);
}
template <typename T>
void listNe(Stack* stack) {
c10::List<T> b = pop(stack).to<c10::List<T>>();
c10::List<T> a = pop(stack).to<c10::List<T>>();
push(stack, a != b);
}
inline bool tensor_list_equal(
const c10::List<at::Tensor>& a,
const c10::List<at::Tensor>& b) {
if (a.size() != b.size()) {
return false;
}
for (size_t i = 0; i < a.size(); ++i) {
at::Tensor a_element = a[i];
at::Tensor b_element = b[i];
// This preserves Python's semantics, which uses eq() to compare two
// elements, then passes the result to bool().
// see: https://docs.python.org/3.4/reference/datamodel.html#object.__ge__
const auto cmp_result = a_element.eq(b_element);
if (!cmp_result.is_nonzero()) {
return false;
}
}
return true;
}
// Specialization for at::Tensor, since it doesn't define operator==
template <>
void listEq<at::Tensor>(Stack* stack);
// Specialization for at::Tensor, since it doesn't define operator==
template <>
void listNe<at::Tensor>(Stack* stack);
void listList(Stack* stack);
template <typename T>
void listContains(Stack* stack) {
auto key = pop(stack).to<T>();
auto list = pop(stack).to<c10::List<T>>();
for (const T& item : list) {
if (item == key) {
push(stack, true);
return;
}
}
push(stack, false);
}
void listAdd(Stack* stack);
void listInplaceAdd(Stack* stack);
void listMulIntLeftInPlace(Stack* stack);
void listMulIntLeft(Stack* stack);
void listMulIntRight(Stack* stack);
void listSlice(Stack* stack);
template <typename T>
void listSort(Stack* stack) {
bool reverse = pop(stack).toBool();
c10::List<T> list = pop(stack).to<c10::List<T>>();
std::sort(list.begin(), list.end(), [reverse](const T& a, const T& b) {
// FBCode errors without this check - "strict weak ordering"
// TODO: remove when possible, since it just slows down
// sorting and doesn't do anything useful
if (a == b) {
return false;
}
return (a < b) != reverse;
});
}
// Specialization for at::Tensor
template <>
void listSort<at::Tensor>(Stack* stack);
template <typename T>
void listCopyAndSort(Stack* stack) {
c10::List<T> list = pop(stack).to<c10::List<T>>();
auto list_copied = list.copy();
std::sort(list_copied.begin(), list_copied.end(), [](const T& a, const T& b) {
// "strict weak ordering" issue - see other sort
if (a == b) {
return false;
}
return a < b;
});
push(stack, list_copied);
}
// Specialization for at::Tensor
template <>
void listCopyAndSort<at::Tensor>(Stack* stack);
void listSetItem(Stack* stack);
#define DEFINE_GENERIC_BINARY_OP(aten_op, op, result) \
Operator( \
#aten_op ".int_int(int a, int b) -> " #result, \
[](Stack* stack) { \
int64_t a, b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema()), \
Operator( \
#aten_op ".float_float(float a, float b) -> " #result, \
[](Stack* stack) { \
double a, b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
// define implementations for primitive number ops
#define DEFINE_GENERIC_OP(aten_op, int_op, float_op, int_result, float_result) \
Operator( \
#aten_op ".int(int a, int b) -> " #int_result, \
[](Stack* stack) { \
int64_t a, b; \
pop(stack, a, b); \
push(stack, int_op); \
}, \
aliasAnalysisFromSchema()), \
Operator( \
#aten_op ".float(float a, float b) -> " #float_result, \
[](Stack* stack) { \
double a, b; \
pop(stack, a, b); \
push(stack, float_op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_INT_FLOAT_OP(aten_op, op, result) \
Operator( \
#aten_op ".int_float(int a, float b) -> " #result, \
[](Stack* stack) { \
int64_t a; \
double b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema()), \
Operator( \
#aten_op ".float_int(float a, int b) -> " #result, \
[](Stack* stack) { \
double a; \
int64_t b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_INT_OP(aten_op, op) \
Operator( \
#aten_op "(int a, int b) -> int", \
[](Stack* stack) { \
int64_t a, b; \
pop(stack, a, b); \
push(stack, op); /* NOLINT(hicpp-signed-bitwise) */ \
}, \
aliasAnalysisFromSchema())
#define DEFINE_STR_CMP_OP(aten_op, op) \
Operator( \
#aten_op ".str(str a, str b) -> bool", \
[](Stack* stack) { \
auto b = pop(stack).toStringRef(); \
auto a = pop(stack).toStringRef(); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
// define a primitive op over Scalar operands.
// it's necessary to register this overload following
// int/float variations to avoid trapping Scalar args
// in unintended implicit conversions
#define DEFINE_SCALAR_BINARY_OP(aten_op, int_op, float_op, result) \
Operator( \
#aten_op "(Scalar a, Scalar b) -> " #result, \
[](Stack* stack) { \
IValue x, y; \
pop(stack, x, y); \
if (x.isDouble()) { \
if (y.isDouble()) { \
double a = x.toDouble(); \
double b = y.toDouble(); \
push(stack, float_op); \
} else { \
double a = x.toDouble(); \
int64_t b = y.toInt(); \
push(stack, float_op); \
} \
} else { \
if (y.isDouble()) { \
int64_t a = x.toInt(); \
double b = y.toDouble(); \
push(stack, float_op); \
} else { \
int64_t a = x.toInt(); \
int64_t b = y.toInt(); \
push(stack, int_op); \
} \
} \
}, \
aliasAnalysisFromSchema())
#define DEFINE_BINARY_OP(aten_op, op) \
DEFINE_GENERIC_OP(aten_op, op, op, int, float), \
DEFINE_INT_FLOAT_OP(aten_op, op, float), \
DEFINE_SCALAR_BINARY_OP(aten_op, op, op, Scalar)
#define DEFINE_BINARY_FLOAT_OP(aten_op, op) \
DEFINE_GENERIC_OP(aten_op, op, op, float, float), \
DEFINE_INT_FLOAT_OP(aten_op, op, float), \
DEFINE_SCALAR_BINARY_OP(aten_op, op, op, float)
#define DEFINE_COMPARISON_OP(aten_op, op) \
DEFINE_GENERIC_OP(aten_op, op, op, bool, bool), \
DEFINE_INT_FLOAT_OP(aten_op, op, bool), \
DEFINE_SCALAR_BINARY_OP(aten_op, op, op, bool), \
DEFINE_STR_CMP_OP(aten_op, op)
#define DEFINE_UNARY_INT_OP(aten_op, op, result) \
Operator( \
#aten_op ".int(int a) -> " #result, \
[](Stack* stack) { \
int64_t a; \
pop(stack, a); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_UNARY_FLOAT_OP(aten_op, op, result) \
Operator( \
#aten_op ".float(float a) -> " #result, \
[](Stack* stack) { \
double a; \
pop(stack, a); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_UNARY_OP(aten_op, op, int_result, float_result) \
DEFINE_UNARY_INT_OP(aten_op, op, int_result), \
DEFINE_UNARY_FLOAT_OP(aten_op, op, float_result), \
Operator( \
#aten_op ".Scalar(Scalar a) -> Scalar", \
[](Stack* stack) { \
IValue x; \
pop(stack, x); \
if (x.isDouble()) { \
double a = x.toDouble(); \
push(stack, static_cast<float_result>(op)); \
} else { \
int64_t a = x.toInt(); \
push(stack, static_cast<int_result>(op)); \
} \
}, \
aliasAnalysisFromSchema())
#define DEFINE_BOOL_OP(aten_op, op) \
Operator( \
#aten_op ".bool(bool a, bool b) -> bool", \
[](Stack* stack) { \
bool a, b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
} // namespace jit
} // namespace torch
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
4353f10e69f58481404bcd065b69b6632a3910fe | cec716697fae96a627a705d9559d70df9c30930f | /Grasp_Manipulation/manipulability/src/manip_doc_23June18.cpp | 411fe05356f9f1449d5006bbac604f5fb9e5084b | [] | no_license | KING1360/mobman | 048e211d9c41ce0360d487b1d53ff60ad287fe85 | c6761c8ec35e49368c642a4106f98b199a23494f | refs/heads/master | 2020-03-26T08:09:22.736801 | 2018-08-15T16:09:14 | 2018-08-15T16:09:14 | 144,688,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,257 | cpp | #include <ros/ros.h>
#include "std_msgs/String.h"
#include <boost/scoped_ptr.hpp>
#include <kdl/chain.hpp>
#include <kdl/chainjnttojacsolver.hpp>
#include <kdl/chainfksolverpos_recursive.hpp>
#include <kdl/frames.hpp>
#include <kdl/jacobian.hpp>
#include <kdl/jntarray.hpp>
#include <kdl_parser/kdl_parser.hpp>
#include <sensor_msgs/JointState.h>
#include <kdl/chainfksolver.hpp>
#include <kdl/frames_io.hpp>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <iostream>
using namespace std;
using namespace KDL;
int main(int argc, char **argv)
{
ros::init(argc, argv, "manip");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Publisher joint_msg_pub = n.advertise<sensor_msgs::JointState>("leg_joints_states", 1);
ros::Rate loop_rate(10);
std::string robot_desc_string;
sensor_msgs::JointState joint_msg;
//n.param("robot_description", robot_desc_string, std::string());
if (n.getParam("robot_description", robot_desc_string))
{
//ROS_INFO("Got param: %s", robot_desc_string.c_str());
}
else
{
ROS_ERROR("Failed to get param 'my_param'");
}
KDL::Tree my_tree;
if (!kdl_parser::treeFromString(robot_desc_string, my_tree) ){
ROS_ERROR("Failed to construct kdl tree!");
return false;
}
else
{
ROS_INFO("Got the tree!");
}
KDL::Chain chain;
float myinput;
scanf ("%e",&myinput);
/*
//Definition of a kinematic chain & add segments to the chain
chain.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(0.0,0.0,1.020))));
chain.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.480))));
chain.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.645))));
chain.addSegment(Segment(Joint(Joint::RotZ)));
chain.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.120))));
chain.addSegment(Segment(Joint(Joint::RotZ)));
// Create solver based on kinematic chain
ChainFkSolverPos_recursive fksolver = ChainFkSolverPos_recursive(chain);
// Create joint array
unsigned int nj = chain.getNrOfJoints();
KDL::JntArray jointpositions = JntArray(nj);
// Assign some values to the joint positions
for(unsigned int i=0;i<nj;i++){
float myinput;
printf ("Enter the position of joint %i: ",i);
scanf ("%e",&myinput);
jointpositions(i)=(double)myinput;
}
// Create the frame that will contain the results
KDL::Frame cartpos;
// Calculate forward position kinematics
bool kinematics_status;
kinematics_status = fksolver.JntToCart(jointpositions,cartpos);
if(kinematics_status>=0){
std::cout << cartpos <<std::endl;
printf("%s \n","Succes, thanks KDL!");
}else{
printf("%s \n","Error: could not calculate forward kinematics :(");
}
*/
// ROS_INFO("I have read the robot description \n", my_tree.getNrOfJoints());
// kdl_parser::treeFromString(robot_desc_string, my_tree);
cout << "What's your name?\n ";
// kdl_parser::treeFromString(robot_desc_string, my_tree);
cout << "Schunk?\n ";
//KDL::Chain chain;
my_tree.getChain("arm_base_link", "arm_7_link", chain);
// Create solver based on kinematic chain
ChainFkSolverPos_recursive fksolver = ChainFkSolverPos_recursive(chain);
// Create joint array
int nj = chain.getNrOfJoints();
KDL::JntArray jointpositions = JntArray(nj);
printf("%s \n","Number of Joints==");
cout<< nj ;
printf("\n %s \n","This was the Number of Joint");
// Assign some values to the joint positions
for(unsigned int i=0;i<nj;i++){
float myinput;
printf ("\nEnter the position of joint %i: ",i);
//scanf ("%e",&myinput);
//jointpositions(i)=(double)myinput;
jointpositions(i)=0;
}
// Create the frame that will contain the results
KDL::Frame cartpos;
// Calculate forward position kinematics
bool kinematics_status;
kinematics_status = fksolver.JntToCart(jointpositions,cartpos);
if(kinematics_status>=0){
std::cout << "\n This is joint position= \n"<<cartpos <<std::endl;
printf("%s \n","Succes, thanks KDL!");
}else{
printf("%s \n","Error: could not calculate forward kinematics :(");
}
int segmentNR;
KDL::Jacobian J_;
J_.resize(chain.getNrOfJoints());
std::cout << "\n No. of rows of Jacobian = \n"<<J_.rows() << "\n No. of columns of Jacobian = \n"<<J_.columns() << ";\n \n"<<std::endl;
// ChainJntToJacSolver Jsolver = ChainJntToJacSolver(chain);
// int tmp_ = Jsolver.JntToJac(jointpositions,J_);
// std::cout << "\n found Jacobian = \n"<<tmp_ <<endl;
// boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_;
// jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(chain));
// jnt_to_jac_solver_->JntToJac(jointpositions, J_);
std::cout << "\n Jacobian = \n"<<J_.data << "\n \n"<<std::endl;
KDL::JntArray joint_pos(chain.getNrOfJoints());
KDL::Frame cart_pos;
KDL::ChainFkSolverPos_recursive fk_solver(chain);
fk_solver.JntToCart(joint_pos, cart_pos);
KDL::JntArray q_init(chain.getNrOfJoints());
for (unsigned int i = 0 ; i < 6 ; i++)
{
xdot_(i) = 0;
for (unsigned int j = 0 ; j < kdl_chain_.getNrOfJoints() ; j++)
xdot_(i) += J_(i,j) * qdot_.qdot(j);
}
//ROS_INFO(joint_pos.data);
//cout<< joint_pos.data<<"HAHADDD";
//my_tree.getChain("base_link", "tool", chain);
// KDL::JntArray joint_pos(cahin.getNrOfJoints());
// KDL::Frame cart_pos;
// KDL::ChainFkSolverPos_recursive fk_solver(chain);
// fk_solver.JntToCart(joint_pos, cart_pos);
// KDL class and functions
KDL::Vector v1(1,2,1);
KDL::Vector v2(v1);
KDL::Vector v3= KDL::Vector::Zero();
cout<< v1.x()<<"\n Here you go!\n";
v2 = 2*v1;
//v1 = v1/2;
double a=dot(v1,v2);
cout<<"\n v1.x ="<< v1.x()<<"; v1.y ="<< v1.y()<<" v1.z ="<< v1.z();
cout<<"\n v2.x ="<< v2.x()<<"; v2.y ="<< v2.y()<<" v2.z ="<< v2.z();
cout<<"\n A= !\n"<< a;
cout<< v2.x()<<"\n Here you go2222222222!\n"<<"\n";
KDL::Rotation r1 = KDL::Rotation::Identity();
cout<<"\n r1 ="<< r1(1,1);
KDL::Rotation r3=KDL::Rotation::RotX(.2);
KDL::Rotation r6=KDL::Rotation::RPY(.2,1,1);
r1.SetInverse();
KDL::Rotation r7 = r1.Inverse();
KDL::Vector v5 = r1*v1;
cout<<"\n V511 ="<< v5(0);cout<<"; r12 ="<< v2(1);cout<<"; r13 ="<< v2(2);
KDL::Rotation r5 = r1*r3;
KDL::Rotation r2 = r5.Inverse();
cout<<"\n r11 ="<< r2(0,0);cout<<"; r12 ="<< r2(1,0);cout<<"; r13 ="<< r2(2,0);
cout<<"\n r21 ="<< r2(0,1);cout<<"; r22 ="<< r2(1,1);cout<<"; r23 ="<< r2(2,1);
cout<<"\n r31 ="<< r2(0,2);cout<<"; r32 ="<< r2(1,2);cout<<"; r33 ="<< r2(2,2)<<"\n";
//FRAMES
KDL::Frame f1;
f1 = KDL::Frame::Identity();
KDL::Frame f2(r5,v1);
f2 = f1.Inverse();
cout<<"\n f11 ="<< f2(0,0);cout<<"; r12 ="<< f2(1,0);cout<<"; f13 ="<< f2(2,0);cout<<"; f14 ="<< f2(3,0);
cout<<"\n f21 ="<< f2(0,1);cout<<"; r22 ="<< f2(1,1);cout<<"; f23 ="<< f2(2,1);cout<<"; f23 ="<< f2(3,1);
cout<<"\n f31 ="<< f2(0,2);cout<<"; r32 ="<< f2(1,2);cout<<"; f33 ="<< f2(2,2);cout<<"; f33 ="<< f2(3,2);
cout<<"\n f31 ="<< f2(0,3);cout<<"; r32 ="<< f2(1,3);cout<<"; f33 ="<< f2(2,3);cout<<"; f33 ="<< f2(3,3)<<"\n";
// cout<<"\n f31 ="<< f2(0,3);cout<<"; r32 ="<< f2(1,3);cout<<"; f33 ="<< f2(2,3);cout<<"; f33 ="<< f2(3,3);<<"\n";
cout<< "\nF2.M = "<<f2.M(1,1);cout<< "\nF2.P = "<<f2.p(1);
Frame f3 = f1*f2;
Twist t1;
Twist t2(v1,v2);
Twist t3 = Twist::Zero();
double vx = t2.vel.x();
cout<< "\n VX = "<< vx <<"\n";
Wrench w1(v1,v2);
Wrench w2 = Wrench::Zero();
Wrench w3 = w1+w2;
double wx = w3.force.x();
cout<< "\n WX = "<< wx <<"\n";
std::string s1;
n.param<std::string>("my_Pa", s1, "Hey this is it!");
ROS_INFO("Got it! %s", s1.c_str());
std::string s;
/*
if (n.getParam("my_Pa", s) ) {
ROS_INFO("Got it! %s", s.c_str());
}
else{
ROS_ERROR("Failed haha!!!");
}*/
int count = 0;
while (ros::ok())
{
std_msgs::String msg;
std::stringstream ss;
ss << "hello world "<<count;
//msg.data = ss.str();
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
//joint_msg_pub.publish(joint_pos);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
| [
"a.ghalamzanesfahani@bham.ac.uk"
] | a.ghalamzanesfahani@bham.ac.uk |
f82f0b62f054b20d694f98805b5d801e450731be | c98af810bfd9e27087b155f3ef54b87e9f1f4bb8 | /src/common/PackedGLEnums_autogen.cpp | be0d8801a2862befe9f4b9b165d5fe5d835de376 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | syberia-project/platform_external_angle | 4b1c75166041b54b07eca0e490f55cdc577bf780 | 56563a9bee7a7e04ec365ff07aeb8b5fb34a6550 | refs/heads/10.0 | 2022-12-09T17:50:36.809226 | 2020-09-03T12:03:44 | 2020-09-03T12:03:44 | 262,032,296 | 2 | 1 | NOASSERTION | 2020-06-24T15:23:32 | 2020-05-07T11:31:38 | C++ | UTF-8 | C++ | false | false | 65,838 | cpp | // GENERATED FILE - DO NOT EDIT.
// Generated by gen_packed_gl_enums.py using data from packed_gl_enums.json.
//
// Copyright 2020 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// PackedGLEnums_autogen.cpp:
// Implements ANGLE-specific enums classes for GLenums and functions operating
// on them.
#include "common/PackedGLEnums_autogen.h"
#include "common/debug.h"
namespace gl
{
template <>
AlphaTestFunc FromGLenum<AlphaTestFunc>(GLenum from)
{
switch (from)
{
case GL_ALWAYS:
return AlphaTestFunc::AlwaysPass;
case GL_EQUAL:
return AlphaTestFunc::Equal;
case GL_GEQUAL:
return AlphaTestFunc::Gequal;
case GL_GREATER:
return AlphaTestFunc::Greater;
case GL_LEQUAL:
return AlphaTestFunc::Lequal;
case GL_LESS:
return AlphaTestFunc::Less;
case GL_NEVER:
return AlphaTestFunc::Never;
case GL_NOTEQUAL:
return AlphaTestFunc::NotEqual;
default:
return AlphaTestFunc::InvalidEnum;
}
}
GLenum ToGLenum(AlphaTestFunc from)
{
switch (from)
{
case AlphaTestFunc::AlwaysPass:
return GL_ALWAYS;
case AlphaTestFunc::Equal:
return GL_EQUAL;
case AlphaTestFunc::Gequal:
return GL_GEQUAL;
case AlphaTestFunc::Greater:
return GL_GREATER;
case AlphaTestFunc::Lequal:
return GL_LEQUAL;
case AlphaTestFunc::Less:
return GL_LESS;
case AlphaTestFunc::Never:
return GL_NEVER;
case AlphaTestFunc::NotEqual:
return GL_NOTEQUAL;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, AlphaTestFunc value)
{
switch (value)
{
case AlphaTestFunc::AlwaysPass:
os << "GL_ALWAYS";
break;
case AlphaTestFunc::Equal:
os << "GL_EQUAL";
break;
case AlphaTestFunc::Gequal:
os << "GL_GEQUAL";
break;
case AlphaTestFunc::Greater:
os << "GL_GREATER";
break;
case AlphaTestFunc::Lequal:
os << "GL_LEQUAL";
break;
case AlphaTestFunc::Less:
os << "GL_LESS";
break;
case AlphaTestFunc::Never:
os << "GL_NEVER";
break;
case AlphaTestFunc::NotEqual:
os << "GL_NOTEQUAL";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
BufferBinding FromGLenum<BufferBinding>(GLenum from)
{
switch (from)
{
case GL_ARRAY_BUFFER:
return BufferBinding::Array;
case GL_ATOMIC_COUNTER_BUFFER:
return BufferBinding::AtomicCounter;
case GL_COPY_READ_BUFFER:
return BufferBinding::CopyRead;
case GL_COPY_WRITE_BUFFER:
return BufferBinding::CopyWrite;
case GL_DISPATCH_INDIRECT_BUFFER:
return BufferBinding::DispatchIndirect;
case GL_DRAW_INDIRECT_BUFFER:
return BufferBinding::DrawIndirect;
case GL_ELEMENT_ARRAY_BUFFER:
return BufferBinding::ElementArray;
case GL_PIXEL_PACK_BUFFER:
return BufferBinding::PixelPack;
case GL_PIXEL_UNPACK_BUFFER:
return BufferBinding::PixelUnpack;
case GL_SHADER_STORAGE_BUFFER:
return BufferBinding::ShaderStorage;
case GL_TRANSFORM_FEEDBACK_BUFFER:
return BufferBinding::TransformFeedback;
case GL_UNIFORM_BUFFER:
return BufferBinding::Uniform;
default:
return BufferBinding::InvalidEnum;
}
}
GLenum ToGLenum(BufferBinding from)
{
switch (from)
{
case BufferBinding::Array:
return GL_ARRAY_BUFFER;
case BufferBinding::AtomicCounter:
return GL_ATOMIC_COUNTER_BUFFER;
case BufferBinding::CopyRead:
return GL_COPY_READ_BUFFER;
case BufferBinding::CopyWrite:
return GL_COPY_WRITE_BUFFER;
case BufferBinding::DispatchIndirect:
return GL_DISPATCH_INDIRECT_BUFFER;
case BufferBinding::DrawIndirect:
return GL_DRAW_INDIRECT_BUFFER;
case BufferBinding::ElementArray:
return GL_ELEMENT_ARRAY_BUFFER;
case BufferBinding::PixelPack:
return GL_PIXEL_PACK_BUFFER;
case BufferBinding::PixelUnpack:
return GL_PIXEL_UNPACK_BUFFER;
case BufferBinding::ShaderStorage:
return GL_SHADER_STORAGE_BUFFER;
case BufferBinding::TransformFeedback:
return GL_TRANSFORM_FEEDBACK_BUFFER;
case BufferBinding::Uniform:
return GL_UNIFORM_BUFFER;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, BufferBinding value)
{
switch (value)
{
case BufferBinding::Array:
os << "GL_ARRAY_BUFFER";
break;
case BufferBinding::AtomicCounter:
os << "GL_ATOMIC_COUNTER_BUFFER";
break;
case BufferBinding::CopyRead:
os << "GL_COPY_READ_BUFFER";
break;
case BufferBinding::CopyWrite:
os << "GL_COPY_WRITE_BUFFER";
break;
case BufferBinding::DispatchIndirect:
os << "GL_DISPATCH_INDIRECT_BUFFER";
break;
case BufferBinding::DrawIndirect:
os << "GL_DRAW_INDIRECT_BUFFER";
break;
case BufferBinding::ElementArray:
os << "GL_ELEMENT_ARRAY_BUFFER";
break;
case BufferBinding::PixelPack:
os << "GL_PIXEL_PACK_BUFFER";
break;
case BufferBinding::PixelUnpack:
os << "GL_PIXEL_UNPACK_BUFFER";
break;
case BufferBinding::ShaderStorage:
os << "GL_SHADER_STORAGE_BUFFER";
break;
case BufferBinding::TransformFeedback:
os << "GL_TRANSFORM_FEEDBACK_BUFFER";
break;
case BufferBinding::Uniform:
os << "GL_UNIFORM_BUFFER";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
BufferUsage FromGLenum<BufferUsage>(GLenum from)
{
switch (from)
{
case GL_DYNAMIC_COPY:
return BufferUsage::DynamicCopy;
case GL_DYNAMIC_DRAW:
return BufferUsage::DynamicDraw;
case GL_DYNAMIC_READ:
return BufferUsage::DynamicRead;
case GL_STATIC_COPY:
return BufferUsage::StaticCopy;
case GL_STATIC_DRAW:
return BufferUsage::StaticDraw;
case GL_STATIC_READ:
return BufferUsage::StaticRead;
case GL_STREAM_COPY:
return BufferUsage::StreamCopy;
case GL_STREAM_DRAW:
return BufferUsage::StreamDraw;
case GL_STREAM_READ:
return BufferUsage::StreamRead;
default:
return BufferUsage::InvalidEnum;
}
}
GLenum ToGLenum(BufferUsage from)
{
switch (from)
{
case BufferUsage::DynamicCopy:
return GL_DYNAMIC_COPY;
case BufferUsage::DynamicDraw:
return GL_DYNAMIC_DRAW;
case BufferUsage::DynamicRead:
return GL_DYNAMIC_READ;
case BufferUsage::StaticCopy:
return GL_STATIC_COPY;
case BufferUsage::StaticDraw:
return GL_STATIC_DRAW;
case BufferUsage::StaticRead:
return GL_STATIC_READ;
case BufferUsage::StreamCopy:
return GL_STREAM_COPY;
case BufferUsage::StreamDraw:
return GL_STREAM_DRAW;
case BufferUsage::StreamRead:
return GL_STREAM_READ;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, BufferUsage value)
{
switch (value)
{
case BufferUsage::DynamicCopy:
os << "GL_DYNAMIC_COPY";
break;
case BufferUsage::DynamicDraw:
os << "GL_DYNAMIC_DRAW";
break;
case BufferUsage::DynamicRead:
os << "GL_DYNAMIC_READ";
break;
case BufferUsage::StaticCopy:
os << "GL_STATIC_COPY";
break;
case BufferUsage::StaticDraw:
os << "GL_STATIC_DRAW";
break;
case BufferUsage::StaticRead:
os << "GL_STATIC_READ";
break;
case BufferUsage::StreamCopy:
os << "GL_STREAM_COPY";
break;
case BufferUsage::StreamDraw:
os << "GL_STREAM_DRAW";
break;
case BufferUsage::StreamRead:
os << "GL_STREAM_READ";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
ClientVertexArrayType FromGLenum<ClientVertexArrayType>(GLenum from)
{
switch (from)
{
case GL_COLOR_ARRAY:
return ClientVertexArrayType::Color;
case GL_NORMAL_ARRAY:
return ClientVertexArrayType::Normal;
case GL_POINT_SIZE_ARRAY_OES:
return ClientVertexArrayType::PointSize;
case GL_TEXTURE_COORD_ARRAY:
return ClientVertexArrayType::TextureCoord;
case GL_VERTEX_ARRAY:
return ClientVertexArrayType::Vertex;
default:
return ClientVertexArrayType::InvalidEnum;
}
}
GLenum ToGLenum(ClientVertexArrayType from)
{
switch (from)
{
case ClientVertexArrayType::Color:
return GL_COLOR_ARRAY;
case ClientVertexArrayType::Normal:
return GL_NORMAL_ARRAY;
case ClientVertexArrayType::PointSize:
return GL_POINT_SIZE_ARRAY_OES;
case ClientVertexArrayType::TextureCoord:
return GL_TEXTURE_COORD_ARRAY;
case ClientVertexArrayType::Vertex:
return GL_VERTEX_ARRAY;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, ClientVertexArrayType value)
{
switch (value)
{
case ClientVertexArrayType::Color:
os << "GL_COLOR_ARRAY";
break;
case ClientVertexArrayType::Normal:
os << "GL_NORMAL_ARRAY";
break;
case ClientVertexArrayType::PointSize:
os << "GL_POINT_SIZE_ARRAY_OES";
break;
case ClientVertexArrayType::TextureCoord:
os << "GL_TEXTURE_COORD_ARRAY";
break;
case ClientVertexArrayType::Vertex:
os << "GL_VERTEX_ARRAY";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
CullFaceMode FromGLenum<CullFaceMode>(GLenum from)
{
switch (from)
{
case GL_BACK:
return CullFaceMode::Back;
case GL_FRONT:
return CullFaceMode::Front;
case GL_FRONT_AND_BACK:
return CullFaceMode::FrontAndBack;
default:
return CullFaceMode::InvalidEnum;
}
}
GLenum ToGLenum(CullFaceMode from)
{
switch (from)
{
case CullFaceMode::Back:
return GL_BACK;
case CullFaceMode::Front:
return GL_FRONT;
case CullFaceMode::FrontAndBack:
return GL_FRONT_AND_BACK;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, CullFaceMode value)
{
switch (value)
{
case CullFaceMode::Back:
os << "GL_BACK";
break;
case CullFaceMode::Front:
os << "GL_FRONT";
break;
case CullFaceMode::FrontAndBack:
os << "GL_FRONT_AND_BACK";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
FilterMode FromGLenum<FilterMode>(GLenum from)
{
switch (from)
{
case GL_NEAREST:
return FilterMode::Nearest;
case GL_LINEAR:
return FilterMode::Linear;
case GL_NEAREST_MIPMAP_NEAREST:
return FilterMode::NearestMipmapNearest;
case GL_NEAREST_MIPMAP_LINEAR:
return FilterMode::NearestMipmapLinear;
case GL_LINEAR_MIPMAP_LINEAR:
return FilterMode::LinearMipmapLinear;
default:
return FilterMode::InvalidEnum;
}
}
GLenum ToGLenum(FilterMode from)
{
switch (from)
{
case FilterMode::Nearest:
return GL_NEAREST;
case FilterMode::Linear:
return GL_LINEAR;
case FilterMode::NearestMipmapNearest:
return GL_NEAREST_MIPMAP_NEAREST;
case FilterMode::NearestMipmapLinear:
return GL_NEAREST_MIPMAP_LINEAR;
case FilterMode::LinearMipmapLinear:
return GL_LINEAR_MIPMAP_LINEAR;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, FilterMode value)
{
switch (value)
{
case FilterMode::Nearest:
os << "GL_NEAREST";
break;
case FilterMode::Linear:
os << "GL_LINEAR";
break;
case FilterMode::NearestMipmapNearest:
os << "GL_NEAREST_MIPMAP_NEAREST";
break;
case FilterMode::NearestMipmapLinear:
os << "GL_NEAREST_MIPMAP_LINEAR";
break;
case FilterMode::LinearMipmapLinear:
os << "GL_LINEAR_MIPMAP_LINEAR";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
FogMode FromGLenum<FogMode>(GLenum from)
{
switch (from)
{
case GL_EXP:
return FogMode::Exp;
case GL_EXP2:
return FogMode::Exp2;
case GL_LINEAR:
return FogMode::Linear;
default:
return FogMode::InvalidEnum;
}
}
GLenum ToGLenum(FogMode from)
{
switch (from)
{
case FogMode::Exp:
return GL_EXP;
case FogMode::Exp2:
return GL_EXP2;
case FogMode::Linear:
return GL_LINEAR;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, FogMode value)
{
switch (value)
{
case FogMode::Exp:
os << "GL_EXP";
break;
case FogMode::Exp2:
os << "GL_EXP2";
break;
case FogMode::Linear:
os << "GL_LINEAR";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
GraphicsResetStatus FromGLenum<GraphicsResetStatus>(GLenum from)
{
switch (from)
{
case GL_NO_ERROR:
return GraphicsResetStatus::NoError;
case GL_GUILTY_CONTEXT_RESET:
return GraphicsResetStatus::GuiltyContextReset;
case GL_INNOCENT_CONTEXT_RESET:
return GraphicsResetStatus::InnocentContextReset;
case GL_UNKNOWN_CONTEXT_RESET:
return GraphicsResetStatus::UnknownContextReset;
default:
return GraphicsResetStatus::InvalidEnum;
}
}
GLenum ToGLenum(GraphicsResetStatus from)
{
switch (from)
{
case GraphicsResetStatus::NoError:
return GL_NO_ERROR;
case GraphicsResetStatus::GuiltyContextReset:
return GL_GUILTY_CONTEXT_RESET;
case GraphicsResetStatus::InnocentContextReset:
return GL_INNOCENT_CONTEXT_RESET;
case GraphicsResetStatus::UnknownContextReset:
return GL_UNKNOWN_CONTEXT_RESET;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, GraphicsResetStatus value)
{
switch (value)
{
case GraphicsResetStatus::NoError:
os << "GL_NO_ERROR";
break;
case GraphicsResetStatus::GuiltyContextReset:
os << "GL_GUILTY_CONTEXT_RESET";
break;
case GraphicsResetStatus::InnocentContextReset:
os << "GL_INNOCENT_CONTEXT_RESET";
break;
case GraphicsResetStatus::UnknownContextReset:
os << "GL_UNKNOWN_CONTEXT_RESET";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
HandleType FromGLenum<HandleType>(GLenum from)
{
switch (from)
{
case GL_HANDLE_TYPE_OPAQUE_FD_EXT:
return HandleType::OpaqueFd;
case GL_HANDLE_TYPE_ZIRCON_VMO_ANGLE:
return HandleType::ZirconVmo;
case GL_HANDLE_TYPE_ZIRCON_EVENT_ANGLE:
return HandleType::ZirconEvent;
default:
return HandleType::InvalidEnum;
}
}
GLenum ToGLenum(HandleType from)
{
switch (from)
{
case HandleType::OpaqueFd:
return GL_HANDLE_TYPE_OPAQUE_FD_EXT;
case HandleType::ZirconVmo:
return GL_HANDLE_TYPE_ZIRCON_VMO_ANGLE;
case HandleType::ZirconEvent:
return GL_HANDLE_TYPE_ZIRCON_EVENT_ANGLE;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, HandleType value)
{
switch (value)
{
case HandleType::OpaqueFd:
os << "GL_HANDLE_TYPE_OPAQUE_FD_EXT";
break;
case HandleType::ZirconVmo:
os << "GL_HANDLE_TYPE_ZIRCON_VMO_ANGLE";
break;
case HandleType::ZirconEvent:
os << "GL_HANDLE_TYPE_ZIRCON_EVENT_ANGLE";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
HintSetting FromGLenum<HintSetting>(GLenum from)
{
switch (from)
{
case GL_DONT_CARE:
return HintSetting::DontCare;
case GL_FASTEST:
return HintSetting::Fastest;
case GL_NICEST:
return HintSetting::Nicest;
default:
return HintSetting::InvalidEnum;
}
}
GLenum ToGLenum(HintSetting from)
{
switch (from)
{
case HintSetting::DontCare:
return GL_DONT_CARE;
case HintSetting::Fastest:
return GL_FASTEST;
case HintSetting::Nicest:
return GL_NICEST;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, HintSetting value)
{
switch (value)
{
case HintSetting::DontCare:
os << "GL_DONT_CARE";
break;
case HintSetting::Fastest:
os << "GL_FASTEST";
break;
case HintSetting::Nicest:
os << "GL_NICEST";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
ImageLayout FromGLenum<ImageLayout>(GLenum from)
{
switch (from)
{
case GL_NONE:
return ImageLayout::Undefined;
case GL_LAYOUT_GENERAL_EXT:
return ImageLayout::General;
case GL_LAYOUT_COLOR_ATTACHMENT_EXT:
return ImageLayout::ColorAttachment;
case GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT:
return ImageLayout::DepthStencilAttachment;
case GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT:
return ImageLayout::DepthStencilReadOnlyAttachment;
case GL_LAYOUT_SHADER_READ_ONLY_EXT:
return ImageLayout::ShaderReadOnly;
case GL_LAYOUT_TRANSFER_SRC_EXT:
return ImageLayout::TransferSrc;
case GL_LAYOUT_TRANSFER_DST_EXT:
return ImageLayout::TransferDst;
case GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT:
return ImageLayout::DepthReadOnlyStencilAttachment;
case GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT:
return ImageLayout::DepthAttachmentStencilReadOnly;
default:
return ImageLayout::InvalidEnum;
}
}
GLenum ToGLenum(ImageLayout from)
{
switch (from)
{
case ImageLayout::Undefined:
return GL_NONE;
case ImageLayout::General:
return GL_LAYOUT_GENERAL_EXT;
case ImageLayout::ColorAttachment:
return GL_LAYOUT_COLOR_ATTACHMENT_EXT;
case ImageLayout::DepthStencilAttachment:
return GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT;
case ImageLayout::DepthStencilReadOnlyAttachment:
return GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT;
case ImageLayout::ShaderReadOnly:
return GL_LAYOUT_SHADER_READ_ONLY_EXT;
case ImageLayout::TransferSrc:
return GL_LAYOUT_TRANSFER_SRC_EXT;
case ImageLayout::TransferDst:
return GL_LAYOUT_TRANSFER_DST_EXT;
case ImageLayout::DepthReadOnlyStencilAttachment:
return GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT;
case ImageLayout::DepthAttachmentStencilReadOnly:
return GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, ImageLayout value)
{
switch (value)
{
case ImageLayout::Undefined:
os << "GL_NONE";
break;
case ImageLayout::General:
os << "GL_LAYOUT_GENERAL_EXT";
break;
case ImageLayout::ColorAttachment:
os << "GL_LAYOUT_COLOR_ATTACHMENT_EXT";
break;
case ImageLayout::DepthStencilAttachment:
os << "GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT";
break;
case ImageLayout::DepthStencilReadOnlyAttachment:
os << "GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT";
break;
case ImageLayout::ShaderReadOnly:
os << "GL_LAYOUT_SHADER_READ_ONLY_EXT";
break;
case ImageLayout::TransferSrc:
os << "GL_LAYOUT_TRANSFER_SRC_EXT";
break;
case ImageLayout::TransferDst:
os << "GL_LAYOUT_TRANSFER_DST_EXT";
break;
case ImageLayout::DepthReadOnlyStencilAttachment:
os << "GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT";
break;
case ImageLayout::DepthAttachmentStencilReadOnly:
os << "GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
LightParameter FromGLenum<LightParameter>(GLenum from)
{
switch (from)
{
case GL_AMBIENT:
return LightParameter::Ambient;
case GL_AMBIENT_AND_DIFFUSE:
return LightParameter::AmbientAndDiffuse;
case GL_CONSTANT_ATTENUATION:
return LightParameter::ConstantAttenuation;
case GL_DIFFUSE:
return LightParameter::Diffuse;
case GL_LINEAR_ATTENUATION:
return LightParameter::LinearAttenuation;
case GL_POSITION:
return LightParameter::Position;
case GL_QUADRATIC_ATTENUATION:
return LightParameter::QuadraticAttenuation;
case GL_SPECULAR:
return LightParameter::Specular;
case GL_SPOT_CUTOFF:
return LightParameter::SpotCutoff;
case GL_SPOT_DIRECTION:
return LightParameter::SpotDirection;
case GL_SPOT_EXPONENT:
return LightParameter::SpotExponent;
default:
return LightParameter::InvalidEnum;
}
}
GLenum ToGLenum(LightParameter from)
{
switch (from)
{
case LightParameter::Ambient:
return GL_AMBIENT;
case LightParameter::AmbientAndDiffuse:
return GL_AMBIENT_AND_DIFFUSE;
case LightParameter::ConstantAttenuation:
return GL_CONSTANT_ATTENUATION;
case LightParameter::Diffuse:
return GL_DIFFUSE;
case LightParameter::LinearAttenuation:
return GL_LINEAR_ATTENUATION;
case LightParameter::Position:
return GL_POSITION;
case LightParameter::QuadraticAttenuation:
return GL_QUADRATIC_ATTENUATION;
case LightParameter::Specular:
return GL_SPECULAR;
case LightParameter::SpotCutoff:
return GL_SPOT_CUTOFF;
case LightParameter::SpotDirection:
return GL_SPOT_DIRECTION;
case LightParameter::SpotExponent:
return GL_SPOT_EXPONENT;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, LightParameter value)
{
switch (value)
{
case LightParameter::Ambient:
os << "GL_AMBIENT";
break;
case LightParameter::AmbientAndDiffuse:
os << "GL_AMBIENT_AND_DIFFUSE";
break;
case LightParameter::ConstantAttenuation:
os << "GL_CONSTANT_ATTENUATION";
break;
case LightParameter::Diffuse:
os << "GL_DIFFUSE";
break;
case LightParameter::LinearAttenuation:
os << "GL_LINEAR_ATTENUATION";
break;
case LightParameter::Position:
os << "GL_POSITION";
break;
case LightParameter::QuadraticAttenuation:
os << "GL_QUADRATIC_ATTENUATION";
break;
case LightParameter::Specular:
os << "GL_SPECULAR";
break;
case LightParameter::SpotCutoff:
os << "GL_SPOT_CUTOFF";
break;
case LightParameter::SpotDirection:
os << "GL_SPOT_DIRECTION";
break;
case LightParameter::SpotExponent:
os << "GL_SPOT_EXPONENT";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
LogicalOperation FromGLenum<LogicalOperation>(GLenum from)
{
switch (from)
{
case GL_AND:
return LogicalOperation::And;
case GL_AND_INVERTED:
return LogicalOperation::AndInverted;
case GL_AND_REVERSE:
return LogicalOperation::AndReverse;
case GL_CLEAR:
return LogicalOperation::Clear;
case GL_COPY:
return LogicalOperation::Copy;
case GL_COPY_INVERTED:
return LogicalOperation::CopyInverted;
case GL_EQUIV:
return LogicalOperation::Equiv;
case GL_INVERT:
return LogicalOperation::Invert;
case GL_NAND:
return LogicalOperation::Nand;
case GL_NOOP:
return LogicalOperation::Noop;
case GL_NOR:
return LogicalOperation::Nor;
case GL_OR:
return LogicalOperation::Or;
case GL_OR_INVERTED:
return LogicalOperation::OrInverted;
case GL_OR_REVERSE:
return LogicalOperation::OrReverse;
case GL_SET:
return LogicalOperation::Set;
case GL_XOR:
return LogicalOperation::Xor;
default:
return LogicalOperation::InvalidEnum;
}
}
GLenum ToGLenum(LogicalOperation from)
{
switch (from)
{
case LogicalOperation::And:
return GL_AND;
case LogicalOperation::AndInverted:
return GL_AND_INVERTED;
case LogicalOperation::AndReverse:
return GL_AND_REVERSE;
case LogicalOperation::Clear:
return GL_CLEAR;
case LogicalOperation::Copy:
return GL_COPY;
case LogicalOperation::CopyInverted:
return GL_COPY_INVERTED;
case LogicalOperation::Equiv:
return GL_EQUIV;
case LogicalOperation::Invert:
return GL_INVERT;
case LogicalOperation::Nand:
return GL_NAND;
case LogicalOperation::Noop:
return GL_NOOP;
case LogicalOperation::Nor:
return GL_NOR;
case LogicalOperation::Or:
return GL_OR;
case LogicalOperation::OrInverted:
return GL_OR_INVERTED;
case LogicalOperation::OrReverse:
return GL_OR_REVERSE;
case LogicalOperation::Set:
return GL_SET;
case LogicalOperation::Xor:
return GL_XOR;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, LogicalOperation value)
{
switch (value)
{
case LogicalOperation::And:
os << "GL_AND";
break;
case LogicalOperation::AndInverted:
os << "GL_AND_INVERTED";
break;
case LogicalOperation::AndReverse:
os << "GL_AND_REVERSE";
break;
case LogicalOperation::Clear:
os << "GL_CLEAR";
break;
case LogicalOperation::Copy:
os << "GL_COPY";
break;
case LogicalOperation::CopyInverted:
os << "GL_COPY_INVERTED";
break;
case LogicalOperation::Equiv:
os << "GL_EQUIV";
break;
case LogicalOperation::Invert:
os << "GL_INVERT";
break;
case LogicalOperation::Nand:
os << "GL_NAND";
break;
case LogicalOperation::Noop:
os << "GL_NOOP";
break;
case LogicalOperation::Nor:
os << "GL_NOR";
break;
case LogicalOperation::Or:
os << "GL_OR";
break;
case LogicalOperation::OrInverted:
os << "GL_OR_INVERTED";
break;
case LogicalOperation::OrReverse:
os << "GL_OR_REVERSE";
break;
case LogicalOperation::Set:
os << "GL_SET";
break;
case LogicalOperation::Xor:
os << "GL_XOR";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
MaterialParameter FromGLenum<MaterialParameter>(GLenum from)
{
switch (from)
{
case GL_AMBIENT:
return MaterialParameter::Ambient;
case GL_AMBIENT_AND_DIFFUSE:
return MaterialParameter::AmbientAndDiffuse;
case GL_DIFFUSE:
return MaterialParameter::Diffuse;
case GL_EMISSION:
return MaterialParameter::Emission;
case GL_SHININESS:
return MaterialParameter::Shininess;
case GL_SPECULAR:
return MaterialParameter::Specular;
default:
return MaterialParameter::InvalidEnum;
}
}
GLenum ToGLenum(MaterialParameter from)
{
switch (from)
{
case MaterialParameter::Ambient:
return GL_AMBIENT;
case MaterialParameter::AmbientAndDiffuse:
return GL_AMBIENT_AND_DIFFUSE;
case MaterialParameter::Diffuse:
return GL_DIFFUSE;
case MaterialParameter::Emission:
return GL_EMISSION;
case MaterialParameter::Shininess:
return GL_SHININESS;
case MaterialParameter::Specular:
return GL_SPECULAR;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, MaterialParameter value)
{
switch (value)
{
case MaterialParameter::Ambient:
os << "GL_AMBIENT";
break;
case MaterialParameter::AmbientAndDiffuse:
os << "GL_AMBIENT_AND_DIFFUSE";
break;
case MaterialParameter::Diffuse:
os << "GL_DIFFUSE";
break;
case MaterialParameter::Emission:
os << "GL_EMISSION";
break;
case MaterialParameter::Shininess:
os << "GL_SHININESS";
break;
case MaterialParameter::Specular:
os << "GL_SPECULAR";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
MatrixType FromGLenum<MatrixType>(GLenum from)
{
switch (from)
{
case GL_MODELVIEW:
return MatrixType::Modelview;
case GL_PROJECTION:
return MatrixType::Projection;
case GL_TEXTURE:
return MatrixType::Texture;
default:
return MatrixType::InvalidEnum;
}
}
GLenum ToGLenum(MatrixType from)
{
switch (from)
{
case MatrixType::Modelview:
return GL_MODELVIEW;
case MatrixType::Projection:
return GL_PROJECTION;
case MatrixType::Texture:
return GL_TEXTURE;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, MatrixType value)
{
switch (value)
{
case MatrixType::Modelview:
os << "GL_MODELVIEW";
break;
case MatrixType::Projection:
os << "GL_PROJECTION";
break;
case MatrixType::Texture:
os << "GL_TEXTURE";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
PointParameter FromGLenum<PointParameter>(GLenum from)
{
switch (from)
{
case GL_POINT_SIZE_MIN:
return PointParameter::PointSizeMin;
case GL_POINT_SIZE_MAX:
return PointParameter::PointSizeMax;
case GL_POINT_FADE_THRESHOLD_SIZE:
return PointParameter::PointFadeThresholdSize;
case GL_POINT_DISTANCE_ATTENUATION:
return PointParameter::PointDistanceAttenuation;
default:
return PointParameter::InvalidEnum;
}
}
GLenum ToGLenum(PointParameter from)
{
switch (from)
{
case PointParameter::PointSizeMin:
return GL_POINT_SIZE_MIN;
case PointParameter::PointSizeMax:
return GL_POINT_SIZE_MAX;
case PointParameter::PointFadeThresholdSize:
return GL_POINT_FADE_THRESHOLD_SIZE;
case PointParameter::PointDistanceAttenuation:
return GL_POINT_DISTANCE_ATTENUATION;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, PointParameter value)
{
switch (value)
{
case PointParameter::PointSizeMin:
os << "GL_POINT_SIZE_MIN";
break;
case PointParameter::PointSizeMax:
os << "GL_POINT_SIZE_MAX";
break;
case PointParameter::PointFadeThresholdSize:
os << "GL_POINT_FADE_THRESHOLD_SIZE";
break;
case PointParameter::PointDistanceAttenuation:
os << "GL_POINT_DISTANCE_ATTENUATION";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
ProvokingVertexConvention FromGLenum<ProvokingVertexConvention>(GLenum from)
{
switch (from)
{
case GL_FIRST_VERTEX_CONVENTION:
return ProvokingVertexConvention::FirstVertexConvention;
case GL_LAST_VERTEX_CONVENTION:
return ProvokingVertexConvention::LastVertexConvention;
default:
return ProvokingVertexConvention::InvalidEnum;
}
}
GLenum ToGLenum(ProvokingVertexConvention from)
{
switch (from)
{
case ProvokingVertexConvention::FirstVertexConvention:
return GL_FIRST_VERTEX_CONVENTION;
case ProvokingVertexConvention::LastVertexConvention:
return GL_LAST_VERTEX_CONVENTION;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, ProvokingVertexConvention value)
{
switch (value)
{
case ProvokingVertexConvention::FirstVertexConvention:
os << "GL_FIRST_VERTEX_CONVENTION";
break;
case ProvokingVertexConvention::LastVertexConvention:
os << "GL_LAST_VERTEX_CONVENTION";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
QueryType FromGLenum<QueryType>(GLenum from)
{
switch (from)
{
case GL_ANY_SAMPLES_PASSED:
return QueryType::AnySamples;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
return QueryType::AnySamplesConservative;
case GL_COMMANDS_COMPLETED_CHROMIUM:
return QueryType::CommandsCompleted;
case GL_PRIMITIVES_GENERATED_EXT:
return QueryType::PrimitivesGenerated;
case GL_TIME_ELAPSED_EXT:
return QueryType::TimeElapsed;
case GL_TIMESTAMP_EXT:
return QueryType::Timestamp;
case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
return QueryType::TransformFeedbackPrimitivesWritten;
default:
return QueryType::InvalidEnum;
}
}
GLenum ToGLenum(QueryType from)
{
switch (from)
{
case QueryType::AnySamples:
return GL_ANY_SAMPLES_PASSED;
case QueryType::AnySamplesConservative:
return GL_ANY_SAMPLES_PASSED_CONSERVATIVE;
case QueryType::CommandsCompleted:
return GL_COMMANDS_COMPLETED_CHROMIUM;
case QueryType::PrimitivesGenerated:
return GL_PRIMITIVES_GENERATED_EXT;
case QueryType::TimeElapsed:
return GL_TIME_ELAPSED_EXT;
case QueryType::Timestamp:
return GL_TIMESTAMP_EXT;
case QueryType::TransformFeedbackPrimitivesWritten:
return GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, QueryType value)
{
switch (value)
{
case QueryType::AnySamples:
os << "GL_ANY_SAMPLES_PASSED";
break;
case QueryType::AnySamplesConservative:
os << "GL_ANY_SAMPLES_PASSED_CONSERVATIVE";
break;
case QueryType::CommandsCompleted:
os << "GL_COMMANDS_COMPLETED_CHROMIUM";
break;
case QueryType::PrimitivesGenerated:
os << "GL_PRIMITIVES_GENERATED_EXT";
break;
case QueryType::TimeElapsed:
os << "GL_TIME_ELAPSED_EXT";
break;
case QueryType::Timestamp:
os << "GL_TIMESTAMP_EXT";
break;
case QueryType::TransformFeedbackPrimitivesWritten:
os << "GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
ShaderType FromGLenum<ShaderType>(GLenum from)
{
switch (from)
{
case GL_VERTEX_SHADER:
return ShaderType::Vertex;
case GL_FRAGMENT_SHADER:
return ShaderType::Fragment;
case GL_GEOMETRY_SHADER_EXT:
return ShaderType::Geometry;
case GL_COMPUTE_SHADER:
return ShaderType::Compute;
default:
return ShaderType::InvalidEnum;
}
}
GLenum ToGLenum(ShaderType from)
{
switch (from)
{
case ShaderType::Vertex:
return GL_VERTEX_SHADER;
case ShaderType::Fragment:
return GL_FRAGMENT_SHADER;
case ShaderType::Geometry:
return GL_GEOMETRY_SHADER_EXT;
case ShaderType::Compute:
return GL_COMPUTE_SHADER;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, ShaderType value)
{
switch (value)
{
case ShaderType::Vertex:
os << "GL_VERTEX_SHADER";
break;
case ShaderType::Fragment:
os << "GL_FRAGMENT_SHADER";
break;
case ShaderType::Geometry:
os << "GL_GEOMETRY_SHADER_EXT";
break;
case ShaderType::Compute:
os << "GL_COMPUTE_SHADER";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
ShadingModel FromGLenum<ShadingModel>(GLenum from)
{
switch (from)
{
case GL_FLAT:
return ShadingModel::Flat;
case GL_SMOOTH:
return ShadingModel::Smooth;
default:
return ShadingModel::InvalidEnum;
}
}
GLenum ToGLenum(ShadingModel from)
{
switch (from)
{
case ShadingModel::Flat:
return GL_FLAT;
case ShadingModel::Smooth:
return GL_SMOOTH;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, ShadingModel value)
{
switch (value)
{
case ShadingModel::Flat:
os << "GL_FLAT";
break;
case ShadingModel::Smooth:
os << "GL_SMOOTH";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureCombine FromGLenum<TextureCombine>(GLenum from)
{
switch (from)
{
case GL_ADD:
return TextureCombine::Add;
case GL_ADD_SIGNED:
return TextureCombine::AddSigned;
case GL_DOT3_RGB:
return TextureCombine::Dot3Rgb;
case GL_DOT3_RGBA:
return TextureCombine::Dot3Rgba;
case GL_INTERPOLATE:
return TextureCombine::Interpolate;
case GL_MODULATE:
return TextureCombine::Modulate;
case GL_REPLACE:
return TextureCombine::Replace;
case GL_SUBTRACT:
return TextureCombine::Subtract;
default:
return TextureCombine::InvalidEnum;
}
}
GLenum ToGLenum(TextureCombine from)
{
switch (from)
{
case TextureCombine::Add:
return GL_ADD;
case TextureCombine::AddSigned:
return GL_ADD_SIGNED;
case TextureCombine::Dot3Rgb:
return GL_DOT3_RGB;
case TextureCombine::Dot3Rgba:
return GL_DOT3_RGBA;
case TextureCombine::Interpolate:
return GL_INTERPOLATE;
case TextureCombine::Modulate:
return GL_MODULATE;
case TextureCombine::Replace:
return GL_REPLACE;
case TextureCombine::Subtract:
return GL_SUBTRACT;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureCombine value)
{
switch (value)
{
case TextureCombine::Add:
os << "GL_ADD";
break;
case TextureCombine::AddSigned:
os << "GL_ADD_SIGNED";
break;
case TextureCombine::Dot3Rgb:
os << "GL_DOT3_RGB";
break;
case TextureCombine::Dot3Rgba:
os << "GL_DOT3_RGBA";
break;
case TextureCombine::Interpolate:
os << "GL_INTERPOLATE";
break;
case TextureCombine::Modulate:
os << "GL_MODULATE";
break;
case TextureCombine::Replace:
os << "GL_REPLACE";
break;
case TextureCombine::Subtract:
os << "GL_SUBTRACT";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureEnvMode FromGLenum<TextureEnvMode>(GLenum from)
{
switch (from)
{
case GL_ADD:
return TextureEnvMode::Add;
case GL_BLEND:
return TextureEnvMode::Blend;
case GL_COMBINE:
return TextureEnvMode::Combine;
case GL_DECAL:
return TextureEnvMode::Decal;
case GL_MODULATE:
return TextureEnvMode::Modulate;
case GL_REPLACE:
return TextureEnvMode::Replace;
default:
return TextureEnvMode::InvalidEnum;
}
}
GLenum ToGLenum(TextureEnvMode from)
{
switch (from)
{
case TextureEnvMode::Add:
return GL_ADD;
case TextureEnvMode::Blend:
return GL_BLEND;
case TextureEnvMode::Combine:
return GL_COMBINE;
case TextureEnvMode::Decal:
return GL_DECAL;
case TextureEnvMode::Modulate:
return GL_MODULATE;
case TextureEnvMode::Replace:
return GL_REPLACE;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureEnvMode value)
{
switch (value)
{
case TextureEnvMode::Add:
os << "GL_ADD";
break;
case TextureEnvMode::Blend:
os << "GL_BLEND";
break;
case TextureEnvMode::Combine:
os << "GL_COMBINE";
break;
case TextureEnvMode::Decal:
os << "GL_DECAL";
break;
case TextureEnvMode::Modulate:
os << "GL_MODULATE";
break;
case TextureEnvMode::Replace:
os << "GL_REPLACE";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureEnvParameter FromGLenum<TextureEnvParameter>(GLenum from)
{
switch (from)
{
case GL_TEXTURE_ENV_MODE:
return TextureEnvParameter::Mode;
case GL_TEXTURE_ENV_COLOR:
return TextureEnvParameter::Color;
case GL_COMBINE_RGB:
return TextureEnvParameter::CombineRgb;
case GL_COMBINE_ALPHA:
return TextureEnvParameter::CombineAlpha;
case GL_RGB_SCALE:
return TextureEnvParameter::RgbScale;
case GL_ALPHA_SCALE:
return TextureEnvParameter::AlphaScale;
case GL_SRC0_RGB:
return TextureEnvParameter::Src0Rgb;
case GL_SRC1_RGB:
return TextureEnvParameter::Src1Rgb;
case GL_SRC2_RGB:
return TextureEnvParameter::Src2Rgb;
case GL_SRC0_ALPHA:
return TextureEnvParameter::Src0Alpha;
case GL_SRC1_ALPHA:
return TextureEnvParameter::Src1Alpha;
case GL_SRC2_ALPHA:
return TextureEnvParameter::Src2Alpha;
case GL_OPERAND0_RGB:
return TextureEnvParameter::Op0Rgb;
case GL_OPERAND1_RGB:
return TextureEnvParameter::Op1Rgb;
case GL_OPERAND2_RGB:
return TextureEnvParameter::Op2Rgb;
case GL_OPERAND0_ALPHA:
return TextureEnvParameter::Op0Alpha;
case GL_OPERAND1_ALPHA:
return TextureEnvParameter::Op1Alpha;
case GL_OPERAND2_ALPHA:
return TextureEnvParameter::Op2Alpha;
case GL_COORD_REPLACE_OES:
return TextureEnvParameter::PointCoordReplace;
default:
return TextureEnvParameter::InvalidEnum;
}
}
GLenum ToGLenum(TextureEnvParameter from)
{
switch (from)
{
case TextureEnvParameter::Mode:
return GL_TEXTURE_ENV_MODE;
case TextureEnvParameter::Color:
return GL_TEXTURE_ENV_COLOR;
case TextureEnvParameter::CombineRgb:
return GL_COMBINE_RGB;
case TextureEnvParameter::CombineAlpha:
return GL_COMBINE_ALPHA;
case TextureEnvParameter::RgbScale:
return GL_RGB_SCALE;
case TextureEnvParameter::AlphaScale:
return GL_ALPHA_SCALE;
case TextureEnvParameter::Src0Rgb:
return GL_SRC0_RGB;
case TextureEnvParameter::Src1Rgb:
return GL_SRC1_RGB;
case TextureEnvParameter::Src2Rgb:
return GL_SRC2_RGB;
case TextureEnvParameter::Src0Alpha:
return GL_SRC0_ALPHA;
case TextureEnvParameter::Src1Alpha:
return GL_SRC1_ALPHA;
case TextureEnvParameter::Src2Alpha:
return GL_SRC2_ALPHA;
case TextureEnvParameter::Op0Rgb:
return GL_OPERAND0_RGB;
case TextureEnvParameter::Op1Rgb:
return GL_OPERAND1_RGB;
case TextureEnvParameter::Op2Rgb:
return GL_OPERAND2_RGB;
case TextureEnvParameter::Op0Alpha:
return GL_OPERAND0_ALPHA;
case TextureEnvParameter::Op1Alpha:
return GL_OPERAND1_ALPHA;
case TextureEnvParameter::Op2Alpha:
return GL_OPERAND2_ALPHA;
case TextureEnvParameter::PointCoordReplace:
return GL_COORD_REPLACE_OES;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureEnvParameter value)
{
switch (value)
{
case TextureEnvParameter::Mode:
os << "GL_TEXTURE_ENV_MODE";
break;
case TextureEnvParameter::Color:
os << "GL_TEXTURE_ENV_COLOR";
break;
case TextureEnvParameter::CombineRgb:
os << "GL_COMBINE_RGB";
break;
case TextureEnvParameter::CombineAlpha:
os << "GL_COMBINE_ALPHA";
break;
case TextureEnvParameter::RgbScale:
os << "GL_RGB_SCALE";
break;
case TextureEnvParameter::AlphaScale:
os << "GL_ALPHA_SCALE";
break;
case TextureEnvParameter::Src0Rgb:
os << "GL_SRC0_RGB";
break;
case TextureEnvParameter::Src1Rgb:
os << "GL_SRC1_RGB";
break;
case TextureEnvParameter::Src2Rgb:
os << "GL_SRC2_RGB";
break;
case TextureEnvParameter::Src0Alpha:
os << "GL_SRC0_ALPHA";
break;
case TextureEnvParameter::Src1Alpha:
os << "GL_SRC1_ALPHA";
break;
case TextureEnvParameter::Src2Alpha:
os << "GL_SRC2_ALPHA";
break;
case TextureEnvParameter::Op0Rgb:
os << "GL_OPERAND0_RGB";
break;
case TextureEnvParameter::Op1Rgb:
os << "GL_OPERAND1_RGB";
break;
case TextureEnvParameter::Op2Rgb:
os << "GL_OPERAND2_RGB";
break;
case TextureEnvParameter::Op0Alpha:
os << "GL_OPERAND0_ALPHA";
break;
case TextureEnvParameter::Op1Alpha:
os << "GL_OPERAND1_ALPHA";
break;
case TextureEnvParameter::Op2Alpha:
os << "GL_OPERAND2_ALPHA";
break;
case TextureEnvParameter::PointCoordReplace:
os << "GL_COORD_REPLACE_OES";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureEnvTarget FromGLenum<TextureEnvTarget>(GLenum from)
{
switch (from)
{
case GL_TEXTURE_ENV:
return TextureEnvTarget::Env;
case GL_POINT_SPRITE_OES:
return TextureEnvTarget::PointSprite;
default:
return TextureEnvTarget::InvalidEnum;
}
}
GLenum ToGLenum(TextureEnvTarget from)
{
switch (from)
{
case TextureEnvTarget::Env:
return GL_TEXTURE_ENV;
case TextureEnvTarget::PointSprite:
return GL_POINT_SPRITE_OES;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureEnvTarget value)
{
switch (value)
{
case TextureEnvTarget::Env:
os << "GL_TEXTURE_ENV";
break;
case TextureEnvTarget::PointSprite:
os << "GL_POINT_SPRITE_OES";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureOp FromGLenum<TextureOp>(GLenum from)
{
switch (from)
{
case GL_ONE_MINUS_SRC_ALPHA:
return TextureOp::OneMinusSrcAlpha;
case GL_ONE_MINUS_SRC_COLOR:
return TextureOp::OneMinusSrcColor;
case GL_SRC_ALPHA:
return TextureOp::SrcAlpha;
case GL_SRC_COLOR:
return TextureOp::SrcColor;
default:
return TextureOp::InvalidEnum;
}
}
GLenum ToGLenum(TextureOp from)
{
switch (from)
{
case TextureOp::OneMinusSrcAlpha:
return GL_ONE_MINUS_SRC_ALPHA;
case TextureOp::OneMinusSrcColor:
return GL_ONE_MINUS_SRC_COLOR;
case TextureOp::SrcAlpha:
return GL_SRC_ALPHA;
case TextureOp::SrcColor:
return GL_SRC_COLOR;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureOp value)
{
switch (value)
{
case TextureOp::OneMinusSrcAlpha:
os << "GL_ONE_MINUS_SRC_ALPHA";
break;
case TextureOp::OneMinusSrcColor:
os << "GL_ONE_MINUS_SRC_COLOR";
break;
case TextureOp::SrcAlpha:
os << "GL_SRC_ALPHA";
break;
case TextureOp::SrcColor:
os << "GL_SRC_COLOR";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureSrc FromGLenum<TextureSrc>(GLenum from)
{
switch (from)
{
case GL_CONSTANT:
return TextureSrc::Constant;
case GL_PREVIOUS:
return TextureSrc::Previous;
case GL_PRIMARY_COLOR:
return TextureSrc::PrimaryColor;
case GL_TEXTURE:
return TextureSrc::Texture;
default:
return TextureSrc::InvalidEnum;
}
}
GLenum ToGLenum(TextureSrc from)
{
switch (from)
{
case TextureSrc::Constant:
return GL_CONSTANT;
case TextureSrc::Previous:
return GL_PREVIOUS;
case TextureSrc::PrimaryColor:
return GL_PRIMARY_COLOR;
case TextureSrc::Texture:
return GL_TEXTURE;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureSrc value)
{
switch (value)
{
case TextureSrc::Constant:
os << "GL_CONSTANT";
break;
case TextureSrc::Previous:
os << "GL_PREVIOUS";
break;
case TextureSrc::PrimaryColor:
os << "GL_PRIMARY_COLOR";
break;
case TextureSrc::Texture:
os << "GL_TEXTURE";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureTarget FromGLenum<TextureTarget>(GLenum from)
{
switch (from)
{
case GL_TEXTURE_2D:
return TextureTarget::_2D;
case GL_TEXTURE_2D_ARRAY:
return TextureTarget::_2DArray;
case GL_TEXTURE_2D_MULTISAMPLE:
return TextureTarget::_2DMultisample;
case GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES:
return TextureTarget::_2DMultisampleArray;
case GL_TEXTURE_3D:
return TextureTarget::_3D;
case GL_TEXTURE_EXTERNAL_OES:
return TextureTarget::External;
case GL_TEXTURE_RECTANGLE_ANGLE:
return TextureTarget::Rectangle;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
return TextureTarget::CubeMapPositiveX;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
return TextureTarget::CubeMapNegativeX;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
return TextureTarget::CubeMapPositiveY;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
return TextureTarget::CubeMapNegativeY;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
return TextureTarget::CubeMapPositiveZ;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
return TextureTarget::CubeMapNegativeZ;
case GL_TEXTURE_CUBE_MAP_ARRAY:
return TextureTarget::CubeMapArray;
case GL_TEXTURE_VIDEO_IMAGE_WEBGL:
return TextureTarget::VideoImage;
default:
return TextureTarget::InvalidEnum;
}
}
GLenum ToGLenum(TextureTarget from)
{
switch (from)
{
case TextureTarget::_2D:
return GL_TEXTURE_2D;
case TextureTarget::_2DArray:
return GL_TEXTURE_2D_ARRAY;
case TextureTarget::_2DMultisample:
return GL_TEXTURE_2D_MULTISAMPLE;
case TextureTarget::_2DMultisampleArray:
return GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES;
case TextureTarget::_3D:
return GL_TEXTURE_3D;
case TextureTarget::External:
return GL_TEXTURE_EXTERNAL_OES;
case TextureTarget::Rectangle:
return GL_TEXTURE_RECTANGLE_ANGLE;
case TextureTarget::CubeMapPositiveX:
return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
case TextureTarget::CubeMapNegativeX:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
case TextureTarget::CubeMapPositiveY:
return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
case TextureTarget::CubeMapNegativeY:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
case TextureTarget::CubeMapPositiveZ:
return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
case TextureTarget::CubeMapNegativeZ:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
case TextureTarget::CubeMapArray:
return GL_TEXTURE_CUBE_MAP_ARRAY;
case TextureTarget::VideoImage:
return GL_TEXTURE_VIDEO_IMAGE_WEBGL;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureTarget value)
{
switch (value)
{
case TextureTarget::_2D:
os << "GL_TEXTURE_2D";
break;
case TextureTarget::_2DArray:
os << "GL_TEXTURE_2D_ARRAY";
break;
case TextureTarget::_2DMultisample:
os << "GL_TEXTURE_2D_MULTISAMPLE";
break;
case TextureTarget::_2DMultisampleArray:
os << "GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES";
break;
case TextureTarget::_3D:
os << "GL_TEXTURE_3D";
break;
case TextureTarget::External:
os << "GL_TEXTURE_EXTERNAL_OES";
break;
case TextureTarget::Rectangle:
os << "GL_TEXTURE_RECTANGLE_ANGLE";
break;
case TextureTarget::CubeMapPositiveX:
os << "GL_TEXTURE_CUBE_MAP_POSITIVE_X";
break;
case TextureTarget::CubeMapNegativeX:
os << "GL_TEXTURE_CUBE_MAP_NEGATIVE_X";
break;
case TextureTarget::CubeMapPositiveY:
os << "GL_TEXTURE_CUBE_MAP_POSITIVE_Y";
break;
case TextureTarget::CubeMapNegativeY:
os << "GL_TEXTURE_CUBE_MAP_NEGATIVE_Y";
break;
case TextureTarget::CubeMapPositiveZ:
os << "GL_TEXTURE_CUBE_MAP_POSITIVE_Z";
break;
case TextureTarget::CubeMapNegativeZ:
os << "GL_TEXTURE_CUBE_MAP_NEGATIVE_Z";
break;
case TextureTarget::CubeMapArray:
os << "GL_TEXTURE_CUBE_MAP_ARRAY";
break;
case TextureTarget::VideoImage:
os << "GL_TEXTURE_VIDEO_IMAGE_WEBGL";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
TextureType FromGLenum<TextureType>(GLenum from)
{
switch (from)
{
case GL_TEXTURE_2D:
return TextureType::_2D;
case GL_TEXTURE_2D_ARRAY:
return TextureType::_2DArray;
case GL_TEXTURE_2D_MULTISAMPLE:
return TextureType::_2DMultisample;
case GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES:
return TextureType::_2DMultisampleArray;
case GL_TEXTURE_3D:
return TextureType::_3D;
case GL_TEXTURE_EXTERNAL_OES:
return TextureType::External;
case GL_TEXTURE_RECTANGLE_ANGLE:
return TextureType::Rectangle;
case GL_TEXTURE_CUBE_MAP:
return TextureType::CubeMap;
case GL_TEXTURE_CUBE_MAP_ARRAY:
return TextureType::CubeMapArray;
case GL_TEXTURE_VIDEO_IMAGE_WEBGL:
return TextureType::VideoImage;
default:
return TextureType::InvalidEnum;
}
}
GLenum ToGLenum(TextureType from)
{
switch (from)
{
case TextureType::_2D:
return GL_TEXTURE_2D;
case TextureType::_2DArray:
return GL_TEXTURE_2D_ARRAY;
case TextureType::_2DMultisample:
return GL_TEXTURE_2D_MULTISAMPLE;
case TextureType::_2DMultisampleArray:
return GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES;
case TextureType::_3D:
return GL_TEXTURE_3D;
case TextureType::External:
return GL_TEXTURE_EXTERNAL_OES;
case TextureType::Rectangle:
return GL_TEXTURE_RECTANGLE_ANGLE;
case TextureType::CubeMap:
return GL_TEXTURE_CUBE_MAP;
case TextureType::CubeMapArray:
return GL_TEXTURE_CUBE_MAP_ARRAY;
case TextureType::VideoImage:
return GL_TEXTURE_VIDEO_IMAGE_WEBGL;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, TextureType value)
{
switch (value)
{
case TextureType::_2D:
os << "GL_TEXTURE_2D";
break;
case TextureType::_2DArray:
os << "GL_TEXTURE_2D_ARRAY";
break;
case TextureType::_2DMultisample:
os << "GL_TEXTURE_2D_MULTISAMPLE";
break;
case TextureType::_2DMultisampleArray:
os << "GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES";
break;
case TextureType::_3D:
os << "GL_TEXTURE_3D";
break;
case TextureType::External:
os << "GL_TEXTURE_EXTERNAL_OES";
break;
case TextureType::Rectangle:
os << "GL_TEXTURE_RECTANGLE_ANGLE";
break;
case TextureType::CubeMap:
os << "GL_TEXTURE_CUBE_MAP";
break;
case TextureType::CubeMapArray:
os << "GL_TEXTURE_CUBE_MAP_ARRAY";
break;
case TextureType::VideoImage:
os << "GL_TEXTURE_VIDEO_IMAGE_WEBGL";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
VertexArrayType FromGLenum<VertexArrayType>(GLenum from)
{
switch (from)
{
case GL_COLOR_ARRAY:
return VertexArrayType::Color;
case GL_NORMAL_ARRAY:
return VertexArrayType::Normal;
case GL_POINT_SIZE_ARRAY_OES:
return VertexArrayType::PointSize;
case GL_TEXTURE_COORD_ARRAY:
return VertexArrayType::TextureCoord;
case GL_VERTEX_ARRAY:
return VertexArrayType::Vertex;
default:
return VertexArrayType::InvalidEnum;
}
}
GLenum ToGLenum(VertexArrayType from)
{
switch (from)
{
case VertexArrayType::Color:
return GL_COLOR_ARRAY;
case VertexArrayType::Normal:
return GL_NORMAL_ARRAY;
case VertexArrayType::PointSize:
return GL_POINT_SIZE_ARRAY_OES;
case VertexArrayType::TextureCoord:
return GL_TEXTURE_COORD_ARRAY;
case VertexArrayType::Vertex:
return GL_VERTEX_ARRAY;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, VertexArrayType value)
{
switch (value)
{
case VertexArrayType::Color:
os << "GL_COLOR_ARRAY";
break;
case VertexArrayType::Normal:
os << "GL_NORMAL_ARRAY";
break;
case VertexArrayType::PointSize:
os << "GL_POINT_SIZE_ARRAY_OES";
break;
case VertexArrayType::TextureCoord:
os << "GL_TEXTURE_COORD_ARRAY";
break;
case VertexArrayType::Vertex:
os << "GL_VERTEX_ARRAY";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
template <>
WrapMode FromGLenum<WrapMode>(GLenum from)
{
switch (from)
{
case GL_CLAMP_TO_EDGE:
return WrapMode::ClampToEdge;
case GL_CLAMP_TO_BORDER:
return WrapMode::ClampToBorder;
case GL_MIRRORED_REPEAT:
return WrapMode::MirroredRepeat;
case GL_REPEAT:
return WrapMode::Repeat;
default:
return WrapMode::InvalidEnum;
}
}
GLenum ToGLenum(WrapMode from)
{
switch (from)
{
case WrapMode::ClampToEdge:
return GL_CLAMP_TO_EDGE;
case WrapMode::ClampToBorder:
return GL_CLAMP_TO_BORDER;
case WrapMode::MirroredRepeat:
return GL_MIRRORED_REPEAT;
case WrapMode::Repeat:
return GL_REPEAT;
default:
UNREACHABLE();
return 0;
}
}
std::ostream &operator<<(std::ostream &os, WrapMode value)
{
switch (value)
{
case WrapMode::ClampToEdge:
os << "GL_CLAMP_TO_EDGE";
break;
case WrapMode::ClampToBorder:
os << "GL_CLAMP_TO_BORDER";
break;
case WrapMode::MirroredRepeat:
os << "GL_MIRRORED_REPEAT";
break;
case WrapMode::Repeat:
os << "GL_REPEAT";
break;
default:
os << "GL_INVALID_ENUM";
break;
}
return os;
}
} // namespace gl
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c10aebc03e1cdcaaa20e642246d4bb7b5d5003e0 | f8065889eb04b83d6e708a3b6331a058d83d0337 | /Tarea2_Ayudantia_Paralela/Funciones.cpp | cc69c54c63bcd838c0fa09fe6785bc21840e09f3 | [] | no_license | michhelhernandez/Ayudantia_Paralela_2019 | ff0f6d6d97b8d2824d6044316b1b9d28297a4ad5 | 605544f3e38fd1abe90f027a0de576f023ae9c3a | refs/heads/master | 2020-05-17T17:21:55.888394 | 2019-06-01T06:05:47 | 2019-06-01T06:05:47 | 183,850,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | cpp | #include <iostream>
#include <math.h>
#define tam 100000
void Llenar_Random(int A[]) //Ingresa 100000 valores random a un arreglo de enteros.
{
srand(time(NULL));
for (int i=0;i<tam;i++)
A[i]=1+rand() % (1000); // Se almacena un numero aleatorio entre 1 y 1000.
}
void Mostrar_Arreglo(int A[]) //Muestra el arreglo.
{
for(int i=0;i<tam;i++)
std::cout<<"Elemento "<<i<<": "<<A[i]<<std::endl;
}
void Calcular_Sumatorias(int A[],int& cantidad_total,double& suma,double& suma_cuadrada) //Calcula la sumatoria, cantidad total y sumatoria al cuadrado de los numeros en el arreglo.
{
for (int i=0;i<tam;i++)
{
cantidad_total++;
suma=suma+A[i];
suma_cuadrada=suma_cuadrada+(A[i]*A[i]);
}
}
double Promedio(int cantidad,double sumatoria) //Calcula y retorna el promedio.
{
double media=0;
if (cantidad!=0)
media=(sumatoria/cantidad);
return media;
}
double Desviacion(int cant,double suma_cuadrada,double promedio) //Calcula y retorna la desviacion estandar poblacional.
{
double desv=0;
if(cant!=0)
desv=sqrt( (suma_cuadrada/cant) - (promedio*promedio) ); //Se calcula la desviacion de forma "simplificada".
return desv;
}
double Varianza(double desviacion) //Calcula y retorna la varianza.
{
return (desviacion*desviacion);
}
| [
"michhelhernandez@hotmail.com"
] | michhelhernandez@hotmail.com |
17d798aed4c5b79e3d1fb37e5c4ab7908408f032 | f4a2658af992523f8cda62eb3d17c4424f6f8432 | /C++/1006.cpp | 325c95c446e95eb5649d4734353fe21bde1d624e | [] | no_license | vmf91/uri-solutions | 520442d9def5e5aca8542df5807d4a844b6a9ce6 | b0db3377fe09cf96b069bb3ff5e98e0333cf6c29 | refs/heads/master | 2020-12-10T22:32:47.959572 | 2020-06-11T03:47:00 | 2020-06-11T03:47:00 | 233,731,059 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main() {
double a, b, c;
cin >> a;
cin >> b;
cin >> c;
cout << fixed << setprecision(1);
cout << "MEDIA = " << (a * 2 + b * 3 + c * 5)/(2 + 3 + 5) << endl;
return 0;
} | [
"vmf91@hotmail.com"
] | vmf91@hotmail.com |
38304845978031d8922d01d9a976f638a2d801a6 | fbe68d84e97262d6d26dd65c704a7b50af2b3943 | /third_party/virtualbox/src/VBox/Additions/os2/VBoxSF/VBoxSFFile.cpp | 4c9873e8023d6af000cf87aceea813931a399d3e | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL"
] | permissive | thalium/icebox | c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb | 6f78952d58da52ea4f0e55b2ab297f28e80c1160 | refs/heads/master | 2022-08-14T00:19:36.984579 | 2022-02-22T13:10:31 | 2022-02-22T13:10:31 | 190,019,914 | 585 | 109 | MIT | 2022-01-13T20:58:15 | 2019-06-03T14:18:12 | C++ | UTF-8 | C++ | false | false | 7,418 | cpp | /** $Id: VBoxSFFile.cpp $ */
/** @file
* VBoxSF - OS/2 Shared Folders, the file level IFS EPs.
*/
/*
* Copyright (c) 2007 knut st. osmundsen <bird-src-spam@anduin.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.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DEFAULT
#include "VBoxSFInternal.h"
#include <VBox/log.h>
#include <iprt/assert.h>
DECLASM(int)
FS32_OPENCREATE(PCDFSI pcdfsi, PVBOXSFCD pcdfsd, PCSZ pszName, USHORT iCurDirEnd,
PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG uOpenMode, USHORT fOpenFlag,
PUSHORT puAction, USHORT fAttr, PBYTE pbEABuf, PUSHORT pfGenFlag)
{
NOREF(pcdfsi); NOREF(pcdfsd); NOREF(pszName); NOREF(iCurDirEnd); NOREF(psffsi); NOREF(psffsd); NOREF(uOpenMode);
NOREF(fOpenFlag); NOREF(puAction); NOREF(fAttr); NOREF(pbEABuf); NOREF(pfGenFlag);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_CLOSE(ULONG uType, ULONG fIoFlags, PSFFSI psffsi, PVBOXSFFSD psffsd)
{
NOREF(uType); NOREF(fIoFlags); NOREF(psffsi); NOREF(psffsd);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_COMMIT(ULONG uType, ULONG fIoFlags, PSFFSI psffsi, PVBOXSFFSD psffsd)
{
NOREF(uType); NOREF(fIoFlags); NOREF(psffsi); NOREF(psffsd);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_CHGFILEPTRL(PSFFSI psffsi, PVBOXSFFSD psffsd, LONGLONG off, ULONG uMethod, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(off); NOREF(uMethod); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
/** Forwards the call to FS32_CHGFILEPTRL. */
extern "C" APIRET APIENTRY
FS32_CHGFILEPTR(PSFFSI psffsi, PVBOXSFFSD psffsd, LONG off, ULONG uMethod, ULONG fIoFlags)
{
return FS32_CHGFILEPTRL(psffsi, psffsd, off, uMethod, fIoFlags);
}
DECLASM(int)
FS32_FILEINFO(ULONG fFlag, PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG uLevel,
PBYTE pbData, ULONG cbData, ULONG fIoFlags)
{
NOREF(fFlag); NOREF(psffsi); NOREF(psffsd); NOREF(uLevel); NOREF(pbData); NOREF(cbData); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_NEWSIZEL(PSFFSI psffsi, PVBOXSFFSD psffsd, LONGLONG cbFile, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(cbFile); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_READ(PSFFSI psffsi, PVBOXSFFSD psffsd, PVOID pvData, PULONG pcb, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pvData); NOREF(pcb); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_WRITE(PSFFSI psffsi, PVBOXSFFSD psffsd, PVOID pvData, PULONG pcb, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pvData); NOREF(pcb); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_READFILEATCACHE(PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG fIoFlags, LONGLONG off, ULONG pcb, KernCacheList_t **ppCacheList)
{
NOREF(psffsi); NOREF(psffsd); NOREF(fIoFlags); NOREF(off); NOREF(pcb); NOREF(ppCacheList);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_RETURNFILECACHE(KernCacheList_t *pCacheList)
{
NOREF(pCacheList);
return ERROR_NOT_SUPPORTED;
}
/* oddments */
DECLASM(int)
FS32_CANCELLOCKREQUESTL(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelockl *pLockRange)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pLockRange);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_CANCELLOCKREQUEST(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelock *pLockRange)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pLockRange);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_FILELOCKSL(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelockl *pUnLockRange,
struct filelockl *pLockRange, ULONG cMsTimeout, ULONG fFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pUnLockRange); NOREF(pLockRange); NOREF(cMsTimeout); NOREF(fFlags);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_FILELOCKS(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelock *pUnLockRange,
struct filelock *pLockRange, ULONG cMsTimeout, ULONG fFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pUnLockRange); NOREF(pLockRange); NOREF(cMsTimeout); NOREF(fFlags);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_IOCTL(PSFFSI psffsi, PVBOXSFFSD psffsd, USHORT uCategory, USHORT uFunction,
PVOID pvParm, USHORT cbParm, PUSHORT pcbParmIO,
PVOID pvData, USHORT cbData, PUSHORT pcbDataIO)
{
NOREF(psffsi); NOREF(psffsd); NOREF(uCategory); NOREF(uFunction); NOREF(pvParm); NOREF(cbParm); NOREF(pcbParmIO);
NOREF(pvData); NOREF(cbData); NOREF(pcbDataIO);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_FILEIO(PSFFSI psffsi, PVBOXSFFSD psffsd, PBYTE pbCmdList, USHORT cbCmdList,
PUSHORT poffError, USHORT fIoFlag)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pbCmdList); NOREF(cbCmdList); NOREF(poffError); NOREF(fIoFlag);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_NMPIPE(PSFFSI psffsi, PVBOXSFFSD psffsd, USHORT uOpType, union npoper *pOpRec,
PBYTE pbData, PCSZ pszName)
{
NOREF(psffsi); NOREF(psffsd); NOREF(uOpType); NOREF(pOpRec); NOREF(pbData); NOREF(pszName);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_OPENPAGEFILE(PULONG pfFlags, PULONG pcMaxReq, PCSZ pszName, PSFFSI psffsi, PVBOXSFFSD psffsd,
USHORT uOpenMode, USHORT fOpenFlags, USHORT fAttr, ULONG uReserved)
{
NOREF(pfFlags); NOREF(pcMaxReq); NOREF(pszName); NOREF(psffsi); NOREF(psffsd); NOREF(uOpenMode); NOREF(fOpenFlags);
NOREF(fAttr); NOREF(uReserved);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_SETSWAP(PSFFSI psffsi, PVBOXSFFSD psffsd)
{
NOREF(psffsi); NOREF(psffsd);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_ALLOCATEPAGESPACE(PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG cb, USHORT cbWantContig)
{
NOREF(psffsi); NOREF(psffsd); NOREF(cb); NOREF(cbWantContig);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_DOPAGEIO(PSFFSI psffsi, PVBOXSFFSD psffsd, struct PageCmdHeader *pList)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pList);
return ERROR_NOT_SUPPORTED;
}
| [
"benoit.amiaux@gmail.com"
] | benoit.amiaux@gmail.com |
2d30806b58f75dbfaec762c2b08eb21f0c2b7d64 | d32f3d77c52a1d41fc77272be5a3582856157fa1 | /cpp/DataStructure/HW3/nhay.cpp | 6c93b016f8dca6306a2ea003760bb813579e334e | [] | no_license | gkzhb/code | c4afc019f7f465845b0b0ef40d08f30c1fd247d6 | 73ab7fb0e156a5904b82811df805b66af36b38c0 | refs/heads/master | 2020-03-18T01:48:59.518692 | 2019-06-15T11:48:40 | 2019-06-15T11:48:40 | 134,161,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | // time limit exceeded
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
void preprocessing(vector<int> &next, const string &s)
{
int i = 0, j = -1;
next[0] = -1;
while (i < s.size())
if (-1 == j || s[i] == s[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
int kmp(string a)
{
int i = 0, j = 0;
vector<int> next(a.size() + 1, 0);
preprocessing(next, a);
char c;
while ((c = getchar()) == '\n')
;
while (c != '\n')
{
if (-1 == i || a[i] == c)
{
i++;
j++;
c = getchar();
}
else
i = next[i];
if (i == a.size())
{
cout << j - i << endl;
i = next[i];
}
}
return -1;
}
int main(void)
{
string s;
while (cin)
{
cin >> s;
cin >> s;
kmp(s);
}
return 0;
} | [
"zhb896579388@163.com"
] | zhb896579388@163.com |
6a73b99bf397ca45cd79a700a3322a9f33743512 | 2c004b31679a90fc71121ad3a3215abdd486e19e | /Segundo Parcial/Tarea4/Ejercicio2/Ejercicio2/DispositivoToken.h | a38958957e8a53d4b935a00a57a34c51aa113668 | [] | no_license | colina118/Estructura | ae51c0e2ec104c102d0abf22f5c633c8942dc663 | b74eaf42775a6d3aa1ee591f87df60cdaa4f834f | refs/heads/master | 2021-01-01T18:07:51.265565 | 2015-05-12T19:28:08 | 2015-05-12T19:28:08 | 29,313,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #include <iostream>
#include <string>
namespace mike{
class DispositivoToken
{
std::string ip;
std::string modelo;
int numero;
public:
DispositivoToken();
DispositivoToken(std::string _ip, std::string _modelo, int _numero)
: ip(_ip), modelo(_modelo), numero(_numero)
{}
friend std::ostream & operator <<(std::ostream & os, DispositivoToken &);
bool operator != (DispositivoToken & dispo);
bool operator == (DispositivoToken & dispo);
};
} | [
"mikehill2010@gmail.com"
] | mikehill2010@gmail.com |
dce853b87afa2ab0390ada9372acc5593895c880 | bf437a984f4176f99ff1a8c6a7f60a64259b2415 | /src/inet/physicallayer/idealradio/IdealReception.cc | d0663e92a1434a61b9c93d824251ba38163cb0ba | [] | no_license | kvetak/ANSA | b8bcd25c9c04a09d5764177e7929f6d2de304e57 | fa0f011b248eacf25f97987172d99b39663e44ce | refs/heads/ansainet-3.3.0 | 2021-04-09T16:36:26.173317 | 2017-02-16T12:43:17 | 2017-02-16T12:43:17 | 3,823,817 | 10 | 16 | null | 2017-02-16T12:43:17 | 2012-03-25T11:25:51 | C++ | UTF-8 | C++ | false | false | 1,855 | cc | //
// Copyright (C) 2013 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/physicallayer/idealradio/IdealReception.h"
namespace inet {
namespace physicallayer {
Register_Enum(inet::physicallayer::IdealReception::Power,
(IdealReception::POWER_UNDETECTABLE,
IdealReception::POWER_DETECTABLE,
IdealReception::POWER_INTERFERING,
IdealReception::POWER_RECEIVABLE));
IdealReception::IdealReception(const IRadio *radio, const ITransmission *transmission, const simtime_t startTime, const simtime_t endTime, const Coord startPosition, const Coord endPosition, const EulerAngles startOrientation, const EulerAngles endOrientation, const Power power) :
ReceptionBase(radio, transmission, startTime, endTime, startPosition, endPosition, startOrientation, endOrientation),
power(power)
{
}
std::ostream& IdealReception::printToStream(std::ostream& stream, int level) const
{
stream << "IdealReception";
if (level >= PRINT_LEVEL_INFO)
stream << ", power = " << cEnum::get(opp_typename(typeid(IdealReception::Power)))->getStringFor(power) + 6;
return ReceptionBase::printToStream(stream, level);
}
} // namespace physicallayer
} // namespace inet
| [
"ivesely@fit.vutbr.cz"
] | ivesely@fit.vutbr.cz |
b1910675392b896ef97947b3896213d30d00305d | 19b9be2641ff9f032454bd4534affd90716c852c | /src/Decimal.h | ef96553bbc1afc3cb40f80d09f9a1ce58ae66dac | [
"BSL-1.0"
] | permissive | maksverver/MSc | 4db9ce5fdb4e179e5cf5896acbc36b2362326672 | f49543afb74eba43c931e3829dffd8975118bbe7 | refs/heads/master | 2021-01-01T15:30:52.885666 | 2014-02-11T22:56:27 | 2014-02-11T22:56:27 | 34,076,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,141 | h | // Copyright (c) 2009-2013 University of Twente
// Copyright (c) 2009-2013 Michael Weber <michaelw@cs.utwente.nl>
// Copyright (c) 2009-2013 Maks Verver <maksverver@geocities.com>
// Copyright (c) 2009-2013 Eindhoven University of Technology
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef DECIMAL_H_INCLUDED
#define DECIMAL_H_INCLUDED
#include <string>
#include <sstream>
//! Arbitrary-precision natural numbers with an internal decimal representation.
class Decimal
{
static std::string str(unsigned i)
{
std::ostringstream oss;
oss << i;
return oss.str();
}
public:
/*! Construct a Decimal from a string.
\param t A string consisting of decimal digits without leading zeros. */
Decimal(const std::string &t) : s(t) { }
//! Construct a Decimal from an unsigned integer.
Decimal(const unsigned i) : s(str(i)) { }
//! Copy constructor.
Decimal(const Decimal &d) : s(d.s) { }
//! Assignment operator.
Decimal &operator=(const Decimal &d) { s = d.s; return *this; }
//! Returns the underlying decimal representation as a std::string.
const std::string &str() const { return s; }
//! Returns a character pointer to underlying decimal representation.
const char *c_str() const { return s.c_str(); }
//! Returns the length of the underlying decimal representation.
size_t size() const { return s.size(); }
//! Returns the result of adding this number to the given argument.
Decimal operator+(const Decimal &d) const;
//! Returns the result of multiplying this number with the given argument.
Decimal operator*(const Decimal &d) const;
private:
/*! Returns the digit at the `i`-th position, counted from the left.
This is equivalent to `str()[i]` which means that `i` must be between
`0` and `size()`, exclusive! */
char operator[](size_t i) const { return s[i]; }
std::string s; //! internal representation as a decimal number
};
#endif /* ndef DECIMAL_H_INCLUDED */
| [
"maksverver@geocities.com"
] | maksverver@geocities.com |
be5e57670eadff632fef6d69287539171afde39c | e0744c97a2b4fd26f5ba6a38ba1f87a7ba9e8bc5 | /CrazyDarts2Android/app/src/main/cpp/EditorMenuMotion.hpp | a12b724268600cf55feaeae6f487c5c5117854b2 | [] | no_license | jsj2008/Metal-Game-Engine | f05ff4ec9d5c05523a774ee2ab1464f15a55c0fe | ad9520516f800126d6c48b1241e18b29aa06ae03 | refs/heads/master | 2022-03-07T14:47:51.337422 | 2019-09-23T06:15:10 | 2019-09-23T06:15:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,202 | hpp | //
// EditorMenuMotion.hpp
// Crazy Darts 2 Mac
//
// Created by Nicholas Raptis on 4/13/19.
// Copyright © 2019 Froggy Studios. All rights reserved.
//
#ifndef EditorMenuMotion_hpp
#define EditorMenuMotion_hpp
#include "ToolMenu.hpp"
#include "EditorMenuMotionTypePanel.hpp"
#include "LevelMotionControllerBlueprint.hpp"
class GameEditor;
class GamePermanentEditor;
class EditorMenuMotion : public ToolMenu {
public:
EditorMenuMotion(GameEditor *pEditor);
EditorMenuMotion(GamePermanentEditor *pEditor);
void Init();
virtual ~EditorMenuMotion();
virtual void Layout() override;
virtual void Notify(void *pSender, const char *pNotification) override;
virtual void Update() override;
void CheckSlicePanels();
bool mIsForPermSpawn;
GameEditor *mEditor;
GamePermanentEditor *mPermEditor;
LevelMotionControllerBlueprint *mMotionController;
ToolMenuPanel *mPanelMainControls;
ToolMenuSectionRow *mRowMain1;
ToolMenuSectionRow *mRowMain2;
ToolMenuSectionRow *mRowMain3;
UIButton *mButtonAddNegate;
UIButton *mButtonAddRotate;
UIButton *mButtonAddOscillateV;
UIButton *mButtonAddOscillateH;
UIButton *mButtonAddOscillateRotation;
UIButton *mButtonRemoveAll;
UIButton *mButtonRemoveFirst;
UIButton *mButtonRemoveLast;
ToolMenuPanel *mPanelTypes;
FList mTypePanelList;
//EditorMenuMotionTypePanel *
};
#endif /* EditorMenuMotion_hpp */
| [
"nraptis@gmail.com"
] | nraptis@gmail.com |
e6d9fa102768bc492c53e50dbcdffc585a98a150 | 2a594aeb45cf16333d83421ae3c11f9ef39dc8bc | /leecode-II/CloneGraph/源.cpp | 76d4f65f15cb9a2354337565600ce95f6fa75e12 | [
"MIT"
] | permissive | lisnb/leetcode | 9bcd40c9fd8a84ed30e4a91edc7451220ffef676 | 7875e4ff20412b663c59e57f76d08cd62b91481c | refs/heads/master | 2020-06-04T05:32:52.595221 | 2015-08-20T14:39:46 | 2015-08-20T14:39:46 | 22,034,965 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 813 | cpp | #include "../leecode-II/leetcode.h"
#include <algorithm>
#include <deque>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef _leetcode_undirectedgraphnode<int> UndirectedGraphNode;
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == nullptr)
return nullptr;
if (cache.find(node->label) == cache.end())
{
cache[node->label] = new UndirectedGraphNode(node->label);
for (auto nei : node->neighbors)
{
cache[node->label]->neighbors.push_back(cloneGraph(nei));
}
}
return cache[node->label];
}
private:
unordered_map<int, UndirectedGraphNode *> cache;
}; | [
"lisnb.h@hotmail.com"
] | lisnb.h@hotmail.com |
64dc35fe593ddd5564730b71e5558c02627b45af | e8dd43ab1d079b921e8b5d246fec7c8afbe12b1e | /animecheat.pw - Copy/b1g pasta/sdk/interfaces/CInput.hpp | a307a8869f548ea0b3fa1685e5b459b2c0f351ea | [] | no_license | hvhgodsmile/some-bs-no-one-works-on | 3031940ab9ec5f2ef806ae10679bb13e2c0dea43 | 8134a772aba3653604da5b16864a9af6299821d3 | refs/heads/master | 2020-05-03T00:16:13.056717 | 2019-03-29T03:09:15 | 2019-03-29T03:09:15 | 178,305,079 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,048 | hpp | #pragma once
#include "../misc/CUserCmd.hpp"
#define MULTIPLAYER_BACKUP 150
class bf_write;
class bf_read;
class CInput
{
public:
virtual void Init_All(void);
virtual void Shutdown_All(void);
virtual int GetButtonBits(int);
virtual void CreateMove(int sequence_number, float input_sample_frametime, bool active);
virtual void ExtraMouseSample(float frametime, bool active);
virtual bool WriteUsercmdDeltaToBuffer(bf_write *buf, int from, int to, bool isnewcommand);
virtual void EncodeUserCmdToBuffer(bf_write& buf, int slot);
virtual void DecodeUserCmdFromBuffer(bf_read& buf, int slot);
inline CUserCmd* GetUserCmd(int sequence_number);
inline CVerifiedUserCmd* GetVerifiedCmd(int sequence_number);
bool m_fTrackIRAvailable;
bool m_fMouseInitialized;
bool m_fMouseActive;
bool m_fJoystickAdvancedInit;
char pad_0x08[0x2C];
char pad_0x00[0x0C];
void* m_pKeys;
char pad_0x38[0x64];
int pad_0x41;
int pad_0x42;
bool m_fCameraInterceptingMouse;
bool m_fCameraInThirdPerson;
bool m_fCameraMovingWithMouse;
Vector m_vecCameraOffset;
bool m_fCameraDistanceMove;
int m_nCameraOldX;
int m_nCameraOldY;
int m_nCameraX;
int m_nCameraY;
bool m_CameraIsOrthographic;
Vector m_angPreviousViewAngles;
Vector m_angPreviousViewAnglesTilt;
float m_flLastForwardMove;
int m_nClearInputState;
char pad_0xE4[0x8];
CUserCmd* m_pCommands;
CVerifiedUserCmd* m_pVerifiedCommands;
};
CUserCmd* CInput::GetUserCmd(int sequence_number)
{
return &m_pCommands[sequence_number % MULTIPLAYER_BACKUP];
}
CVerifiedUserCmd* CInput::GetVerifiedCmd(int sequence_number)
{
return &m_pVerifiedCommands[sequence_number % MULTIPLAYER_BACKUP];
} | [
"49047029+hvhgodsmile@users.noreply.github.com"
] | 49047029+hvhgodsmile@users.noreply.github.com |
8d6dca2c2c6ca804acb24a0a222543eae74b62f7 | 500d9a3048560023bd989dbf5d770e0b8abf224d | /BZOJ/3156 防御准备/3156.cpp | 1804b8ebcbd954051ddb229fcfd060ec19e05483 | [] | no_license | hilbertanjou/OJ | 2138bd349607adebd7674861e00dad57a23724bd | 641f412d904edd66e97befdabcc32b7076729a53 | refs/heads/master | 2020-12-30T23:33:13.961562 | 2013-08-23T09:44:49 | 2013-08-23T09:44:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | cpp | #include <cstdio>
typedef long long LL;
const int MAXN = 1111111;
int a[MAXN], q[MAXN];
LL f[MAXN], g[MAXN];
inline LL calc(int i, int j) {
return g[j] - LL(i) * j;
}
int main() {
int n, l = 0, r = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
for (; l < r && calc(i, q[l + 1]) < calc(i, q[l]); ++l);
f[i] = a[i] + (LL(i) * i - i >> 1) + calc(i, q[l]);
g[i] = f[i] + (LL(i) * i + i >> 1);
for (; r && (q[r] - q[r - 1]) * (g[i] - g[q[r]]) - (i - q[r]) * (g[q[r]] - g[q[r - 1]]) <= 0; --r);
q[++r] = i;
if (l > r)
l = r;
}
printf("%lld\n", f[n]);
return 0;
}
| [
"xy_xuyi@foxmail.com"
] | xy_xuyi@foxmail.com |
9bb476606913caccb4028aa3f7d29dbe6130f0fb | 5fbfe741e7823f7eafd819177d6ad075bd9598d9 | /SpaceShipGame/SimpleSfmlEngine/dataTypes/clock.hpp | 5028d0a2a409ed6aa776a3b50be502628f4bdb1c | [] | no_license | OfficialLahusa/SpaceShip | 062a81b69b55199906296d7f5724eb42e688864a | 991a50478cae564015d1424a196cf6c1676e501a | refs/heads/master | 2021-06-27T03:01:22.018966 | 2020-11-17T13:51:29 | 2020-11-17T13:51:29 | 166,654,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | hpp | #pragma once
#include <chrono>
namespace sse
{
class clock
{
public:
clock()
:m_start(std::chrono::steady_clock::now())
{
}
template<typename T>
T restart()
{
const std::chrono::steady_clock::time_point old = m_start;
m_start = std::chrono::steady_clock::now();
const std::chrono::duration<T> elapsedTime = m_start - old;
return elapsedTime.count();
}
void restart()
{
m_start = std::chrono::steady_clock::now();
}
template<typename T>
T getElapsedTime()
{
const std::chrono::duration<T> elapsedTime = std::chrono::steady_clock::now() - m_start;
return elapsedTime.count();
}
private:
std::chrono::steady_clock::time_point m_start;
};
} | [
"lassehuber@outlook.de"
] | lassehuber@outlook.de |
2cb950b064d18a201b742c79140713f61844c657 | cb3b8fda8f03642e50fa5bc84438a594128930a2 | /src/system/kernel/core/processor/mips_common/Disassembler.cc | 122c54285a2ace3d03ca280eaf85f2cca9c86d29 | [
"ISC"
] | permissive | OuluLinux/pedigree | fbb83055d0afd1e620f48d8cfd89a2bf88235701 | 4f02647d8237cc19cff3c20584c0fdd27b14a7d4 | refs/heads/master | 2022-12-28T15:49:01.918113 | 2013-05-25T02:20:01 | 2013-05-25T02:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,091 | cc | /*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Disassembler.h"
const char *g_pOpcodes[64] = {
0, // Special
0, // RegImm
"j ",
"jal ",
"beq ",
"bne ",
"blez ",
"bgtz ",
"addi ", // 8
"addiu ",
"slti ",
"sltiu ",
"andi ",
"ori ",
"xori ",
"lui ",
"cop0 ", // 16
"cop1 ",
"cop2 ",
"cop3 ",
"beql ",
"bnel ",
"blezl ",
"bgtzl ",
0, // 24
0,
0,
0,
0,
0,
0,
0,
"lb ", // 32
"lh ",
"lwl ",
"lw ",
"lbu ",
"lhu ",
"lwr ",
0,
"sb ", // 40
"sh ",
"swl ",
"sw ",
0,
0,
"swr ",
"cache ",
"ll ", // 48
"lwc1 ",
"lwc2 ",
"lwc3 ",
0,
"ldc1 ",
"ldc2 ",
"ldc3 ",
"sc ", // 56
"swc1 ",
"swc2 ",
"swc3 ",
0,
"sdc1 ",
"sdc2 ",
"sdc3 "
};
const char *g_pSpecial[64] = {
"sll ",
0,
"srl ",
"sra ",
"sllv ",
0,
"srlv ",
"srav ",
"jr ", // 8
"jalr ",
0,
0,
"syscall",
"break ",
0,
"sync ",
"mfhi ", // 16
"mthi ",
"mflo ",
"mtlo ",
0,
0,
0,
0,
"mult ", // 24
"multu ",
"div ",
"divu ",
0,
0,
0,
0,
"add ", // 32
"addu ",
"sub ",
"subu ",
"and ",
"or ",
"xor ",
"nor ",
0, // 40
0,
"slt ",
"sltu ",
0,
0,
0,
0,
"tge ", // 48
"tgeu ",
"tlt ",
"tltu ",
"teq ",
0,
"tne ",
0,
0, // 56
0,
0,
0,
0,
0,
0,
0
};
const char *g_pRegimm[32] = {
"bltz ",
"bgez ",
"bltzl ",
"bgezl ",
0,
0,
0,
0,
"tgei ", // 8
"tgeiu ",
"tlti ",
"tltiu ",
"teqi ",
0,
"tnei ",
0,
"bltzal", // 16
"bgezal",
"bltzall",
"bgezall",
0,
0,
0,
0,
0, // 24
0,
0,
0,
0,
0,
0,
0
};
const char *g_pCopzRs[32] = {
"mfc",
0,
"cfc",
0,
"mtc",
0,
"ctc",
0,
"bc", // 8
0,
0,
0,
0,
0,
0,
0,
"co", // 16
"co",
"co",
"co",
"co",
"co",
"co",
"co",
"co", // 24
"co",
"co",
"co",
"co",
"co",
"co",
"co"
};
const char *g_pCopzRt[32] = {
"f",
"t",
"fl",
"tl",
0,
0,
0,
0,
0, // 8
0,
0,
0,
0,
0,
0,
0,
0, // 16
0,
0,
0,
0,
0,
0,
0,
0, // 24
0,
0,
0,
0,
0,
0,
0
};
const char *g_pCp0Function[64] = {
0,
"tlbr",
"tlbwi",
0,
0,
0,
"tlbwr",
0,
"tlbp", // 8
0,
0,
0,
0,
0,
0,
0,
"rfe", // 16
0,
0,
0,
0,
0,
0,
0,
"eret", // 24
0,
0,
0,
0,
0,
0,
0,
0, // 32
0,
0,
0,
0,
0,
0,
0,
0, // 40
0,
0,
0,
0,
0,
0,
0,
0, // 48
0,
0,
0,
0,
0,
0,
0,
0, // 56
0,
0,
0,
0,
0,
0,
0
};
const char *g_pRegisters[32] = {
"zero",
"at",
"v0",
"v1",
"a0",
"a1",
"a2",
"a3",
"t0",
"t1",
"t2",
"t3",
"t4",
"t5",
"t6",
"t7",
"s0",
"s1",
"s2",
"s3",
"s4",
"s5",
"s6",
"s7",
"t8",
"t9",
"k0",
"k1",
"gp",
"sp",
"fp",
"ra"
};
MipsDisassembler::MipsDisassembler()
: m_nLocation(0)
{
}
MipsDisassembler::~MipsDisassembler()
{
}
void MipsDisassembler::setLocation(uintptr_t nLocation)
{
m_nLocation = nLocation;
}
uintptr_t MipsDisassembler::getLocation()
{
return m_nLocation;
}
void MipsDisassembler::setMode(size_t nMode)
{
}
void MipsDisassembler::disassemble(LargeStaticString &text)
{
uint32_t nInstruction = * reinterpret_cast<uint32_t*> (m_nLocation);
m_nLocation += 4;
// SLL $zero, $zero, 0 == nop.
if (nInstruction == 0)
{
text += "nop";
return;
}
// Grab the instruction opcode.
int nOpcode = (nInstruction >> 26) & 0x3F;
// Handle special opcodes.
if (nOpcode == 0)
{
disassembleSpecial(nInstruction, text);
}
else if (nOpcode == 1)
{
disassembleRegImm(nInstruction, text);
}
else
{
disassembleOpcode(nInstruction, text);
}
}
void MipsDisassembler::disassembleSpecial(uint32_t nInstruction, LargeStaticString & text)
{
// Special instructions are R-Types.
uint32_t nRs = (nInstruction >> 21) & 0x1F;
uint32_t nRt = (nInstruction >> 16) & 0x1F;
uint32_t nRd = (nInstruction >> 11) & 0x1F;
uint32_t nShamt = (nInstruction >> 6) & 0x1F;
uint32_t nFunct = nInstruction & 0x3F;
if (g_pSpecial[nFunct] == 0)
return;
switch (nFunct)
{
case 00: // SLL
case 02: // SRL
case 03: // SRA
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRt];
text += ", ";
text += nShamt;
break;
case 04: // SLLV
case 06: // SRLV
case 07: // SRAV
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRt];
text += ", ";
text += g_pRegisters[nRs];
break;
case 010: // JR
text += "jr ";
text += g_pRegisters[nRs];
break;
case 011: // JALR
{
text += "jalr ";
if (nRd != 31)
{
text += g_pRegisters[nRd];
text += ", ";
}
text += g_pRegisters[nRs];
break;
}
case 014: // SYSCALL
case 015: // BREAK
case 017: // SYNC
text += g_pSpecial[nFunct];
break;
case 020: // MFHI
case 022: // MFLO
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
break;
case 021: // MTHI
case 023: // MTLO
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRs];
break;
case 030: // MULT
case 031: // MULTU
case 032: // DIV
case 033: // DIVU
case 060: // TGE
case 061: // TGEU
case 062: // TLT
case 063: // TLTU
case 064: // TEQ
case 065: // TNE
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRs];
text += ", ";
text += g_pRegisters[nRt];
break;
case 041: // ADDU
if (nRt == 0)
{
// If this is an add of zero, it is actually a "move".
text += "move ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRs];
break;
}
// Fall through.
default:
{
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRs];
text += ", ";
text += g_pRegisters[nRt];
}
};
}
void MipsDisassembler::disassembleRegImm(uint32_t nInstruction, LargeStaticString & text)
{
uint32_t nRs = (nInstruction >> 21)&0x1F;
uint32_t nOp = (nInstruction >> 16)&0x1F;
uint16_t nImmediate = nInstruction & 0xFFFF;
uint32_t nTarget = (nImmediate << 2) + m_nLocation;
switch (nOp)
{
case 010: // TGEI
case 011: // TGEIU
case 012: // TLTI
case 013: // TLTIU
case 014: // TEQI
case 016: // TNEI
text += g_pRegimm[nOp];
text += " ";
text += g_pRegisters[nRs];
text += ", ";
text.append(static_cast<int16_t>(nImmediate), 10);
break;
default:
text += g_pRegimm[nOp];
text += " ";
text += g_pRegisters[nRs];
text += ", 0x";
text.append(nTarget, 16);
};
}
void MipsDisassembler::disassembleOpcode(uint32_t nInstruction, LargeStaticString & text)
{
// Opcode instructions are J-Types, or I-Types.
// Jump target is the lower 26 bits shifted left 2 bits, OR'd with the high 4 bits of the delay slot.
uint32_t nTarget = ((nInstruction & 0x03FFFFFF)<<2) | (m_nLocation & 0xF0000000);
uint16_t nImmediate = nInstruction & 0x0000FFFF;
uint32_t nRt = (nInstruction >> 16) & 0x1F;
uint32_t nRs = (nInstruction >> 21) & 0x1F;
int nOpcode = (nInstruction >> 26) & 0x3F;
switch (nOpcode)
{
case 02: // J
case 03: // JAL
text += g_pOpcodes[nOpcode];
text += " 0x";
text.append(nTarget, 16);
break;
case 006: // BLEZ
case 007: // BGTZ
case 026: // BLEZL
case 027: // BGTZL
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRs];
text += ", 0x";
text.append( (static_cast<uint32_t>(nImmediate) << 2)+m_nLocation, 16);
break;
case 004: // BEQ
case 005: // BNE
case 024: // BEQL
case 025: // BNEL
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRs];
text += ", ";
text += g_pRegisters[nRt];
text += ", 0x";
text.append( (static_cast<uint32_t>(nImmediate) << 2)+m_nLocation, 16);
break;
case 010: // ADDI
case 011: // ADDIU
case 012: // SLTI
case 013: // SLTIU
case 014: // ANDI
case 015: // ORI
case 016: // XORI
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRt];
text += ", ";
text += g_pRegisters[nRs];
text += ", ";
text.append(static_cast<short>(nImmediate), 10);
break;
case 017: // LUI
text += "lui ";
text += g_pRegisters[nRt];
text += ", 0x";
text.append(nImmediate, 16);
break;
case 020: // COP0
case 021: // COP1
case 022: // COP2
case 023: // COP3
{
if (nRs == 8) // BC
{
text += g_pCopzRs[nRs];
text.append( static_cast<unsigned char>(nOpcode&0x3));
text += g_pCopzRt[nRt];
text += ", 0x";
text.append( (nImmediate<<2)+m_nLocation, 16);
}
else if (nOpcode == 020 /* CP0 */ && nRs >= 16 /* CO */)
{
text += g_pCp0Function[nInstruction&0x1F];
}
else
{
text += g_pCopzRs[nRs];
text.append( static_cast<unsigned char>(nOpcode&0x3));
text += " ";
text += g_pRegisters[nRt];
text += ", ";
text.append( ((nInstruction>>11)&0x1F), 10);
}
break;
}
default:
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRt];
text += ", ";
text.append(static_cast<short>(nImmediate), 10);
text += "(";
text += g_pRegisters[nRs];
text += ")";
break;
}
}
| [
"mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d"
] | mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d |
ca8789855bcf56d446ac2e9ee577703c34959e3e | 06cbc74aac6be71a48d4b800178583f5eaa8f3e0 | /Lab1/APPOO_1.2/APPOO_1.2/Phone.hpp | 1da59e48e249245eda4e2a71b548a0da52127340 | [] | no_license | MihaiCapra/APPOO | 0a761d56a5c1153a331a7b611df7f346ccc48d16 | 0632b9b01d1bd65c5409a5aa78aee2d28ba6a877 | refs/heads/master | 2021-01-18T23:34:49.969857 | 2017-05-23T05:29:17 | 2017-05-23T05:29:17 | 87,119,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | hpp | #pragma once
class Phone
{
public:
Phone(): brand(""), model(""),color(""),price(0){}
~Phone() {}
friend std::istream&operator >> (std::istream &in, Phone &obj);
friend std::ostream&operator <<(std::ostream &out, Phone &obj);
std::string getBrand();
std::string getModel();
std::string getColor();
double getPrice();
private:
std::string brand,model,color;
double price;
}; | [
"mihai.capra27@gmail.com"
] | mihai.capra27@gmail.com |
60bebf6f7448ddc77bded4656fbdb4ae179985b6 | cac15913ccad3c0ca2de77d8d12809ef4fe21e57 | /Source/ThirdPersonCamera/ThirdPersonCameraGameMode.h | b7287cab8e32fe0daa0ce368505f536d2f4a757c | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | ArnaudSpicht/third-person-camera | 431d6b2ee276c296fe1ff348c7c2ca559201cd44 | 7bedf626d15820d0ff3563b503729d8e2ce5aaa9 | refs/heads/develop | 2020-03-13T15:21:12.026161 | 2018-08-13T06:47:37 | 2018-08-13T06:47:37 | 131,175,154 | 0 | 0 | MIT | 2018-08-13T06:48:26 | 2018-04-26T15:23:11 | C++ | UTF-8 | C++ | false | false | 270 | h | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "ThirdPersonCameraGameMode.generated.h"
UCLASS(minimalapi)
class AThirdPersonCameraGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
AThirdPersonCameraGameMode();
};
| [
"dev@npruehs.de"
] | dev@npruehs.de |
d15bb44d11df4fbd6311370817a5b49a4e99dcc5 | 8b957ec62991c367dfc6c9247ada90860077b457 | /src/qt/rpcconsole.h | 1c679a1ecac3f667c6f041b2a214d594c75c23db | [
"MIT"
] | permissive | valuero-org/valuero | 113f29046bd63c8b93160604452a99ed51367942 | c0a8d40d377c39792e5a79d4a67f00bc592aef87 | refs/heads/master | 2020-05-24T17:44:46.409378 | 2019-09-09T10:18:59 | 2019-09-09T10:18:59 | 187,392,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,204 | h | // Copyright (c) 2012-2019 The Bitcoin Core developers
// Copyright (c) 2017-2019 The Raven Core developers
// Copyright (c) 2018-2019 The Rito Core developers
// Copyright (c) 2019 The Valuero developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef VAL_QT_RPCCONSOLE_H
#define VAL_QT_RPCCONSOLE_H
#include "guiutil.h"
#include "peertablemodel.h"
#include "net.h"
#include <QWidget>
#include <QCompleter>
#include <QThread>
class ClientModel;
class PlatformStyle;
class RPCTimerInterface;
namespace Ui {
class RPCConsole;
}
QT_BEGIN_NAMESPACE
class QMenu;
class QItemSelection;
QT_END_NAMESPACE
/** Local Valuero RPC console. */
class RPCConsole: public QWidget
{
Q_OBJECT
public:
explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole();
static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr);
static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr) {
return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut);
}
void setClientModel(ClientModel *model);
enum MessageClass {
MC_ERROR,
MC_DEBUG,
CMD_REQUEST,
CMD_REPLY,
CMD_ERROR
};
enum TabTypes {
TAB_INFO = 0,
TAB_CONSOLE = 1,
TAB_GRAPH = 2,
TAB_PEERS = 3
};
protected:
virtual bool eventFilter(QObject* obj, QEvent *event);
void keyPressEvent(QKeyEvent *);
private Q_SLOTS:
void on_lineEdit_returnPressed();
void on_tabWidget_currentChanged(int index);
/** open the debug.log from the current datadir */
void on_openDebugLogfileButton_clicked();
/** change the time range of the network traffic graph */
void on_sldGraphRange_valueChanged(int value);
/** update traffic statistics */
void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut);
void resizeEvent(QResizeEvent *event);
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
/** Show custom context menu on Peers tab */
void showPeersTableContextMenu(const QPoint& point);
/** Show custom context menu on Bans tab */
void showBanTableContextMenu(const QPoint& point);
/** Hides ban table if no bans are present */
void showOrHideBanTableIfRequired();
/** clear the selected node */
void clearSelectedNode();
public Q_SLOTS:
void clear(bool clearHistory = true);
void fontBigger();
void fontSmaller();
void setFontSize(int newSize);
/** Append the message to the message widget */
void message(int category, const QString &message, bool html = false);
/** Set number of connections shown in the UI */
void setNumConnections(int count);
/** Set network state shown in the UI */
void setNetworkActive(bool networkActive);
/** Set number of blocks and last block date shown in the UI */
void setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers);
/** Set size (number of transactions and memory usage) of the mempool in the UI */
void setMempoolSize(long numberOfTxs, size_t dynUsage);
/** Go forward or back in history */
void browseHistory(int offset);
/** Scroll console view to end */
void scrollToEnd();
/** Handle selection of peer in peers list */
void peerSelected(const QItemSelection &selected, const QItemSelection &deselected);
/** Handle selection caching before update */
void peerLayoutAboutToChange();
/** Handle updated peer information */
void peerLayoutChanged();
/** Disconnect a selected node on the Peers tab */
void disconnectSelectedNode();
/** Ban a selected node on the Peers tab */
void banSelectedNode(int bantime);
/** Unban a selected node on the Bans tab */
void unbanSelectedNode();
/** set which tab has the focus (is visible) */
void setTabFocus(enum TabTypes tabType);
Q_SIGNALS:
// For RPC command executor
void stopExecutor();
void cmdRequest(const QString &command);
private:
void startExecutor();
void setTrafficGraphRange(int mins);
/** show detailed information on ui about selected node */
void updateNodeDetail(const CNodeCombinedStats *stats);
enum ColumnWidths
{
ADDRESS_COLUMN_WIDTH = 200,
SUBVERSION_COLUMN_WIDTH = 150,
PING_COLUMN_WIDTH = 80,
BANSUBNET_COLUMN_WIDTH = 200,
BANTIME_COLUMN_WIDTH = 250
};
Ui::RPCConsole *ui;
ClientModel *clientModel;
QStringList history;
int historyPtr;
QString cmdBeforeBrowsing;
QList<NodeId> cachedNodeids;
const PlatformStyle *platformStyle;
RPCTimerInterface *rpcTimerInterface;
QMenu *peersTableContextMenu;
QMenu *banTableContextMenu;
int consoleFontSize;
QCompleter *autoCompleter;
QThread thread;
/** Update UI with latest network info from model. */
void updateNetworkState();
};
#endif // VAL_QT_RPCCONSOLE_H
| [
"rishabhworking@gmail.com"
] | rishabhworking@gmail.com |
74fb8f8384b6e0d7b70c1ef55eeb2573b184d7bf | 22172c29a36537e27fd273406eaec993daa8b371 | /eeprom_i2c.cpp | 8771436bd67cb6475c28f9a72ae4c36383a7a06e | [
"MIT"
] | permissive | stuwilkins/eeprom_i2c | 33fcb0863c7f381d674427ebc43b2fcfae67ecd0 | 42d9e12dbcf781fb709c090f1d44702969098491 | refs/heads/master | 2020-03-25T15:48:49.661878 | 2019-01-20T17:41:09 | 2019-01-20T17:41:09 | 143,902,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,163 | cpp | /*
* =====================================================================================
*
* Filename: eeprom_i2c.cpp
*
* Description:
*
* Version: 1.0
* Created: 07/14/2018 13:05:17
* Revision: none
* Compiler: gcc
*
* Author: Stuart B. Wilkins (sbw), stuwilkins@mac.com
* Organization:
*
* =====================================================================================
*/
#include <Wire.h>
#include <uCRC16Lib.h>
#include <eeprom_i2c.h>
EEPROM_I2C::EEPROM_I2C(uint8_t addr)
{
_addr = addr;
}
int EEPROM_I2C::begin(void)
{
Wire.begin();
Wire.setClock(400000);
_chunk = 4;
return OK;
}
int EEPROM_I2C::writeIfDiff(uint16_t offset, uint8_t *data, int size, bool crc, bool verify)
{
if(size > EEPROM_BUFFER_SIZE)
{
return BUFFER_ERROR;
}
uint8_t _buffer[EEPROM_BUFFER_SIZE];
read(offset, _buffer, size, crc);
if(memcmp(_buffer, data, size))
{
if(verify)
{
writeAndVerify(offset, data, size, crc);
} else {
write(offset, data, size, crc);
}
} else {
return NO_WRITE;
}
return OK;
}
int EEPROM_I2C::writeAndVerify(uint16_t offset, uint8_t *data, int size, bool crc, int retries)
{
if(size > EEPROM_BUFFER_SIZE)
{
return BUFFER_ERROR;
}
int ok = retries;
while(ok)
{
write(offset, data, size, crc);
uint8_t _buffer[EEPROM_BUFFER_SIZE];
read(offset, _buffer, size, crc);
if(!memcmp(_buffer, data, size))
{
return OK;
}
ok--;
}
return VERIFY_FAILED;
}
void EEPROM_I2C::_write(uint16_t offset, uint8_t *data, int chunk)
{
Wire.beginTransmission(_addr);
Wire.write((int)(offset >> 8));
Wire.write((int)(offset & 0xFF));
for(int j=0;j<chunk;j++)
{
Wire.write((int)data[j]);
}
Wire.endTransmission();
delay(5);
}
int EEPROM_I2C::write(uint16_t offset, uint8_t *data, int size, bool crc)
{
uint8_t *ptr = data;
uint16_t _offset = offset;
for(int i = 0;i<size;i+=_chunk){
int _c = (size - i) > _chunk ? _chunk : (size - i);
_write(_offset, ptr, _c);
_offset += _c;
ptr += _c;
}
if(crc)
{
uint16_t c_crc = uCRC16Lib::calculate((char*)data, size);
_write(_offset, (uint8_t*)(&c_crc), sizeof(c_crc));
}
return OK;
}
void EEPROM_I2C::_read(uint16_t offset, uint8_t* data, int chunk)
{
Wire.beginTransmission(_addr);
Wire.write(offset >> 8);
Wire.write(offset & 0xFF);
Wire.endTransmission();
Wire.requestFrom(_addr, chunk);
int j=0;
while(Wire.available())
{
data[j++] = Wire.read();
}
}
int EEPROM_I2C::read(uint16_t offset, uint8_t* data, int size, bool crc)
{
uint8_t *data_ptr = data;
uint16_t _offset = offset;
for(int i = 0;i<size;i+=_chunk)
{
int _c = (size - i) > _chunk ? _chunk : (size - i);
_read(_offset, data_ptr, _c);
data_ptr += _c;
_offset += _c;
}
if(crc)
{
uint16_t c_crc, r_crc;
_read(_offset, (uint8_t*)(&r_crc), sizeof(r_crc));
c_crc = uCRC16Lib::calculate((char*)data, size);
if(c_crc != r_crc)
{
return VERIFY_FAILED;
}
}
return OK;
}
| [
"swilkins@bnl.gov"
] | swilkins@bnl.gov |
a6d6020788fe4312a4bcbeea600aaf347b030c59 | e2b51bd4959f9ff9a5d946355401c2b45d866c66 | /V21/Prediction.h | 2096ba182ce8bc8d67513e5e34a2ac53aa5c6943 | [] | no_license | BrandTime/Vault21 | 91be552cfffa72b825fe81343150b350cb4a735e | ed85ab7a36b9ede72bedbf3d940e5280bc9f678f | refs/heads/master | 2023-03-17T11:32:53.637385 | 2021-02-12T12:34:41 | 2021-02-12T12:34:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,168 | h | #pragma once
#include "stdafx.h"
#include "ObjectManager.h"
#include "NetClient.h"
#include "Geometry.h"
#include "ManagerTemplate.h"
namespace HACKUZAN {
class PredOutPut
{
public:
Vector3 CastPosition;
Vector3 UnitPosition;
std::vector<GameObject*> CollisionObjects;
HitChance HitsChance = HitChance::Immobile;
PredOutPut(Vector3 castposition, Vector3 unitposition, std::vector<GameObject*> collisionobjects, HitChance hitchance)
{
CastPosition = castposition;
UnitPosition = unitposition;
CollisionObjects = collisionobjects;
HitsChance = hitchance;
}
PredOutPut() {};
};
inline Vector3 PredGetUnitPosition(GameObject* target, float delay)
{
delay = delay + NetClient::Instance->GetPing() / 1000;
std::vector<Vector3> waypoint = target->GetWaypointList();
if (waypoint.size() == 1)
return waypoint.front();
if (target->IsDashing() && PredAllDashData[target->NetworkId] != nullptr)
{
auto data = PredAllDashData[target->NetworkId];
float dashdistance = delay * data->dashSpeed;
return dashdistance >= Distance(target, data->end) ? data->end
: Extend(target->Position, data->end, dashdistance);
}
float distance = target->MoveSpeed * delay;
for (int i = 1; i < waypoint.size(); i = i + 1)
{
float waydistance = Distance(waypoint[i - 1], waypoint[i]);
if (waydistance >= distance)
{
return Extend(waypoint[i - 1], waypoint[i], distance);
}
if (i = waypoint.size() - 1)
return waypoint[i];
distance = distance - waydistance;
}
return target->Position;
}
inline vector<GameObject*> PredGetCollisions(Vector3 From, Vector3 To, int ColiFlag, GameObject* target, float spelldelay, float spellspeed, float spellradius)
{
vector<GameObject*> Collisons;
if (ColiFlag & kCollidesWithHeroes || ColiFlag & kCollidesWithMinions)
{
//GGame->PrintChat("a");
SArray<GameObject*> Heroes;
SArray<GameObject*> Minions;
SArray<GameObject*> AllUnits;
auto aibase_list = HACKUZAN::GameObject::GetAIBases();
for (size_t i = 0; i < aibase_list->size; i++)
{
auto unit = aibase_list->entities[i];
if (unit && unit->Hero() && unit->IsAlly() && unit->Alive() && unit->NetworkId != target->NetworkId) {
if (ColiFlag & kCollidesWithHeroes)
{
Heroes.Add(unit);
}
}
if (unit && unit->Minion() && unit->IsAlly() && unit->Alive() && unit->NetworkId == target->NetworkId) {
if (ColiFlag & kCollidesWithMinions)
{
if (Distance(From, unit->Position) + 500 <= 600) {
Minions.Add(unit);
}
}
}
}
AllUnits.AddRange(Heroes);
AllUnits.AddRange(Minions);
for (GameObject* hero : AllUnits.elems)
{
float delay = spelldelay + Distance(From, hero->Position) / spellspeed;
Vector3 pred = PredGetUnitPosition(hero, delay);
float mindistance = hero->GetBoundingRadius() + spellradius / 2 + 25;
if (Distance(hero->Position, From, To, true) < mindistance
|| Distance(pred, From, To, true) < mindistance
|| GetSegmentSegmentIntersections(From, To, hero->Position, pred))
{
Collisons.push_back(hero);
}
}
}
if (ColiFlag & kCollidesWithYasuoWall)
{
GameObject* Wall;
SArray<GameObject*> AllUnits;
auto aibase_list = HACKUZAN::GameObject::GetAIBases();
for (size_t i = 0; i < aibase_list->size; i++)
{
auto unit = aibase_list->entities[i];
if (unit) {
AllUnits.Add(unit);
}
}
AllUnits = AllUnits.Where([&](GameObject* i) {return i != nullptr && Contains(i->Name, "w_windwall_enemy_"); });
if (AllUnits.Any()) {
Wall = AllUnits.FirstOrDefault();
float length = 300 + 5 * 5;
Vector3 direction = Pendicular(Normalize((Wall->Position - PredLastYasuoWallCastPos)));
Vector3 WallStart = ToVec3((ToVec2(Wall->Position) + length * ToVec2(direction) / 2));
Vector3 WallEnd = ToVec3((ToVec2(Wall->Position) - length * ToVec2(direction) / 2));
float mindistance = 50 + spellradius / 2 + 50;
if (Distance(WallStart, From, To, true) < mindistance
|| Distance(WallEnd, From, To, true) < mindistance
|| GetSegmentSegmentIntersections(From, To, WallStart, WallEnd))
{
Collisons.push_back(Wall);
}
}
}
return Collisons;
}
inline PredOutPut PredGetPrediction(Vector3 startpos, float spellspeed, float spellrange, float spelldelay, GameObject* target, int collisionFlags, float spellradius)
{
if (target != nullptr) {
PredOutPut output;
output.HitsChance = HitChance::Impossible;
std::vector<Vector3> waypoint = target->GetWaypointList();
Vector3 RangeCheckFrom = startpos;
if (waypoint.size() == 1)
{
output.CastPosition = waypoint[0];
output.UnitPosition = waypoint[0];
output.HitsChance = HitChance::High;
}
float speed = target->IsDashing() && PredAllDashData[target->NetworkId] != nullptr ? PredAllDashData[target->NetworkId]->dashSpeed : target->MoveSpeed;
float realspelldelay = spelldelay; /*> spell->Radius() / 2.f / speed ? spell->GetDelay() - spell->Radius() / 2.f / speed : 0.f;*/
float time = 0.f;
for (int i = 1; i < waypoint.size(); i = i + 1)
{
float distance = Distance(waypoint[i - 1], waypoint[i]);
for (float j = 0; j <= distance; j = j + 5)
{
Vector3 Position = Extend(waypoint[i - 1], waypoint[i], j);
//time = Vector3(Position - RangeCheckFrom).Length() / spellspeed;
//time += realspelldelay;
float spelldistance = Distance(RangeCheckFrom, Position);
float targettime = time + j / speed;
float spelltime = realspelldelay + spelldistance / spellspeed;
if (abs(targettime - spelltime) < 10 / target->MoveSpeed)
{
output.CastPosition = Position;
output.UnitPosition = Position;
output.HitsChance = HitChance::High;
goto ABC;
}
}
time = time + distance / target->MoveSpeed;
}
ABC:
if (output.HitsChance > HitChance::Impossible)
{
if (PredAllNewPathTicks[target->NetworkId] != 0 && ClockFacade::GameTickCount() - PredAllNewPathTicks[target->NetworkId] < 100)
output.HitsChance = HitChance::VeryHigh;
if (Distance(target, RangeCheckFrom) <= 300)
output.HitsChance = HitChance::VeryHigh;
if (target->IsDashing())
output.HitsChance = HitChance::Dashing;
else if (waypoint.size() == 1 && (target->FindBuffType(BuffType::Stun) || target->FindBuffType(BuffType::Knockup) || target->FindBuffType(BuffType::Knockback) || target->FindBuffType(BuffType::Charm) || target->FindBuffType(BuffType::Flee) ||
target->FindBuffType(BuffType::Snare) || target->FindBuffType(BuffType::Fear) || target->FindBuffType(BuffType::Taunt) || target->FindBuffType(BuffType::Polymorph)))
output.HitsChance = HitChance::Immobile;
if (Distance(output.CastPosition, RangeCheckFrom) > spellrange && spellrange != 0)
{
output.HitsChance = HitChance::OutOfRange;
}
auto collisionobjects = PredGetCollisions(RangeCheckFrom, output.CastPosition, collisionFlags, target, spelldelay, spellspeed, spellradius);
if (collisionobjects.size() != 0)
{
output.HitsChance = HitChance::Collision;
}
output.CollisionObjects = collisionobjects;
return output;
}
output.CastPosition = waypoint.back();
output.UnitPosition = waypoint.back();
output.HitsChance = HitChance::Impossible;
output.CollisionObjects = PredGetCollisions(RangeCheckFrom, output.CastPosition, collisionFlags, target, spelldelay, spellspeed, spellradius);
return output;
}
}
//cast
inline bool CastPrediction(kSpellSlot slot, Vector3 startpos, float spellspeed, float spellrange, float spellradius, float spelldelay, GameObject* target, int collFlags, HitChance MinHitChance = HitChance::Medium)
{
PredOutPut pred = PredGetPrediction(startpos, spellspeed, spellrange, spelldelay, target, collFlags, spellradius);
if (pred.HitsChance >= MinHitChance)
{
ObjectManager::Player->CastSpellPos(slot, (DWORD)ObjectManager::Player, pred.CastPosition);
Draw.Line(startpos, pred.CastPosition, 2, IM_COL32(255, 255, 69, 255));
Draw.DrawCircle3D(pred.CastPosition, 30, spellradius, IM_COL32(255, 255, 69, 255));
return true;
}
return false;
}
} | [
"53059806+walangtayoexb@users.noreply.github.com"
] | 53059806+walangtayoexb@users.noreply.github.com |
a18b8f80aea76bd869847aed0e146fa6f0c24548 | 4dc775f76236beffc15eae55fdcdcf187bc4afaa | /src/qt/rpcconsole.cpp | f12d8de798d4d737011fa7593c50cd921a8ae7de | [
"MIT"
] | permissive | EnceladusProject/Enceladus_Coin | 21e15fc63211af078667ca80623fe0a30b6359e9 | 0ba1477f56e05c83b294d22adbb3bc8cdd05607c | refs/heads/master | 2020-04-01T11:13:46.405359 | 2018-11-10T16:22:21 | 2018-11-10T16:22:21 | 153,153,251 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,202 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Enceladus developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "peertablemodel.h"
#include "chainparams.h"
#include "main.h"
#include "rpcclient.h"
#include "rpcserver.h"
#include "util.h"
#include "json/json_spirit_value.h"
#include <openssl/crypto.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#endif
#include <QDir>
#include <QKeyEvent>
#include <QScrollBar>
#include <QThread>
#include <QTime>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
// Repair parameters
const QString SALVAGEWALLET("-salvagewallet");
const QString RESCAN("-rescan");
const QString ZAPTXES1("-zapwallettxes=1");
const QString ZAPTXES2("-zapwallettxes=2");
const QString UPGRADEWALLET("-upgradewallet");
const QString REINDEX("-reindex");
const struct {
const char* url;
const char* source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public slots:
void request(const QString& command);
signals:
void reply(int category, const QString& command);
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string>& args, const std::string& strCommand)
{
enum CmdParseState {
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach (char ch, strCommand) {
switch (state) {
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch (ch) {
case '"':
state = STATE_DOUBLEQUOTED;
break;
case '\'':
state = STATE_SINGLEQUOTED;
break;
case '\\':
state = STATE_ESCAPE_OUTER;
break;
case ' ':
case '\n':
case '\t':
if (state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default:
curarg += ch;
state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch (ch) {
case '\'':
state = STATE_ARGUMENT;
break;
default:
curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch (ch) {
case '"':
state = STATE_ARGUMENT;
break;
case '\\':
state = STATE_ESCAPE_DOUBLEQUOTED;
break;
default:
curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch;
state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if (ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch;
state = STATE_DOUBLEQUOTED;
break;
}
}
switch (state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString& command)
{
std::vector<std::string> args;
if (!parseCommandLine(args, command.toStdString())) {
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if (args.empty())
return; // Nothing to do
try {
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
} catch (json_spirit::Object& objError) {
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
} catch (std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
} catch (std::exception& e) {
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget* parent) : QDialog(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
cachedNodeid(-1)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
// Wallet Repair Buttons
connect(ui->btn_salvagewallet, SIGNAL(clicked()), this, SLOT(walletSalvage()));
connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan()));
connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1()));
connect(ui->btn_zapwallettxes2, SIGNAL(clicked()), this, SLOT(walletZaptxes2()));
connect(ui->btn_upgradewallet, SIGNAL(clicked()), this, SLOT(walletUpgrade()));
connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex()));
// set library version labels
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
ui->wallet_path->setText(QString::fromStdString(GetDataDir().string() + QDir::separator().toLatin1() + GetArg("-wallet", "wallet.dat")));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
startExecutor();
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
clear();
}
RPCConsole::~RPCConsole()
{
GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent* keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch (key) {
case Qt::Key_Up:
if (obj == ui->lineEdit) {
browseHistory(-1);
return true;
}
break;
case Qt::Key_Down:
if (obj == ui->lineEdit) {
browseHistory(1);
return true;
}
break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if (obj == ui->lineEdit) {
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if (obj == ui->messagesWidget && ((!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) {
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel* model)
{
clientModel = model;
ui->trafficGraph->setClientModel(model);
if (model) {
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks());
connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
setMasternodeCount(model->getMasternodeCountString());
connect(model, SIGNAL(strMasternodesChanged(QString)), this, SLOT(setMasternodeCount(QString)));
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64, quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
// connect the peerWidget selection model to our peerSelected() handler
connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this, SLOT(peerSelected(const QItemSelection&, const QItemSelection&)));
connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
}
}
static QString categoryClass(int category)
{
switch (category) {
case RPCConsole::CMD_REQUEST:
return "cmd-request";
break;
case RPCConsole::CMD_REPLY:
return "cmd-reply";
break;
case RPCConsole::CMD_ERROR:
return "cmd-error";
break;
default:
return "misc";
}
}
/** Restart wallet with "-salvagewallet" */
void RPCConsole::walletSalvage()
{
buildParameterlist(SALVAGEWALLET);
}
/** Restart wallet with "-rescan" */
void RPCConsole::walletRescan()
{
buildParameterlist(RESCAN);
}
/** Restart wallet with "-zapwallettxes=1" */
void RPCConsole::walletZaptxes1()
{
buildParameterlist(ZAPTXES1);
}
/** Restart wallet with "-zapwallettxes=2" */
void RPCConsole::walletZaptxes2()
{
buildParameterlist(ZAPTXES2);
}
/** Restart wallet with "-upgradewallet" */
void RPCConsole::walletUpgrade()
{
buildParameterlist(UPGRADEWALLET);
}
/** Restart wallet with "-reindex" */
void RPCConsole::walletReindex()
{
buildParameterlist(REINDEX);
}
/** Build command-line parameter list for restart */
void RPCConsole::buildParameterlist(QString arg)
{
// Get command-line arguments and remove the application name
QStringList args = QApplication::arguments();
args.removeFirst();
// Remove existing repair-options
args.removeAll(SALVAGEWALLET);
args.removeAll(RESCAN);
args.removeAll(ZAPTXES1);
args.removeAll(ZAPTXES2);
args.removeAll(UPGRADEWALLET);
args.removeAll(REINDEX);
// Append repair parameter to command line.
args.append(arg);
// Send command-line arguments to BitcoinGUI::handleRestart()
emit handleRestart(args);
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
history.clear();
historyPtr = 0;
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for (int i = 0; ICON_MAPPING[i].url; ++i) {
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Courier, Courier New, Lucida Console, monospace; font-size: 12px; } " // Todo: Remove fixed font-size
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } ");
message(CMD_REPLY, (tr("Welcome to the ENCP RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")),
true);
}
void RPCConsole::reject()
{
// Ignore escape keypress if this is not a seperate window
if (windowType() != Qt::Widget)
QDialog::reject();
}
void RPCConsole::message(int category, const QString& message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if (html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
QString connections = QString::number(count) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumBlocks(int count)
{
ui->numberOfBlocks->setText(QString::number(count));
if (clientModel)
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
void RPCConsole::setMasternodeCount(const QString& strMasternodes)
{
ui->masternodeCount->setText(strMasternodes);
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if (!cmd.isEmpty()) {
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while (history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if (historyPtr < 0)
historyPtr = 0;
if (historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if (historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor* executor = new RPCExecutor();
executor->moveToThread(thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int, QString)), this, SLOT(message(int, QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if (ui->tabWidget->widget(index) == ui->tab_console) {
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar* scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
QString RPCConsole::FormatBytes(quint64 bytes)
{
if (bytes < 1024)
return QString(tr("%1 B")).arg(bytes);
if (bytes < 1024 * 1024)
return QString(tr("%1 KB")).arg(bytes / 1024);
if (bytes < 1024 * 1024 * 1024)
return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
}
void RPCConsole::showInfo()
{
ui->tabWidget->setCurrentIndex(0);
show();
}
void RPCConsole::showConsole()
{
ui->tabWidget->setCurrentIndex(1);
show();
}
void RPCConsole::showNetwork()
{
ui->tabWidget->setCurrentIndex(2);
show();
}
void RPCConsole::showPeers()
{
ui->tabWidget->setCurrentIndex(3);
show();
}
void RPCConsole::showRepair()
{
ui->tabWidget->setCurrentIndex(4);
show();
}
void RPCConsole::showConfEditor()
{
GUIUtil::openConfigfile();
}
void RPCConsole::showMNConfEditor()
{
GUIUtil::openMNConfigfile();
}
void RPCConsole::peerSelected(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(deselected);
if (!clientModel || selected.indexes().isEmpty())
return;
const CNodeCombinedStats* stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel)
return;
const CNodeCombinedStats* stats = NULL;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeid == -1) // no node selected yet
return;
// find the currently selected row
int selectedRow;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (selectedModelIndex.isEmpty())
selectedRow = -1;
else
selectedRow = selectedModelIndex.first().row();
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);
if (detailNodeRow < 0) {
// detail node dissapeared from table (node disconnected)
fUnselect = true;
cachedNodeid = -1;
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
} else {
if (detailNodeRow != selectedRow) {
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0) {
ui->peerWidget->selectionModel()->select(QItemSelection(selectedModelIndex.first(), selectedModelIndex.last()),
QItemSelectionModel::Deselect);
}
if (fReselect) {
ui->peerWidget->selectRow(detailNodeRow);
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats* stats)
{
// Update cached nodeid
cachedNodeid = stats->nodeStats.nodeid;
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerVersion->setText(QString("%1").arg(stats->nodeStats.nVersion));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(stats->nodeStats.nStartingHeight));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
} else {
ui->peerBanScore->setText(tr("Fetching..."));
ui->peerSyncHeight->setText(tr("Fetching..."));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent* event)
{
QWidget::showEvent(event);
if (!clientModel)
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
}
void RPCConsole::hideEvent(QHideEvent* event)
{
QWidget::hideEvent(event);
if (!clientModel)
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
}
void RPCConsole::showBackups()
{
GUIUtil::showBackups();
}
| [
""
] | |
d46ee2f16c1489e91cd8494117167a6b5d03af23 | 45b242225b117852d0b4f3768ed845614e3e96ed | /src/DGL_SkyBox.h | b4e57dde15aa8d96fa74cd065ddbd707219bad71 | [
"Apache-2.0"
] | permissive | da0x/xr.desktop | d7da667470d3bb75ad59759d0fc7d66a36021f83 | 218a7cff7a9be5865cf786d7cad31da6072f7348 | refs/heads/master | 2021-05-28T02:15:19.583099 | 2014-12-14T20:20:44 | 2014-12-14T20:20:44 | 28,004,479 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,547 | h | //C++
/*
----------------------------------------------------
The Desktop Project
------------------
Copyright 2004 Daher Alfawares
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------
*/
#ifndef ___DSKYBOX_H
#define ___DSKYBOX_H
/*
TODO List:
- ...
*/
namespace DGL {
class SkyBox {
private:
float SkyboxWidth,SkyboxHeight,SkyboxLength;
DGL::Texture top,bottom,left,right,front,back;
public:
void InitSkybox(char *name){
LogPrint(va("SkyBox '%s' Initializations:",name));
DGL::Texture::Filter skyfilter(Texture::Filter::FilterName::TRILINEAR, true);
top .Build(va("textures/skies/%sTop.jpg", name), skyfilter);
bottom .Build(va("textures/skies/%sBottom.jpg", name), skyfilter);
left .Build(va("textures/skies/%sLeft.jpg", name), skyfilter);
right .Build(va("textures/skies/%sRight.jpg", name), skyfilter);
front .Build(va("textures/skies/%sFront.jpg", name), skyfilter);
back .Build(va("textures/skies/%sBack.jpg", name), skyfilter);
SkyboxWidth = 12.0f;
SkyboxLength = 12.0f;
SkyboxHeight = 8.0f;
}
void Render(){
DMacro_TraceEnter(SkyBox::Render);
float x,y,z;
glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
x = - this->SkyboxWidth / 2.0f;
y = - this->SkyboxHeight / 2.0f;
z = - this->SkyboxLength / 2.0f;
Color::ColorWhite().MakeCurrent();
glPushMatrix();
float m[4][4];
glGetFloatv(GL_MODELVIEW_MATRIX, (float *)m);
m[3][0] = m[3][1] = m[3][2] = 0.0f;
glLoadMatrixf( (float *)m);
glBindTexture( GL_TEXTURE_2D, this->back);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->front);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->top);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->bottom);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->left);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->right);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glPopAttrib();
glPopMatrix();
DMacro_TraceLeave();
}
void Destroy()
{
this->top.Delete();
this->bottom.Delete();
this->left.Delete();
this->right.Delete();
this->front.Delete();
this->back.Delete();
}
};
class SkyBox_HalfDom {
protected:
float SkyboxWidth,SkyboxHeight,SkyboxLength;
DGL::Texture top,left,right,front,back;
public:
void InitSkybox(char *name){
LogPrint(va("SkyBox '%s' Initializations:",name));
DGL::Texture::Filter skyfilter(Texture::Filter::FilterName::TRILINEAR, true);
top .Build(va("textures/skies/%sTop.jpg", name), skyfilter);
left .Build(va("textures/skies/%sLeft.jpg", name), skyfilter);
right .Build(va("textures/skies/%sRight.jpg", name), skyfilter);
front .Build(va("textures/skies/%sFront.jpg", name), skyfilter);
back .Build(va("textures/skies/%sBack.jpg", name), skyfilter);
SkyboxWidth = 12.0f;
SkyboxLength = 12.0f;
SkyboxHeight = 6.0f;
}
void Render(){
DMacro_TraceEnter(SkyBox_HalfDom::Render);
float x,y,z;
glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
x = - SkyboxWidth / 2.0f;
y = 0.0f;
z = - SkyboxLength / 2.0f;
Color::ColorWhite().MakeCurrent();
glPushMatrix();
float m[4][4];
glGetFloatv(GL_MODELVIEW_MATRIX, (float *)m);
m[3][0] = m[3][1] = m[3][2] = 0.0f;
glLoadMatrixf( (float *)m);
glBindTexture( GL_TEXTURE_2D, back);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, front);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glEnd();
glBindTexture( GL_TEXTURE_2D, top);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, left);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, right);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glPopAttrib();
glPopMatrix();
DMacro_TraceLeave();
}
void Destroy()
{
this->top.Delete();
this->left.Delete();
this->right.Delete();
this->front.Delete();
this->back.Delete();
}
};
////////////////////////////////
// static skybox
class SkyBox_static {
protected:
float SkyboxWidth,SkyboxHeight,SkyboxLength;
DGL::Texture top,left,right,front,back;
public:
void InitSkybox(char *name, float width, float length, float height){
LogPrint(va("SkyBox '%s' Initializations:",name));
DGL::Texture::Filter skyfilter(Texture::Filter::FilterName::TRILINEAR, true);
top .Build(va("textures/skies/%sTop.jpg", name), skyfilter);
left .Build(va("textures/skies/%sLeft.jpg", name), skyfilter);
right .Build(va("textures/skies/%sRight.jpg", name), skyfilter);
front .Build(va("textures/skies/%sFront.jpg", name), skyfilter);
back .Build(va("textures/skies/%sBack.jpg", name), skyfilter);
SkyboxWidth = width;
SkyboxLength = length;
SkyboxHeight = height;
}
void Render(){
DMacro_TraceEnter(SkyBox_static::Render);
float x,y,z;
glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
// glDisable(GL_DEPTH_TEST);
x = - SkyboxWidth / 2.0f;
y = 0.0f;
z = - SkyboxLength / 2.0f;
Color::ColorWhite().MakeCurrent();
glBindTexture( GL_TEXTURE_2D, back);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, front);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glEnd();
glBindTexture( GL_TEXTURE_2D, top);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, left);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, right);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glPopAttrib();
glPopMatrix();
DMacro_TraceLeave();
}
void Destroy()
{
this->top.Delete();
this->left.Delete();
this->right.Delete();
this->front.Delete();
this->back.Delete();
}
};
}//namespace DGL
#endif // ___DSKYBOX_H | [
"daher.alfawares@live.com"
] | daher.alfawares@live.com |
fbb25f84020137d214bef66e31d7972a8c169a6f | 3e2af944f53e2640e147c17acac703af16548c8f | /logic/animation.cpp | 28dcc9267c1304231e9f8bc9a45026684017f9a4 | [] | no_license | jneem/anim | 5d0721342c254907b5bfc0c2609ecdadd209c62a | ce0c362def116046f56abdd79a915c57d998008b | refs/heads/master | 2020-05-30T22:47:15.690850 | 2019-08-31T19:20:34 | 2019-08-31T19:20:34 | 189,998,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,486 | cpp | #include "animation.h"
#include "changingpath.h"
#include "snippet.h"
#include <QDebug>
#include <QPainterPath>
Animation::Animation(QObject *parent) : QObject(parent)
{
}
// After adding a snippet to an animation, you must never modify it again. Otherwise, updatedPaths might not be correct.
void Animation::addSnippet(Snippet *s)
{
Q_ASSERT(!snippets.contains(s));
snippets.insert(s);
emit snippetAdded(s);
}
void
Animation::removeSnippet(Snippet *s)
{
Q_ASSERT(snippets.contains(s));
snippets.remove(s);
emit snippetRemoved(s);
}
QVector<RenderedPath>
Animation::updatedPaths(qint64 prev_t, qint64 cur_t)
{
QVector<RenderedPath> ret;
// TODO: we're looping over all snippets here, but we could be more efficient.
for (Snippet *s : snippets) {
QVector<RenderedPath> v;
if (dirty_snippets.contains(s)) {
v = s->changedPaths(s->startTime(), cur_t);
} else {
v = s->changedPaths(prev_t, cur_t);
}
ret.append(std::move(v));
}
dirty_snippets.clear();
return ret;
}
qint64 Animation::endTime() const
{
// TODO: this is inefficient
qint64 ret = 0;
for (Snippet *s : snippets) {
ret = std::max(ret, s->endTime());
}
return ret;
}
void Animation::warpSnippet(Snippet *s, qint64 old_time, qint64 new_time)
{
Q_ASSERT(snippets.contains(s));
dirty_snippets.insert(s);
s->addLerp(old_time, new_time);
emit snippetChanged(s);
}
| [
"joeneeman@gmail.com"
] | joeneeman@gmail.com |
2749e6df919ca99ae8c9cfd2132574d3707878bc | 8b877fd49a93d461588b85918728114effe2a847 | /GUI/GUIwithconnections/WidgetsUsed/Compass/compass.cpp | 096f46ee4237f7d02bf66ecccb6546c296f6a868 | [] | no_license | NaviPolytechnique/GUI | 301da3ef0ab9154a0853d058519b5abf6211d5ae | ae85f8bed7b815a7d2d3208ab561ceb22e7133aa | refs/heads/master | 2016-08-12T16:09:57.381982 | 2016-03-23T21:18:55 | 2016-03-23T21:18:55 | 44,568,567 | 3 | 1 | null | 2015-12-22T10:41:57 | 2015-10-19T22:47:53 | C++ | UTF-8 | C++ | false | false | 2,008 | cpp | #include "compass.h"
#include "ui_compass.h"
Compass::Compass(QWidget *parent) :
QDialog(parent),
ui(new Ui::Compass)
{
ui->setupUi(this);
mCompassGauge = new QcGaugeWidget;
mCompassGauge->addBackground(79);
QcBackgroundItem *bkg1 = mCompassGauge->addBackground(72);
bkg1->clearrColors();
bkg1->addColor(0.1,Qt::black);
bkg1->addColor(1.0,Qt::white);
QcBackgroundItem *bkg2 = mCompassGauge->addBackground(68);
bkg2->clearrColors();
bkg2->addColor(0.1,Qt::white);
bkg2->addColor(1.0,Qt::black);
QcLabelItem *w = mCompassGauge->addLabel(60);
w->setText("W");
w->setAngle(0);
w->setColor(Qt::white);
QcLabelItem *n = mCompassGauge->addLabel(60);
n->setText("N");
n->setAngle(90);
n->setColor(Qt::white);
QcLabelItem *e = mCompassGauge->addLabel(60);
e->setText("E");
e->setAngle(180);
e->setColor(Qt::white);
QcLabelItem *s = mCompassGauge->addLabel(60);
s->setText("S");
s->setAngle(270);
s->setColor(Qt::white);
QcDegreesItem *deg = mCompassGauge->addDegrees(50);
deg->setStep(5);
deg->setMaxDegree(270);
deg->setMinDegree(-75);
deg->setColor(Qt::white);
mCompassNeedle = mCompassGauge->addNeedle(60);
mCompassNeedle->setNeedle(QcNeedleItem::CompassNeedle);
mCompassNeedle->setValueRange(0,360);
mCompassNeedle->setMaxDegree(360);
mCompassNeedle->setMinDegree(0);
mCompassGauge->addBackground(6);
mCompassGauge->addGlass(68);
ui->compass->addWidget(mCompassGauge);
}
void Compass::MAJCompass(QString DroneStatusMAJ){
//roll
QStringList LED=DroneStatusMAJ.split(",");
QString s1yaw=LED[2];
QStringList s2yaw=s1yaw.split( ".");
QString s3yaw=s2yaw.at(0);
int yaw=s3yaw.toInt();
while (yaw<(-90)|| yaw > 270 ){
if (yaw<(-90)){
yaw+=360;
}
else{
yaw-=360;
}
}
mCompassNeedle->setCurrentValue(yaw+90);
}
Compass::~Compass()
{
delete ui;
}
| [
"mr.pierrely@gmail.com"
] | mr.pierrely@gmail.com |
504a63c4bacd6e8bc3aeb11828eaf22dfbb91878 | 5094f4c1029ea2a1e525a82c8c6ed1bd1119bea5 | /test.cc | 48e78ce447662268c1c49b5871bea9fce8086c3e | [
"BSD-3-Clause"
] | permissive | xuefeng529/evcpp | d3dcef90392735d8fece7f845abf04e6f289a129 | bccf9b47830ad6f98223e2166321b3609164fbc6 | refs/heads/master | 2020-06-12T17:30:42.411685 | 2015-02-25T07:21:59 | 2015-02-25T07:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | cc | // Copyright 2010, Shuo Chen. All rights reserved.
// http://github.com/chenshuo/evcpp
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
#include "evcpp.h"
void onConnect(evcpp::TcpConnectionPtr conn)
{
printf("onConnect %zd\n", conn.use_count());
}
int main()
{
evcpp::EventLoop loop;
evcpp::Listener listener(&loop, 1234);
listener.setNewConnectionCallback(onConnect);
loop.loop();
}
| [
"chenshuo@chenshuo.com"
] | chenshuo@chenshuo.com |
158f28dd90325d169263144298c7b75be50ee2f7 | 0c7e20a002108d636517b2f0cde6de9019fdf8c4 | /Sources/Elastos/Packages/Apps/Calculator/inc/elastos/droid/calculator2/CCalculatorPadLayout.h | 75eeb2ceb72a909b13f61d4d95fc58111cd0edcf | [
"Apache-2.0"
] | permissive | kernal88/Elastos5 | 022774d8c42aea597e6f8ee14e80e8e31758f950 | 871044110de52fcccfbd6fd0d9c24feefeb6dea0 | refs/heads/master | 2021-01-12T15:23:52.242654 | 2016-10-24T08:20:15 | 2016-10-24T08:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | h | #ifndef _ELASTOS_DROID_CALCULATOR2_CCALCULATORPADLAYOUT_H__
#define _ELASTOS_DROID_CALCULATOR2_CCALCULATORPADLAYOUT_H__
#include "_Elastos_Droid_Calculator2_CCalculatorPadLayout.h"
#include "elastos/droid/calculator2/CalculatorPadLayout.h"
namespace Elastos {
namespace Droid {
namespace Calculator2 {
CarClass(CCalculatorPadLayout), public CalculatorPadLayout
{
public:
CAR_OBJECT_DECL()
};
} // namespace Calculator2
} // namespace Droid
} // namespace Elastos
#endif // _ELASTOS_DROID_CALCULATOR2_CCALCULATORPADLAYOUT_H__ | [
"bao.rongzhen@kortide.com"
] | bao.rongzhen@kortide.com |
68dee00ea29895bdc5c7f97260a0969c619e92de | ccae3c9b20fa3c895042a1c7aa0815fd0faec141 | /trunk/TestCode/DekTecTest/ZQASIRenderFilter/ASIDevConfig.h | d612af581c002efc747d7fe50e17cdea19a11fc5 | [] | no_license | 15831944/TxUIProject | 7beaf17eb3642bcffba2bbe8eaa7759c935784a0 | e90f3319ad0e57c0012e0e3a7e457851c2c6f0f1 | refs/heads/master | 2021-12-03T10:05:27.018212 | 2014-05-16T08:16:17 | 2014-05-16T08:16:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322 | h | #pragma once
#include "IASIDevPreConfig.h"
class CASIDevConfig :
public IASIDevPreConfig
{
public:
CASIDevConfig(void);
~CASIDevConfig(void);
DECLARE_IUNKNOWN
STDMETHODIMP set_param (
devparam *paramIn //
) PURE;
STDMETHODIMP get_param (
devparam *paramOut //
) PURE;
devparam m_DevParam;
};
| [
"tyxwgy@sina.com"
] | tyxwgy@sina.com |
d23d2f014efcb1a74325e66d63078f25af814844 | 7319661bce6b667b9db71d1cafd6bdaee9f1e264 | /code/test/test1.cpp | f607d7a06daef7b3be7e37160575e271030f7238 | [] | no_license | Silmarillli/ObjectOrientedSoftware | cef77e0282b90d7f70ef3791ea57d6d9f1d278f6 | 63319c4d71359e47e4777c6ee00f80eb8435f9ed | refs/heads/master | 2020-03-24T20:54:36.278670 | 2018-07-31T11:16:43 | 2018-07-31T11:16:43 | 142,900,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,588 | cpp | #include <string>
#include <ostream>
#include <iostream>
#include <string>
#include "Debug.h"
#include "Instance.h"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
int main(int argc, char *argv[]) {
Ptr<Instance::Manager> manager = shippingInstanceManager();
if (manager == NULL) {
cerr << "Unexpected NULL manager." << endl;
return 1;
}
Ptr<Instance> stats = manager->instanceNew("myStats", "Stats");
if (stats == NULL) {
cerr << "Unexpected NULL stats." << endl;
return 1;
}
Ptr<Instance> conn = manager->instanceNew("myConn", "Conn");
Ptr<Instance> fleet = manager->instanceNew("myFleet", "Fleet");
fleet->attributeIs("Boat, speed", "20");
fleet->attributeIs("Boat, capacity", "1000");
fleet->attributeIs("Boat, cost", "30");
fleet->attributeIs("Truck, speed", "60");
fleet->attributeIs("Truck, capacity", "50");
fleet->attributeIs("Truck, cost", "20");
fleet->attributeIs("Plane, speed", "700");
fleet->attributeIs("Plane, capacity", "200");
fleet->attributeIs("Plane, cost", "60");
Ptr<Instance> customer1 = manager->instanceNew("customer1", "Customer");
Ptr<Instance> port1 = manager->instanceNew("port1", "Port");
Ptr<Instance> port2 = manager->instanceNew("port2", "Port");
Ptr<Instance> port3 = manager->instanceNew("port3", "Port");
Ptr<Instance> planeTerminal1 = manager->instanceNew("planeTerminal1", "Plane terminal");
Ptr<Instance> truckTerminal1 = manager->instanceNew("truckTerminal1", "Truck terminal");
Ptr<Instance> boatTerminal1 = manager->instanceNew("boatTerminal1", "Boat terminal");
Ptr<Instance> planeSegA = manager->instanceNew("planeSegA", "Plane segment");
Ptr<Instance> planeSegB = manager->instanceNew("planeSegB", "Plane segment");
Ptr<Instance> planeSegC = manager->instanceNew("planeSegC", "Plane segment");
Ptr<Instance> planeSegD = manager->instanceNew("planeSegD", "Plane segment");
Ptr<Instance> planeSegE = manager->instanceNew("planeSegE", "Plane segment");
Ptr<Instance> planeSegF = manager->instanceNew("planeSegF", "Plane segment");
Ptr<Instance> planeSegG = manager->instanceNew("planeSegG", "Plane segment");
Ptr<Instance> planeSegH = manager->instanceNew("planeSegH", "Plane segment");
Ptr<Instance> planeSegX = manager->instanceNew("planeSegX", "Plane segment");
Ptr<Instance> truckSegA = manager->instanceNew("truckSegA", "Truck segment");
Ptr<Instance> truckSegB = manager->instanceNew("truckSegB", "Truck segment");
Ptr<Instance> truckSegC = manager->instanceNew("truckSegC", "Truck segment");
Ptr<Instance> truckSegD = manager->instanceNew("truckSegD", "Truck segment");
Ptr<Instance> truckSegX = manager->instanceNew("truckSegX", "Truck segment");
Ptr<Instance> boatSegA = manager->instanceNew("boatSegA", "Boat segment");
Ptr<Instance> boatSegB = manager->instanceNew("boatSegB", "Boat segment");
Ptr<Instance> boatSegC = manager->instanceNew("boatSegC", "Boat segment");
Ptr<Instance> boatSegD = manager->instanceNew("boatSegD", "Boat segment");
Ptr<Instance> boatSegX = manager->instanceNew("boatSegX", "Boat segment");
Ptr<Instance> boatSegY = manager->instanceNew("boatSegY", "Boat segment");
planeSegA->attributeIs("return segment", "planeSegB");
planeSegA->attributeIs("source", "customer1");
planeSegB->attributeIs("source", "planeTerminal1");
planeSegA->attributeIs("expedite support", "yes");
planeSegA->attributeIs("length", "300.0");
planeSegA->attributeIs("difficulty", "4.0");
planeSegB->attributeIs("expedite support", "yes");
planeSegB->attributeIs("length", "400.0");
planeSegB->attributeIs("difficulty", "2.0");
planeSegC->attributeIs("return segment", "planeSegD");
planeSegC->attributeIs("source", "planeTerminal1");
planeSegD->attributeIs("source", "port1");
planeSegC->attributeIs("length", "800");
planeSegD->attributeIs("length", "800");
planeSegE->attributeIs("return segment", "planeSegF");
planeSegE->attributeIs("source", "planeTerminal1");
planeSegF->attributeIs("source", "port2");
planeSegE->attributeIs("length", "1000");
planeSegF->attributeIs("length", "1200");
planeSegE->attributeIs("expedite support", "yes");
planeSegF->attributeIs("expedite support", "yes");
planeSegG->attributeIs("return segment", "planeSegH");
planeSegG->attributeIs("source", "port1");
planeSegH->attributeIs("source", "port2");
planeSegG->attributeIs("length", "2000");
planeSegH->attributeIs("length", "2000");
planeSegX->attributeIs("return segment", "");
planeSegX->attributeIs("source", "planeTerminal1");
planeSegX->attributeIs("length", "1337");
truckSegA->attributeIs("return segment", "truckSegB");
truckSegA->attributeIs("source", "customer1");
truckSegA->attributeIs("length", "250");
truckSegA->attributeIs("difficulty", "4.0");
truckSegB->attributeIs("length", "250.0");
truckSegB->attributeIs("difficulty", "4.0");
truckSegB->attributeIs("source", "truckTerminal1");
truckSegC->attributeIs("return segment", "truckSegD");
truckSegC->attributeIs("source", "truckTerminal1");
truckSegC->attributeIs("expedite support", "yes");
truckSegD->attributeIs("source", "port1");
truckSegC->attributeIs("length", "200");
truckSegD->attributeIs("length", "200");
truckSegX->attributeIs("source", "port3");
truckSegX->attributeIs("length", "500");
boatSegA->attributeIs("return segment", "boatSegB");
boatSegA->attributeIs("source", "port1");
boatSegB->attributeIs("source", "boatTerminal1");
boatSegA->attributeIs("length", "1300");
boatSegB->attributeIs("length", "1400");
boatSegC->attributeIs("return segment", "boatSegD");
boatSegC->attributeIs("source", "boatTerminal1");
boatSegD->attributeIs("source", "port2");
boatSegC->attributeIs("length", "900");
boatSegD->attributeIs("length", "900");
boatSegX->attributeIs("return segment", "boatSegY");
boatSegX->attributeIs("source", "customer1");
boatSegY->attributeIs("source", "");
boatSegX->attributeIs("length", "200");
boatSegY->attributeIs("length", "200");
cout << "LOCATIONS:" << endl;
cout << "Customers: " << stats->attribute("Customer") << endl;
cout << "Ports: " << stats->attribute("Port") << endl;
cout << "Truck terminals: " << stats->attribute("Truck terminal") << endl;
cout << "Boat terminals: " << stats->attribute("Boat terminal") << endl;
cout << "Plane terminals: " << stats->attribute("Plane terminal") << endl;
cout << endl;
cout << "SEGMENTS:" << endl;
cout << "Truck segments: " << stats->attribute("Truck segment") << endl;
cout << "Boat segments: " << stats->attribute("Boat segment") << endl;
cout << "Plane segments: " << stats->attribute("Plane segment") << endl;
cout << endl;
cout << "EXPEDITE SUPPORT:" << endl;
cout << "Exp %: " << stats->attribute("expedite percentage") << endl;
cout << endl;
cout << "FLEET STATS:" << endl;
cout << "Boat speed: " << fleet->attribute("Boat, speed") << endl;
cout << "Boat cost: " << fleet->attribute("Boat, cost") << endl;
cout << "Boat capacity: " << fleet->attribute("Boat, capacity") << endl;
cout << "Plane speed: " << fleet->attribute("Plane, speed") << endl;
cout << "Plane cost: " << fleet->attribute("Plane, cost") << endl;
cout << "Plane capacity: " << fleet->attribute("Plane, capacity") << endl;
cout << "Truck speed: " << fleet->attribute("Truck, speed") << endl;
cout << "Truck cost: " << fleet->attribute("Truck, cost") << endl;
cout << "Truck capacity: " << fleet->attribute("Truck, capacity") << endl;
cout << endl;
cout << "explore customer1 : expedited " << endl;
cout << conn->attribute("explore customer1 : expedited");
cout << endl;
cout << "explore customer1 : cost 150000 time 1000" << endl;
cout << conn->attribute("explore customer1 : cost 150000 time 1000");
cout << endl;
cout << "connect customer1 : port2" << endl;
cout << conn->attribute("connect customer1 : port2");
cout << endl;
cout << "Removing myConn" << endl;
manager->instanceDel("myConn");
cout << "Making secondConn" << endl;
Ptr<Instance> secondConn = manager->instanceNew("secondConn", "Conn");
cout << "connect customer1 : port2" << endl;
cout << secondConn->attribute("connect customer1 : port2");
cout << "Done!" << endl;
return 0;
}
| [
"jishnu.nishaanth@gmail.com"
] | jishnu.nishaanth@gmail.com |
c2283514b616badbd5d4dfdb8a6dc5e5b4cd39ea | 50aa6227fb65ef56e230d890711ad248a2a6634f | /Saturn/include/Graphics/Sprite.hpp | e460abf383d31b0744e8477e85e7453521f44dd7 | [
"MIT"
] | permissive | Tackwin/BossRoom | 7b63fb354a9261fa56306bbb8cbb0fa3c34ea1ad | ecad5853e591b9edc54e75448547e20e14964f72 | refs/heads/master | 2021-01-19T19:52:17.076149 | 2019-01-10T04:33:27 | 2019-01-10T04:33:27 | 67,225,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | hpp | #pragma once
#include "Concepts/Delete.hpp"
#include "FrameBuffer.hpp"
#include "Transform.hpp"
#include "Texture.hpp"
#include "VAO.hpp"
struct SpriteInfo {
Texture* texture;
Transform transform;
VAO mesh;
};
class Sprite : NoCopy {
public:
Sprite();
Sprite(const Sprite&& that);
Sprite& operator=(const Sprite&& that);
void set_texture(const std::string& key);
void render(const FrameBuffer& target) const;
private:
SpriteInfo _info;
}; | [
"tackwinbrx@hotmail.fr"
] | tackwinbrx@hotmail.fr |
0f8983822ec6ea0ee29dff236908887888dc74cd | 013c7539d6fb9ffc30740a33691aac902b11b06e | /practive/NCU/18summer/7.17/D.cpp | 9d3651a6d9a0fa8415559f0fc81eb199206ad2e0 | [] | no_license | eternity6666/life-in-acm | 1cc4ebaa65af62219130d53c9be534ad31b361e2 | e279121a28e179d0de33674b9ce10c6763d78d32 | refs/heads/master | 2023-04-13T07:50:58.231217 | 2023-04-09T09:23:24 | 2023-04-09T09:23:24 | 127,930,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | #include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <fstream>
#include <sstream>
using namespace std;
// #define usefre
double calculate1(int);
double calculate2(int);
int main()
{
#ifdef usefre
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int t;
cin>>t;
while(t--)
{
int numCase=0;
int m,n;
while(cin>>n>>m)
{
cout<<"Case #"<<++numCase<<": ";
double nAns=calculate1(n);
double mAns=calculate2(m);
printf("%.6lf %.6lf\n",nAns,mAns);
}
}
}
double calculate1(int n)
{
double ans=0;
if(n == 1) ans = 1.0;
else ans=1.0/2.0;
return ans;
}
double calculate2(int m)
{
double ans=0;
ans=(double)(1+m)/2/m;
return ans;
} | [
"1462928058@qq.com"
] | 1462928058@qq.com |
11473bdeb4be52359799066dc2bfba6c54b171e2 | 6ea50d800eaf5690de87eea3f99839f07c662c8b | /ver.0.14.0/ChestScreen.h | e58072107dcb2e9b276edc45046e7c41fbdede9c | [] | no_license | Toku555/MCPE-Headers | 73eefeab8754a9ce9db2545fb0ea437328cade9e | b0806aebd8c3f4638a1972199623d1bf686e6497 | refs/heads/master | 2021-01-15T20:53:23.115576 | 2016-09-01T15:38:27 | 2016-09-01T15:38:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | h | #pragma once
class ChestScreen{
public:
void _buttonClicked(Button &);
void _controllerDirectionChanged(int,StickDirection);
void _controllerDirectionHeld(int,StickDirection);
void _drawSlotItemAt(Tessellator &,ItemInstance const*,int,int,bool);
void _entityCheck(void);
void _getChestEntity(void);
void _getContainer(void);
void _getInventory(void);
void _handleAddItem(FillingContainer *,FillingContainer *,int);
void _handleBulkItemMovementRequest(Touch::InventoryPane &);
void _handleRenderPane(Touch::InventoryPane &,Tessellator &,int,int,float);
void _init(void);
void _setupPane(void);
void _updateSelectedIndexes(StickDirection);
void addItem(Touch::InventoryPane &,int);
void containerChanged(int);
void getItems(Touch::InventoryPane const&);
void handleBackEvent(bool);
void handleButtonPress(short);
void handleButtonRelease(short);
void handleScrollWheel(float);
void init(void);
void isAllowed(int);
void onInternetUpdate(void);
void render(int,int,float);
void renderGameBehind(void);
void setupPositions(void);
void tick(void);
void ~ChestScreen();
void ~ChestScreen();
};
| [
"sinigami3427@gmail.com"
] | sinigami3427@gmail.com |
a86fb49db5ea4e893d2c88cb9af041ab78f86102 | 73c71311c08cb8d58b75dcd06c7a31f8b097b956 | /ewk/unittest/utc_blink_ewk_view_web_application_icon_urls_get_func.cpp | 615359cb894c1a51e8a1d2abf3fc4f2116268c4d | [
"BSD-3-Clause"
] | permissive | crosswalk-project/chromium-efl | 47927f6e17c0553d3756d9b9ca5c3e783b3641b8 | 3c1af10d16e2df57e8584378b79f0ff3335eb99d | refs/heads/efl/crosswalk-10/39.0.2171.19 | 2023-03-23T12:34:43.754226 | 2014-12-15T23:47:39 | 2014-12-15T23:47:39 | 27,436,290 | 9 | 14 | null | 2015-01-21T08:10:49 | 2014-12-02T14:33:10 | C++ | UTF-8 | C++ | false | false | 2,809 | cpp | // Copyright 2014 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "utc_blink_ewk_base.h"
#include <map>
class utc_blink_ewk_view_web_application_icon_urls_get : public utc_blink_ewk_base
{
protected:
void LoadFinished(Evas_Object *)
{
EventLoopStop(Success);
}
static void webAppUrlsGetCallback(Eina_List *urls, utc_blink_ewk_view_web_application_icon_urls_get *owner)
{
ASSERT_TRUE(NULL != owner);
utc_message("[webAppUrlsGetCallback] :: ");
ASSERT_EQ(owner->expectedUrls.size(), eina_list_count(urls));
Eina_List *l = 0;
void *d = 0;
EINA_LIST_FOREACH(urls, l, d) {
const char* size = ewk_web_application_icon_data_size_get(static_cast<Ewk_Web_App_Icon_Data *>(d));
ASSERT_TRUE(NULL != size);
const char* url = ewk_web_application_icon_data_url_get(static_cast<Ewk_Web_App_Icon_Data *>(d));
ASSERT_TRUE(NULL != url);
utc_message("[URLS]: %s ; %s", size, url);
ASSERT_STREQ(owner->GetResourceUrl(owner->expectedUrls[size].c_str()).c_str(), url);
}
owner->EventLoopStop(Success);
}
protected:
std::map<std::string, std::string> expectedUrls;
static const char * const webAppUrlsPage;
static const char * const noUrlsPage;
};
const char * const utc_blink_ewk_view_web_application_icon_urls_get::webAppUrlsPage = "ewk_view_web_application/web_app_urls_get.html";
const char * const utc_blink_ewk_view_web_application_icon_urls_get::noUrlsPage = "<html><body></body></html>";
TEST_F(utc_blink_ewk_view_web_application_icon_urls_get, WEB_APP_URLS_PAGE)
{
ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), GetResourceUrl(webAppUrlsPage).c_str()));
ASSERT_EQ(Success, EventLoopStart());
expectedUrls["64x64"] = "ewk_view_web_application/tizen-icon1.png";
expectedUrls["128x128"] = "ewk_view_web_application/tizen-icon2.png";
expectedUrls["144x144"] = "ewk_view_web_application/tizen-icon3.png";
ASSERT_EQ(EINA_TRUE, ewk_view_web_application_icon_urls_get(GetEwkWebView(),
(void(*)(Eina_List*,void*))webAppUrlsGetCallback,
this));
ASSERT_EQ(Success, EventLoopStart());
}
TEST_F(utc_blink_ewk_view_web_application_icon_urls_get, NO_URLS_PAGE)
{
ASSERT_EQ(EINA_TRUE, ewk_view_html_string_load(GetEwkWebView(), noUrlsPage, 0, 0));
ASSERT_EQ(Success, EventLoopStart());
ASSERT_EQ(EINA_TRUE, ewk_view_web_application_icon_urls_get(GetEwkWebView(),
(void(*)(Eina_List*,void*))webAppUrlsGetCallback,
this));
ASSERT_EQ(Success, EventLoopStart());
}
| [
"a1.gomes@samsung.com"
] | a1.gomes@samsung.com |
017a66f4d9898012e3124efef99454570e89cd31 | 463a2089420c04245a715d171ad490e2e6abaedd | /leetcode/e-m-h/easy/easy167.cpp | fd2545cd782f4e419566fb6ec64373e6e4c8d55f | [] | no_license | faa678/coding | 9c86ec2936b17d426fe2d03708116042950f46ef | 0b43fbb6397b6e8ac335d2f7e20d7fdda247fc34 | refs/heads/master | 2022-01-30T14:09:34.213640 | 2022-01-03T13:17:08 | 2022-01-03T13:17:08 | 220,933,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | /*
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
*/
#include<iostream>
#include<vector>
using namespace std;
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> empty;
int len = numbers.size();
if(len < 2)return empty;
vector<int> result;
int i = 0, j = len - 1;
while(i < j){
if(numbers[i] + numbers[j] == target){
result.emplace_back(i);
result.push_back(j);
return result;
}
else if(numbers[i] + numbers[j] < target) i++;
else j--;
}
return empty;
}
//result.emplace_back()更加高效 | [
"2532506036@qq.com"
] | 2532506036@qq.com |
e7b7499a41722c463f91fa6bdcc8b5aedc013221 | c683a0aa9853c826197eac66d42e1a1f1901afec | /Engine/Engine/Core/Bitmap.cpp | 91a686d2b741adc90b7585c4a81688d5bb4ace2d | [] | no_license | poonasp257/Ping-pong | 1cb17f403bd3742422691fe0ffca916fafa5fee8 | 54ce8cc053b1aac414a4127867bbc866065d283a | refs/heads/master | 2020-09-01T16:33:46.093080 | 2019-11-11T03:47:16 | 2019-11-11T03:47:16 | 219,004,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,982 | cpp | #include "stdafx.h"
Bitmap::Bitmap() : vertexBuffer(nullptr), indexBuffer(nullptr),
texture(std::make_shared<Texture>()){
}
Bitmap::~Bitmap() {
texture.reset();
if (indexBuffer) {
indexBuffer->Release();
indexBuffer = nullptr;
}
if (vertexBuffer) {
vertexBuffer->Release();
vertexBuffer = nullptr;
}
}
bool Bitmap::initialize(ID3D11Device* device, int screenWidth, int screenHeight, const WCHAR* textureFilename, int
bitmapWidth, int bitmapHeight) {
bool result;
this->screenWidth = screenWidth;
this->screenHeight = screenHeight;
this->bitmapWidth = bitmapWidth;
this->bitmapHeight = bitmapHeight;
previousPosX = -1;
previousPosY = -1;
result = initializeBuffers(device);
if (!result) return false;
result = loadTexture(device, textureFilename);
if (!result) return false;
return true;
}
bool Bitmap::render(ID3D11DeviceContext* deviceContext, int positionX, int positionY) {
bool result = updateBuffers(deviceContext, positionX, positionY);
if (!result) return false;
renderBuffers(deviceContext);
return true;
}
int Bitmap::getIndexCount() const {
return indexCount;
}
ID3D11ShaderResourceView* Bitmap::getTexture() {
return texture->getTexture();
}
bool Bitmap::initializeBuffers(ID3D11Device* device) {
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
vertexCount = 6;
indexCount = vertexCount;
vertices = new VertexType[vertexCount];
if (!vertices) return false;
indices = new unsigned long[indexCount];
if (!indices) return false;
memset(vertices, 0, (sizeof(VertexType) * vertexCount));
for (int i = 0; i < indexCount; i++) {
indices[i] = i;
}
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);
if (FAILED(result)) return false;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);
if (FAILED(result)) return false;
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
bool Bitmap::updateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY) {
float left, right, top, bottom;
VertexType* vertices;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* verticesPtr;
HRESULT result;
if ((positionX == previousPosX)
&& (positionY == previousPosY)) return true;
previousPosX = positionX;
previousPosY = positionY;
left = (float)((screenWidth / 2) * -1) + (float)positionX;
right = left + (float)bitmapWidth;
top = (float)(screenHeight / 2) - (float)positionY;
bottom = top - (float)bitmapHeight;
vertices = new VertexType[vertexCount];
if (!vertices) return false;
vertices[0].position = D3DXVECTOR3(left, top, 0.0f);
vertices[0].texture = D3DXVECTOR2(0.0f, 0.0f);
vertices[1].position = D3DXVECTOR3(right, bottom, 0.0f);
vertices[1].texture = D3DXVECTOR2(1.0f, 1.0f);
vertices[2].position = D3DXVECTOR3(left, bottom, 0.0f);
vertices[2].texture = D3DXVECTOR2(0.0f, 1.0f);
vertices[3].position = D3DXVECTOR3(left, top, 0.0f);
vertices[3].texture = D3DXVECTOR2(0.0f, 0.0f);
vertices[4].position = D3DXVECTOR3(right, top, 0.0f);
vertices[4].texture = D3DXVECTOR2(1.0f, 0.0f);
vertices[5].position = D3DXVECTOR3(right, bottom, 0.0f);
vertices[5].texture = D3DXVECTOR2(1.0f, 1.0f);
result = deviceContext->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result)) return false;
verticesPtr = (VertexType*)mappedResource.pData;
memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * vertexCount));
deviceContext->Unmap(vertexBuffer, 0);
delete[] vertices;
vertices = 0;
return true;
}
void Bitmap::renderBuffers(ID3D11DeviceContext* deviceContext) {
unsigned int stride;
unsigned int offset;
stride = sizeof(VertexType);
offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
deviceContext->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
bool Bitmap::loadTexture(ID3D11Device* device, const WCHAR* filename) {
bool result = texture->initialize(device, filename);
if (!result) return false;
return true;
} | [
"poonasp257@gmail.com"
] | poonasp257@gmail.com |
9ba8ba81069de290222c8b734e4d7c602a3c1431 | 5e34b73f3b5b57aa9fab98591adc451ea04d5ff2 | /groups/bsl/bslstl/bslstl_multimap.h | 285456eb033d30a172ee35ddf0ea7ecd63770b86 | [
"MIT"
] | permissive | yangg86/bsl | ff0f3e505f5daea975fc93092c54ab9a7e68db37 | ae1c8ab60f8daff69718bda575d044ebdeae484b | refs/heads/master | 2021-01-20T22:55:42.547882 | 2012-11-13T21:03:57 | 2012-11-13T21:03:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 85,716 | h | // bslstl_multimap.h -*-C++-*-
#ifndef INCLUDED_BSLSTL_MULTIMAP
#define INCLUDED_BSLSTL_MULTIMAP
#ifndef INCLUDED_BSLS_IDENT
#include <bsls_ident.h>
#endif
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide an STL-compliant multimap class.
//
//@CLASSES:
// bsl::multimap STL-compatible multimap template
//
//@SEE_ALSO: bslstl_map, bslstl_multiset
//
//@DESCRIPTION: This component defines a single class template 'multimap',
// implementing the standard container holding an ordered sequence of key-value
// pairs (possibly having duplicate keys), and presenting a mapping from the
// keys (of a template parameter type, 'KEY') to their associated values (of
// another template parameter type, 'VALUE').
//
// An instantiation of 'multimap' is an allocator-aware, value-semantic type
// whose salient attributes are its size (number of key-value pairs) and the
// ordered sequence of key-value pairs the multimap contains. If 'multimap' is
// instantiated with either a key type or mapped-value type that is not itself
// value-semantic, then it will not retain all of its value-semantic qualities.
// In particular, if a either the key or value type cannot be tested for
// equality, then a 'multimap' containing that type cannot be tested for
// equality. It is even possible to instantiate 'multimap' with a key or
// mapped-value type that does not have a copy-constructor, in which case the
// 'multimap' will not be copyable.
//
// A 'multimap' meets the requirements of an associative container with
// bidirectional iterators in the C++11 standard [23.2.4]. The 'multimap'
// implemented here adheres to the C++11 standard, except that it does not have
// interfaces that take rvalue references, 'initializer_lists', 'emplace', or
// operations taking a variadic number of template parameters. Note that
// excluded C++11 features are those that require (or are greatly simplified
// by) C++11 compiler support.
//
///Requirements on 'KEY' and 'VALUE'
///---------------------------------
// A 'multimap' is a fully "Value-Semantic Type" (see {'bsldoc_glossary'}) only
// if the supplied 'KEY' and 'VALUE' template parameters are themselves fully
// value-semantic. It is possible to instantiate a 'multimap' with 'KEY' and
// 'VALUE' parameter arguments that do not provide a full set of value-semantic
// operations, but then some methods of the container may not be instantiable.
// The following terminology, adopted from the C++11 standard, is used in the
// function documentation of 'multimap' to describe a function's requirements
// for the 'KEY' and 'VALUE' template parameters. These terms are also defined
// in section [17.6.3.1] of the C++11 standard. Note that, in the context of a
// 'multimap' instantiation, the requirements apply specifically to the
// multimap's entry type, 'value_type', which is an alias for 'bsl::pair<KEY,
// VALUE>'.
//
//: "default-constructible": The type provides a default constructor.
//:
//: "copy-constructible": The type provides a copy constructor.
//:
//: "equality-comparable": The type provides an equality-comparison operator
//: that defines an equivalence relationship and is both reflexive and
//: transitive.
//:
//: "less-than-comparable": The type provides a less-than operator, which
//: defines a strict weak ordering relation on values of the type.
//
///Memory Allocation
///-----------------
// The type supplied as a multimap's 'ALLOCATOR' template parameter determines
// how that multimap will allocate memory. The 'multimap' template supports
// allocators meeting the requirements of the C++11 standard [17.6.3.5], in
// addition it supports scoped-allocators derived from the 'bslma::Allocator'
// memory allocation protocol. Clients intending to use 'bslma' style
// allocators should use the template's default 'ALLOCATOR' type: The default
// type for the 'ALLOCATOR' template parameter, 'bsl::allocator', provides a
// C++11 standard-compatible adapter for a 'bslma::Allocator' object.
//
///'bslma'-Style Allocators
/// - - - - - - - - - - - -
// If the (template parameter) type 'ALLOCATOR' of an 'multimap' instantiation'
// is 'bsl::allocator', then objects of that multimap type will conform to the
// standard behavior of a 'bslma'-allocator-enabled type. Such a multimap
// accepts an optional 'bslma::Allocator' argument at construction. If the
// address of a 'bslma::Allocator' object is explicitly supplied at
// construction, it will be used to supply memory for the 'multimap' throughout
// its lifetime; otherwise, the multimap will use the default allocator
// installed at the time of the multimap's construction (see 'bslma_default').
// In addition to directly allocating memory from the indicated
// 'bslma::Allocator', a multimap supplies that allocator's address to the
// constructors of contained objects of the (template parameter) types 'KEY'
// and 'VALUE', if respectively, the types define the
// 'bslma::UsesBslmaAllocator' trait.
//
///Operations
///----------
// This section describes the run-time complexity of operations on instances
// of 'multimap':
//..
// Legend
// ------
// 'K' - (template parameter) type 'KEY' of the 'multimap'
// 'V' - (template parameter) type 'VALUE' of the 'multimap'
// 'a', 'b' - two distinct objects of type 'multimap<K, V>'
// 'n', 'm' - number of elements in 'a' and 'b' respectively
// 'value_type' - 'multimap<K, V>::value_type'
// 'c' - comparator providing an ordering for objects of type 'K'
// 'al - an STL-style memory allocator
// 'i1', 'i2' - two iterators defining a sequence of 'value_type' objects
// 'k' - an object of type 'K'
// 'v' - an object of type 'V'
// 'p1', 'p2' - two iterators belonging to 'a'
// distance(i1,i2) - the number of elements in the range [i1, i2)
//
// +----------------------------------------------------+--------------------+
// | Operation | Complexity |
// +====================================================+====================+
// | multimap<K, V> a; (default construction) | O[1] |
// | multimap<K, V> a(al); | |
// | multimap<K, V> a(c, al); | |
// +----------------------------------------------------+--------------------+
// | multimap<K, V> a(b); (copy construction) | O[n] |
// | multimap<K, V> a(b, al); | |
// +----------------------------------------------------+--------------------+
// | multimap<K, V> a(i1, i2); | O[N] if [i1, i2) |
// | multimap<K, V> a(i1, i2, al); | is sorted with |
// | multimap<K, V> a(i1, i2, c, al); | 'a.value_comp()', |
// | | O[N * log(N)] |
// | | otherwise, where N |
// | | is distance(i1,i2) |
// +----------------------------------------------------+--------------------+
// | a.~multimap<K, V>(); (destruction) | O[n] |
// +----------------------------------------------------+--------------------+
// | a = b; (assignment) | O[n] |
// +----------------------------------------------------+--------------------+
// | a.begin(), a.end(), a.cbegin(), a.cend(), | O[1] |
// | a.rbegin(), a.rend(), a.crbegin(), a.crend() | |
// +----------------------------------------------------+--------------------+
// | a == b, a != b | O[n] |
// +----------------------------------------------------+--------------------+
// | a < b, a <= b, a > b, a >= b | O[n] |
// +----------------------------------------------------+--------------------+
// | a.swap(b), swap(a,b) | O[1] if 'a' and |
// | | 'b' use the same |
// | | allocator, |
// | | O[n + m] otherwise |
// +----------------------------------------------------+--------------------+
// | a.size() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.max_size() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.empty() | O[1] |
// +----------------------------------------------------+--------------------+
// | get_allocator() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.insert(value_type(k, v)) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.insert(p1, value_type(k, v)) | amortized constant |
// | | if the value is |
// | | inserted right |
// | | before p1, |
// | | O[log(n)] |
// | | otherwise |
// +----------------------------------------------------+--------------------+
// | a.insert(i1, i2) | O[log(N) * |
// | | distance(i1,i2)] |
// | | |
// | | where N is |
// | | n + distance(i1,i2)|
// +----------------------------------------------------+--------------------+
// | a.erase(p1) | amortized constant |
// +----------------------------------------------------+--------------------+
// | a.erase(k) | O[log(n) + |
// | | a.count(k)] |
// +----------------------------------------------------+--------------------+
// | a.erase(p1, p2) | O[log(n) + |
// | | distance(p1, p2)] |
// +----------------------------------------------------+--------------------+
// | a.erase(p1, p2) | O[log(n) + |
// | | distance(p1, p2)] |
// +----------------------------------------------------+--------------------+
// | a.clear() | O[n] |
// +----------------------------------------------------+--------------------+
// | a.key_comp() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.value_comp() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.find(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.count(k) | O[log(n) + |
// | | a.count(k)] |
// +----------------------------------------------------+--------------------+
// | a.lower_bound(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.upper_bound(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.equal_range(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
//..
//
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 1: Creating a Phone Book
/// - - - - - - - - - - - - - - - -
// In this example, we will define a class 'PhoneBook', that provides a mapping
// of names to phone numbers. The 'PhoneBook' class will be implemented using
// a 'bsl::multimap', and will supply manipulators, allowing a client to add or
// remove entries from the phone book, as well as accessors, allowing clients
// to efficiently lookup entries by name, and to iterate over the entries in
// the phone book in sorted order.
//
// Note that this example uses a type 'string' that is based on the standard
// type 'string' (see 'bslstl_string'). For the sake of brevity, the
// implementation of 'string' is not explored here.
//
// First, we define an alias for a pair of 'string' objects that we will use to
// represent names in the phone book:
//..
// typedef bsl::pair<string, string> FirstAndLastName;
// // This 'typedef' provides an alias for a pair of 'string' objects,
// // whose 'first' and 'second' elements refer to the first and last
// // names of a person, respectively.
//..
// Then, we define a comparison functor for 'FirstAndLastName' objects (note
// that this comparator is required because we intend for the last name to
// take precedence over the first name in the ordering of entries maintained
// by the phone book, which differs from the behavior supplied by 'operator<'
// for 'pair'):
//..
// struct FirstAndLastNameLess {
// // This 'struct' defines an ordering on 'FirstAndLastName' values,
// // allowing them to be included in sorted containers such as
// // 'bsl::multimap'. Note that last name (the 'second' member of a
// // 'FirstAndLastName' value) takes precedence over first name in the
// // ordering defined by this functor.
//
// bool operator()(const FirstAndLastName& lhs,
// const FirstAndLastName& rhs) const
// // Return 'true' if the value of the specified 'lhs' is less than
// // (ordered before) the value of the specified 'rhs', and 'false'
// // otherwise. The 'lhs' value is considered less than the 'rhs'
// // value if the second value in the 'lhs' pair (the last name) is
// // less than the second value in the 'rhs' pair or, if the second
// // values are equal, if the first value in the 'lhs' pair (the
// // first name) is less than the first value in the 'rhs' pair.
// {
// int cmp = std::strcmp(lhs.second.c_str(), rhs.second.c_str());
// if (0 == cmp) {
// cmp = std::strcmp(lhs.first.c_str(), rhs.first.c_str());
// }
// return cmp < 0;
// }
// };
//..
// Next, we define the public interface for 'PhoneBook':
//..
// class PhoneBook {
// // This class provides a mapping of a person's name to their phone
// // number. Names within a 'Phonebook' are represented using a using
// // 'FirstAndLastName' object, and phone numbers are represented using a
// // 'bsls::Types::Uint64' value.
//
//..
// Here, we create a type alias, 'NameToNumberMap', for a 'bsl::multimap' that
// will serve as the data member for a 'PhoneBook'. A 'NameToNumberMap' has
// keys of type 'FirstAndLastName', mapped-values of type
// 'bsls::Types::Uint64', and a comparator of type 'FirstAndLastNameLess'. We
// use the default 'ALLOCATOR' template parameter as we intend to use
// 'PhoneBook' with 'bslma' style allocators:
//..
// // PRIVATE TYPES
// typedef bsl::multimap<FirstAndLastName,
// bsls::Types::Uint64,
// FirstAndLastNameLess> NameToNumberMap;
// // This 'typedef' is an alias for a mapping between names and phone
// // numbers.
//
// // DATA
// NameToNumberMap d_nameToNumber; // mapping of names to phone numbers
//
// // FRIENDS
// friend bool operator==(const PhoneBook& lhs, const PhoneBook& rhs);
//
// public:
// // PUBLIC TYPES
// typedef bsls::Types::Uint64 PhoneNumber;
// // This 'typedef' provides an alias for the type of an unsigned
// // integers used to represent phone-numbers in a 'PhoneBook'.
//
// typedef NameToNumberMap::const_iterator ConstIterator;
// // This 'typedef' provides an alias for the type of an iterator
// // providing non-modifiable access to the entries in a 'PhoneBook'.
//
// // CREATORS
// PhoneBook(bslma::Allocator *basicAllocator = 0);
// // Create an empty 'PhoneBook' object. Optionally specify a
// // 'basicAllocator' used to supply memory. If 'basicAllocator' is
// // 0, the currently installed default allocator is used.
//
// PhoneBook(const PhoneBook& original,
// bslma::Allocator *basicAllocator = 0);
// // Create a 'PhoneBook' object having the same value as the
// // specified 'original' object. Optionally specify a
// // 'basicAllocator' used to supply memory. If 'basicAllocator' is
// // 0, the currently installed default allocator is used.
//
// //! ~PhoneBook() = default;
// // Destroy this object.
//
// // MANIPULATORS
// PhoneBook& operator=(const PhoneBook& rhs);
// // Assign to this object the value of the specified 'rhs' object,
// // and return a reference providing modifiable access to this
// // object.
//
// void addEntry(const FirstAndLastName& name, PhoneNumber number);
// // Add an entry to this phone book having the specified 'name' and
// // 'number'. The behavior is undefined unless 'name.first' and
// // 'name.end' are non-empty strings.
//
// int removeEntry(const FirstAndLastName& name, PhoneNumber number);
// // Remove the entries from this phone book having the specified
// // 'name' and 'number', if they exists, and return the number of
// // removed entries; otherwise, return 0 with no other effects.
//
// // ACCESSORS
// bsl::pair<ConstIterator, ConstIterator> lookupByName(
// const FirstAndLastName& name) const;
// // Return a pair of iterators to the ordered sequence of entries
// // held in this phone book having the specified 'name', where the
// // first iterator is position at the start of the sequence, and the
// // second is positioned one past the last entry in the sequence.
// // If 'name' does not exist in this phone book, then the two
// // returned iterators will have the same value.
//
// ConstIterator begin() const;
// // Return an iterator providing non-modifiable access to the first
// // entry in the ordered sequence of entries held in this phone
// // book, or the past-the-end iterator if this phone book is empty.
//
// ConstIterator end() const;
// // Return an iterator providing non-modifiable access to the
// // past-the-end entry in the ordered sequence of entries maintained
// // by this phone book.
//
// int numEntries() const;
// // Return the number of entries contained in this phone book.
// };
//..
// Then, we declare the free operators for 'PhoneBook':
//..
// inline
// bool operator==(const PhoneBook& lhs, const PhoneBook& rhs);
// // Return 'true' if the specified 'lhs' and 'rhs' objects have the same
// // value, and 'false' otherwise. Two 'PhoneBook' objects have the
// // same value if they have the same number of entries, and each
// // corresponding entry, in their respective ordered sequence of
// // entries, is the same.
//
// inline
// bool operator!=(const PhoneBook& lhs, const PhoneBook& rhs);
// // Return 'true' if the specified 'lhs' and 'rhs' objects do not have
// // the same value, and 'false' otherwise. Two 'PhoneBook' objects do
// // not have the same value if they either differ in their number of
// // contained entries, or if any of the corresponding entries, in their
// // respective ordered sequences of entries, is not the same.
//..
// Now, we define the implementations methods of the 'PhoneBook' class:
//..
// // CREATORS
// inline
// PhoneBook::PhoneBook(bslma::Allocator *basicAllocator)
// : d_nameToNumber(FirstAndLastNameLess(), basicAllocator)
// {
// }
//..
// Notice that, on construction, we pass the contained 'bsl::multimap'
// ('d_nameToNumber'), a default constructed 'FirstAndLastNameLess' object that
// it will use to perform comparisons, and the allocator supplied to
// 'PhoneBook' at construction'.
//..
// inline
// PhoneBook::PhoneBook(const PhoneBook& original,
// bslma::Allocator *basicAllocator)
// : d_nameToNumber(original.d_nameToNumber, basicAllocator)
// {
// }
//
// // MANIPULATORS
// inline
// PhoneBook& PhoneBook::operator=(const PhoneBook& rhs)
// {
// d_nameToNumber = rhs.d_nameToNumber;
// return *this;
// }
//
// inline
// void PhoneBook::addEntry(const FirstAndLastName& name, PhoneNumber number)
// {
// BSLS_ASSERT(!name.first.empty());
// BSLS_ASSERT(!name.second.empty());
//
// d_nameToNumber.insert(NameToNumberMap::value_type(name, number));
// }
//
// inline
// int PhoneBook::removeEntry(const FirstAndLastName& name,
// PhoneNumber number)
// {
//
// bsl::pair<NameToNumberMap::iterator, NameToNumberMap::iterator> range =
// d_nameToNumber.equal_range(name);
//
// NameToNumberMap::iterator itr = range.first;
// int numRemovedEntries = 0;
//
// while (itr != range.second) {
// if (itr->second == number) {
// itr = d_nameToNumber.erase(itr);
// ++numRemovedEntries;
// }
// else {
// ++itr;
// }
// }
//
// return numRemovedEntries;
// }
//
// // ACCESSORS
// inline
// bsl::pair<PhoneBook::ConstIterator, PhoneBook::ConstIterator>
// PhoneBook::lookupByName(const FirstAndLastName& name) const
// {
// return d_nameToNumber.equal_range(name);
// }
//
// inline
// PhoneBook::ConstIterator PhoneBook::begin() const
// {
// return d_nameToNumber.begin();
// }
//
// inline
// PhoneBook::ConstIterator PhoneBook::end() const
// {
// return d_nameToNumber.end();
// }
//
// inline
// int PhoneBook::numEntries() const
// {
// return d_nameToNumber.size();
// }
//..
// Finally, we implement the free operators for 'PhoneBook':
//..
// inline
// bool operator==(const PhoneBook& lhs, const PhoneBook& rhs)
// {
// return lhs.d_nameToNumber == rhs.d_nameToNumber;
// }
//
// inline
// bool operator!=(const PhoneBook& lhs, const PhoneBook& rhs)
// {
// return !(lhs == rhs);
// }
//..
#if defined(BSL_OVERRIDES_STD) && !defined(BSL_STDHDRS_PROLOGUE_IN_EFFECT)
#error "include <bsl_map.h> instead of <bslstl_multimap.h> in \
BSL_OVERRIDES_STD mode"
#endif
#ifndef INCLUDED_BSLSCM_VERSION
#include <bslscm_version.h>
#endif
#ifndef INCLUDED_BSLSTL_ALLOCATOR
#include <bslstl_allocator.h>
#endif
#ifndef INCLUDED_BSLSTL_PAIR
#include <bslstl_pair.h>
#endif
#ifndef INCLUDED_BSLSTL_MAPCOMPARATOR
#include <bslstl_mapcomparator.h>
#endif
#ifndef INCLUDED_BSLSTL_STDEXCEPTUTIL
#include <bslstl_stdexceptutil.h>
#endif
#ifndef INCLUDED_BSLSTL_TREEITERATOR
#include <bslstl_treeiterator.h>
#endif
#ifndef INCLUDED_BSLSTL_TREENODE
#include <bslstl_treenode.h>
#endif
#ifndef INCLUDED_BSLSTL_TREENODEPOOL
#include <bslstl_treenodepool.h>
#endif
#ifndef INCLUDED_BSLALG_SWAPUTIL
#include <bslalg_swaputil.h>
#endif
#ifndef INCLUDED_BSLALG_RANGECOMPARE
#include <bslalg_rangecompare.h>
#endif
#ifndef INCLUDED_BSLALG_RBTREEANCHOR
#include <bslalg_rbtreeanchor.h>
#endif
#ifndef INCLUDED_BSLALG_RBTREENODE
#include <bslalg_rbtreenode.h>
#endif
#ifndef INCLUDED_BSLALG_RBTREEUTIL
#include <bslalg_rbtreeutil.h>
#endif
#ifndef INCLUDED_BSLALG_TYPETRAITHASSTLITERATORS
#include <bslalg_typetraithasstliterators.h>
#endif
#ifndef INCLUDED_FUNCTIONAL
#include <functional>
#define INCLUDED_FUNCTIONAL
#endif
namespace bsl {
// ==============
// class multimap
// ==============
template <class KEY,
class VALUE,
class COMPARATOR = std::less<KEY>,
class ALLOCATOR = bsl::allocator<bsl::pair<const KEY, VALUE> > >
class multimap {
// This class template implements a value-semantic container type holding
// an ordered sequence of key-value pairs having possibly duplicate keys
// that provide a mapping from keys (of the template parameter type, 'KEY')
// to their associated values (of another template parameter type,
// 'VALUE').
//
// This class:
//: o supports a complete set of *value-semantic* operations
//: o except for 'bdex' serialization
//: o is *exception-neutral* (agnostic except for the 'at' method)
//: o is *alias-safe*
//: o is 'const' *thread-safe*
// For terminology see {'bsldoc_glossary'}.
// PRIVATE TYPES
typedef bsl::pair<const KEY, VALUE> ValueType;
// This typedef is an alias for the type of key-value pair objects
// maintained by this multimap.
typedef BloombergLP::bslstl::MapComparator<KEY, VALUE, COMPARATOR>
Comparator;
// This typedef is an alias for the comparator used internally by this
// multimap.
typedef BloombergLP::bslstl::TreeNode<ValueType> Node;
// This typedef is an alias for the type of nodes held by the tree (of
// nodes) used to implement this multimap.
typedef BloombergLP::bslstl::TreeNodePool<ValueType, ALLOCATOR>
NodeFactory;
// This typedef is an alias for the factory type used to create and
// destroy 'Node' objects.
typedef typename bsl::allocator_traits<ALLOCATOR> AllocatorTraits;
// This typedef is an alias for the allocator traits type associated
// with this container.
struct DataWrapper : public Comparator {
// This struct is wrapper around the comparator and allocator data
// members. It takes advantage of the empty-base optimization (EBO) so
// that if the allocator is stateless, it takes up no space.
//
// TBD: This struct should eventually be replaced by the use of a
// general EBO-enabled component that provides a 'pair'-like
// interface or a 'tuple'.
NodeFactory d_pool; // pool of 'Node' objects
explicit DataWrapper(const COMPARATOR& comparator,
const ALLOCATOR& allocator);
// Create a 'DataWrapper' object with the specified 'comparator'
// and 'allocator'.
};
// DATA
DataWrapper d_compAndAlloc;
// comparator and pool of 'Node'
// objects
BloombergLP::bslalg::RbTreeAnchor d_tree; // balanced tree of 'Node'
// objects
private:
// PRIVATE MANIPULATORS
NodeFactory& nodeFactory();
// Return a reference providing modifiable access to the
// node-allocator for this tree.
Comparator& comparator();
// Return a reference providing modifiable access to the
// comparator for this tree.
void quickSwap(multimap& other);
// Efficiently exchange the value and comparator of this object with
// the value of the specified 'other' object. This method provides
// the no-throw exception-safety guarantee. The behavior is undefined
// unless this object was created with the same allocator as 'other'.
// PRIVATE ACCESSORS
const NodeFactory& nodeFactory() const;
// Return a reference providing non-modifiable access to the
// node-allocator for this tree.
const Comparator& comparator() const;
// Return a reference providing non-modifiable access to the
// comparator for this tree.
public:
// PUBLIC TYPES
typedef KEY key_type;
typedef VALUE mapped_type;
typedef bsl::pair<const KEY, VALUE> value_type;
typedef COMPARATOR key_compare;
typedef ALLOCATOR allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename AllocatorTraits::size_type size_type;
typedef typename AllocatorTraits::difference_type difference_type;
typedef typename AllocatorTraits::pointer pointer;
typedef typename AllocatorTraits::const_pointer const_pointer;
typedef BloombergLP::bslstl::TreeIterator<value_type,
Node,
difference_type> iterator;
typedef BloombergLP::bslstl::TreeIterator<const value_type,
Node,
difference_type> const_iterator;
typedef bsl::reverse_iterator<iterator> reverse_iterator;
typedef bsl::reverse_iterator<const_iterator> const_reverse_iterator;
class value_compare {
// This nested class defines a mechanism for comparing two objects of
// the (template parameter) type 'COMPARATOR'. Note that this class
// exactly matches its definition in the C++11 standard [23.4.5.1];
// otherwise we would have implemented it as a separate component-local
// class.
// FRIENDS
friend class multimap;
protected:
COMPARATOR comp; // we would not have elected to make this data
// member protected ourselves
value_compare(COMPARATOR c) : comp(c) {}
// Create a 'value_compare' object that will delegate to the
// specified 'comparator' for comparisons.
public:
typedef bool result_type;
// This 'typedef' is an alias for the result type of a call to
// the overload of 'operator()' (the comparison function) provided
// by a 'multimap::value_compare' object.
typedef value_type first_argument_type;
// This 'typedef' is an alias for the type of the first parameter
// of the overload of 'operator()' (the comparison function)
// provided by a 'multimap::value_compare' object.
typedef value_type second_argument_type;
// This 'typedef' is an alias for the type of the second parameter
// of the overload of 'operator()' (the comparison function)
// provided by a 'multimap::value_compare' object.
bool operator()(const value_type& x, const value_type& y) const
// Return 'true' if the specified 'x' object is ordered before the
// specified 'y' object, as determined by the comparator supplied
// at construction.
{
return comp(x.first, y.first);
}
};
public:
// CREATORS
explicit multimap(const COMPARATOR& comparator = COMPARATOR(),
const ALLOCATOR& allocator = ALLOCATOR())
// Construct an empty multimap. Optionally specify a 'comparator' used
// to order key-value pairs contained in this object. If 'comparator'
// is not supplied, a default-constructed object of the (template
// parameter) type 'COMPARATOR' is used. Optionally specify an
// 'allocator' used to supply memory. If 'allocator' is not supplied,
// a default-constructed object of the (template parameter) type
// ALLOCATOR' is used. If the 'ALLOCATOR' argument is of type
// 'bsl::allocator' (the default), then 'allocator', if supplied,
// shall be convertible to 'bslma::Allocator *'. If the 'ALLOCATOR'
// argument is of type 'bsl::allocator' and 'allocator' is not
// supplied, the currently installed default allocator will be used to
// supply memory.
: d_compAndAlloc(comparator, allocator)
, d_tree()
{
// The implementation is placed here in the class definition to
// workaround an AIX compiler bug, where the constructor can fail to
// compile because it is unable to find the definition of the default
// argument. This occurs when a templatized class wraps around the
// container and the comparator is defined after the new class.
}
explicit multimap(const ALLOCATOR& allocator);
// Construct an empty multimap that will use the specified 'allocator'
// to supply memory. Use a default-constructed object of the (template
// parameter) type 'COMPARATOR' to order the key-value pairs contained
// in this multimap. If the template parameter 'ALLOCATOR' argument is
// of type 'bsl::allocator' (the default) then 'allocator' shall be
// convertible to 'bslma::Allocator *'.
multimap(const multimap& original);
// Construct a multimap having the same value as the specified
// 'original'. Use a copy of 'original.key_comp()' to order the
// key-value pairs contained in this multimap. Use the allocator
// returned by 'bsl::allocator_traits<ALLOCATOR>::
// select_on_container_copy_construction(original.allocator())' to
// allocate memory. If the (template parameter) type 'ALLOCATOR' is
// of type 'bsl::allocator' (the default), the currently installed
// default allocator will be used to supply memory. This method
// requires that the (template parameter) types 'KEY' and 'VALUE'
// both be "copy-constructible" (see {Requirements on 'KEY' and
// 'VALUE'}).
multimap(const multimap& original, const ALLOCATOR& allocator);
// Construct a multimap having the same value as that of the specified
// 'original' that will use the specified 'allocator' to supply memory.
// Use a copy of 'original.key_comp()' to order the key-value pairs
// contained in this multimap. If the template parameter 'ALLOCATOR'
// argument is of type 'bsl::allocator' (the default) then 'allocator'
// shall be convertible to 'bslma::Allocator *'. This method requires
// that the (template parameter) types 'KEY' and 'VALUE' both be
// "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
template <class INPUT_ITERATOR>
multimap(INPUT_ITERATOR first,
INPUT_ITERATOR last,
const COMPARATOR& comparator = COMPARATOR(),
const ALLOCATOR& allocator = ALLOCATOR());
// Construct a multimap, and insert each 'value_type' object in the
// sequence starting at the specified 'first' element, and ending
// immediately before the specified 'last' element, ignoring those
// pairs having a key that appears earlier in the sequence. Optionally
// specify a 'comparator' used to order key-value pairs contained in
// this object. If 'comparator' is not supplied, a default-constructed
// object of the (template parameter) type 'COMPARATOR' is used.
// Optionally specify a 'allocator' used to supply memory. If
// 'allocator' is not supplied, a default-constructed object of the
// (template parameter) type 'ALLOCATOR' is used. If the template
// parameter 'ALLOCATOR' argument is of type 'bsl::allocator' (the
// default) then 'allocator', if supplied, shall be convertible to
// 'bslma::Allocator *'. If the template parameter 'ALLOCATOR'
// argument is of type 'bsl::allocator' and 'allocator' is not
// supplied, the currently installed default allocator will be used to
// supply memory. If the sequence 'first' and 'last' is ordered
// according to the identified 'comparator' then this operation will
// have O[N] complexity, where N is the number of elements between
// 'first' and 'last', otherwise this operation will have O[N * log(N)]
// complexity. The (template parameter) type 'INPUT_ITERATOR' shall
// meet the requirements of an input iterator defined in the C++11
// standard [24.2.3] providing access to values of a type convertible
// to 'value_type'. The behavior is undefined unless 'first' and
// 'last' refer to a sequence of valid values where 'first' is at a
// position at or before 'last'. This method requires that the
// (template parameter) types 'KEY' and 'VALUE' both be
// "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
~multimap();
// Destroy this object;
// MANIPULATORS
multimap& operator=(const multimap& rhs);
// Assign to this object the value and comparator of the specified
// 'rhs' object, propagate to this object the allocator of 'rhs' if the
// 'ALLOCATOR' type has trait 'propagate_on_container_copy_assignment',
// and return a reference providing modifiable access to this object.
// This method requires that the (template parameter) types 'KEY' and
// 'VALUE' both be "copy-constructible" (see {Requirements on 'KEY' and
// 'VALUE'}).
iterator begin();
// Return an iterator providing modifiable access to the first
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or the 'end' iterator if this multimap
// is empty.
iterator end();
// Return an iterator providing modifiable access to the past-the-end
// element in the ordered sequence of 'value_type' objects maintained
// by this multimap.
reverse_iterator rbegin();
// Return a reverse iterator providing modifiable access to the last
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or 'rend' if this multimap is empty.
reverse_iterator rend();
// Return a reverse iterator providing modifiable access to the
// prior-to-the-beginning element in the ordered sequence of
// 'value_type' objects maintained by this multimap.
iterator insert(const value_type& value);
// Insert the specified 'value' into this multimap. If a range
// containing elements equivalent to 'value' already exist, insert
// 'value' at the end of that range. Return an iterator referring to
// the newly inserted 'value_type' object. This method requires that
// the (template parameter) types 'KEY' and 'VALUE' both be
// "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
iterator insert(const_iterator hint, const value_type& value);
// Insert the specified 'value' into this multimap as close as possible
// to the position just prior to the specified 'hint' (in amortized
// constant time if the specified 'hint' is a valid immediate successor
// to the key of 'value'). If 'hint' is not a valid immediate
// successor to the key of 'value', this operation will have O[log(N)]
// complexity, where 'N' is the size of this multimap. The behavior is
// undefined unless 'hint' is a valid iterator into this multimap.
// This method requires that the (template parameter) types 'KEY' and
// 'VALUE' both be "copy-constructible" (see {Requirements on 'KEY' and
// 'VALUE'}).
template <class INPUT_ITERATOR>
void insert(INPUT_ITERATOR first, INPUT_ITERATOR last);
// Insert into this multimap the value of each 'value_type' object in
// the range starting at the specified 'first' iterator and ending
// immediately before the specified 'last' iterator. The (template
// parameter) type 'INPUT_ITERATOR' shall meet the requirements of an
// input iterator defined in the C++11 standard [24.2.3] providing
// access to values of a type convertible to 'value_type'. This method
// requires that the (template parameter) types 'KEY' and 'VALUE' both
// be "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
iterator erase(const_iterator position);
// Remove from this multimap the 'value_type' object at the specified
// 'position', and return an iterator referring to the element
// immediately following the removed element, or to the past-the-end
// position if the removed element was the last element in the sequence
// of elements maintained by this multimap. The behavior is undefined
// unless 'position' refers to a 'value_type' object in this multimap.
size_type erase(const key_type& key);
// Remote from this multimap all 'value_type' objects having the
// specified 'key', if they exist, and return the number of erased
// objects; otherwise, if there is no 'value_type' objects having
// 'key', return 0 with no other effect.
iterator erase(const_iterator first, const_iterator last);
// Remove from this multimap the 'value_type' objects starting at the
// specified 'first' position up to, but including the specified 'last'
// position, and return 'last'. The behavior is undefined unless
// 'first' and 'last' either refer to elements in this multimap or are
// the 'end' iterator, and the 'first' position is at or before the
// 'last' position in the ordered sequence provided by this container.
void swap(multimap& other);
// Exchange the value of this object as well as its comparator with
// those of the specified 'other' object. Additionally if
// 'bslstl::AllocatorTraits<ALLOCATOR>::propagate_on_container_swap' is
// 'true' then exchange the allocator of this object with that of the
// 'other' object, and do not modify either allocator otherwise. This
// method provides the no-throw exception-safety guarantee and
// guarantees O[1] complexity. The behavior is undefined is unless
// either this object was created with the same allocator as 'other' or
// 'propagate_on_container_swap' is 'true'.
void clear();
// Remove all entries from this multimap. Note that the multimap is
// empty after this call, but allocated memory may be retained for
// future use.
iterator find(const key_type& key);
// Return an iterator providing modifiable access to the first
// 'value_type' object having the specified 'key' in ordered sequence
// maintained by this multimap, if such an object exists; otherwise,
// return the past-the-end ('end') iterator.
iterator lower_bound(const key_type& key);
// Return an iterator providing modifiable access to the first (i.e.,
// ordered least) 'value_type' object in this multimap whose key is
// greater-than or equal-to the specified 'key', and the past-the-end
// iterator if this multimap does not contain a 'value_type' object
// whose key is greater-than or equal-to 'key'. Note that this
// function returns the *first* position before which a 'value_type'
// object having 'key' could be inserted into the ordered sequence
// maintained by this multimap, while preserving its ordering.
iterator upper_bound(const key_type& key);
// Return an iterator providing modifiable access to the first (i.e.,
// ordered least) 'value_type' object in this multimap whose key is
// greater than the specified 'key', and the past-the-end iterator if
// this multimap does not contain a 'value_type' object whose key is
// greater-than 'key'. Note that this function returns the *last*
// position before which a 'value_type' object having 'key' could be
// inserted into the ordered sequence maintained by this multimap,
// while preserving its ordering.
bsl::pair<iterator,iterator> equal_range(const key_type& x);
// Return a pair of iterators providing modifiable access to the
// sequence of 'value_type' objects in this multimap having the
// specified 'key', where the the first iterator is positioned at the
// start of the sequence, and the second is positioned one past the end
// of the sequence. The first returned iterator will be
// 'lower_bound(key)'; the second returned iterator will be
// 'upper_bound(key)'; and, if this multimap contains no 'value_type'
// objects having 'key', then the two returned iterators will have the
// same value.
// ACCESSORS
allocator_type get_allocator() const;
// Return (a copy of) the allocator used for memory allocation by this
// multimap.
const_iterator begin() const;
// Return an iterator providing non-modifiable access to the first
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or the 'end' iterator if this multimap
// is empty.
const_iterator end() const;
// Return an iterator providing non-modifiable access to the
// past-the-end element in the ordered sequence of 'value_type' objects
// maintained by this multimap.
const_reverse_iterator rbegin() const;
// Return a reverse iterator providing non-modifiable access to the
// last 'value_type' object in the ordered sequence of 'value_type'
// objects maintained by this multimap, or 'rend' if this multimap is
// empty.
const_reverse_iterator rend() const;
// Return a reverse iterator providing non-modifiable access to the
// prior-to-the-beginning element in the ordered sequence of
// 'value_type' objects maintained by this multimap.
const_iterator cbegin() const;
// Return an iterator providing non-modifiable access to the first
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or the 'cend' iterator if this multimap
// is empty.
const_iterator cend() const;
// Return an iterator providing non-modifiable access to the
// past-the-end element in the ordered sequence of 'value_type' objects
// maintained by this multimap.
const_reverse_iterator crbegin() const;
// Return a reverse iterator providing non-modifiable access to the
// last 'value_type' object in the ordered sequence of 'value_type'
// objects maintained by this multimap, or 'rend' if this multimap is
// empty.
const_reverse_iterator crend() const;
// Return a reverse iterator providing non-modifiable access to the
// prior-to-the-beginning element in the ordered sequence of
// 'value_type' objects maintained by this multimap.
bool empty() const;
// Return 'true' if this multimap contains no elements, and 'false'
// otherwise.
size_type size() const;
// Return the number of elements in this multimap.
size_type max_size() const;
// Return a theoretical upper bound on the largest number of elements
// that this multimap could possibly hold. Note that there is no
// guarantee that the multimap can successfully grow to the returned
// size, or even close to that size without running out of resources.
key_compare key_comp() const;
// Return the key-comparison functor (or function pointer) used by this
// multimap; if a comparator was supplied at construction, return its
// value, otherwise return a default constructed 'key_compare' object.
// Note that this comparator compares objects of type 'KEY', which is
// the key part of the 'value_type' objects contained in this multimap.
value_compare value_comp() const;
// Return a functor for comparing two 'value_type' objects by comparing
// their respective keys using 'key_comp()'. Note that this
// comparator compares objects of type 'value_type' (i.e.,
// 'bsl::pair<KEY, VALUE>').
const_iterator find(const key_type& key) const;
// Return an iterator providing non-modifiable access to the first
// 'value_type' object having the specified 'key' in ordered sequence
// maintained by this multimap, if such an object exists; otherwise,
// return the past-the-end ('end') iterator.
size_type count(const key_type& key) const;
// Return the number of 'value_type' objects within this multimap
// having the specified 'key'.
const_iterator lower_bound(const key_type& key) const;
// Return an iterator providing non-modifiable access to the first
// (i.e., ordered least) 'value_type' object in this multimap whose key
// is greater-than or equal-to the specified 'key', and the
// past-the-end iterator if this multimap does not contain a
// 'value_type' object whose key is greater-than or equal-to 'key'.
// Note that this function returns the *first* position before which a
// 'value_type' object having 'key' could be inserted into the ordered
// sequence maintained by this multimap, while preserving its ordering.
const_iterator upper_bound(const key_type& key) const;
// Return an iterator providing non-modifiable access to the first
// (i.e., ordered least) 'value_type' object in this multimap whose key
// is greater than the specified 'key', and the past-the-end iterator
// if this multimap does not contain a 'value_type' object whose key is
// greater-than 'key'. Note that this function returns the *last*
// position before which a 'value_type' object having 'key' could be
// inserted into the ordered sequence maintained by this multimap,
// while preserving its ordering.
bsl::pair<const_iterator,const_iterator> equal_range(
const key_type& x) const;
// Return a pair of iterators providing non-modifiable access to the
// sequence of 'value_type' objects in this multimap having the
// specified 'key', where the the first iterator is positioned at the
// start of the sequence, and the second is positioned one past the end
// of the sequence. The first returned iterator will be
// 'lower_bound(key)'; the second returned iterator will be
// 'upper_bound(key)'; and, if this multimap contains no 'value_type'
// objects having 'key', then the two returned iterators will have the
// same value.
// NOT IMPLEMENTED
// The following methods are defined by the C++11 standard, but they
// are not implemented as they require some level of C++11 compiler
// support not currently available on all supported platforms.
// multimap(multimap<KEY,VALUE,COMPARATOR,ALLOCATOR>&& original);
// multimap(multimap&&, const ALLOCATOR&);
// multimap(initializer_list<value_type>,
// const COMPARATOR& = COMPARATOR(),
// const ALLOCATOR& = ALLOCATOR());
// multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>&
// operator=(multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>&& rhs);
// multimap& operator=(initializer_list<value_type>);
// template <class... Args> pair<iterator, bool> emplace(Args&&... args);
// template <class... Args> iterator emplace_hint(const_iterator position,
// Args&&... args);
// template <class P> iterator insert(P&& value);
// template <class P>
// iterator insert(const_iterator position, P&&);
// void insert(initializer_list<value_type>);
};
} // namespace bsl
// ============================================================================
// TYPE TRAITS
// ============================================================================
// Type traits for STL *ordered* containers:
//: o An ordered container defines STL iterators.
//: o An ordered container uses 'bslma' allocators if the parameterized
//: 'ALLOCATOR' is convertible from 'bslma::Allocator*'.
namespace BloombergLP {
namespace bslalg {
template <typename KEY,
typename VALUE,
typename COMPARATOR,
typename ALLOCATOR>
struct HasStlIterators<bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR> >
: bsl::true_type
{};
}
namespace bslma {
template <typename KEY,
typename VALUE,
typename COMPARATOR,
typename ALLOCATOR>
struct UsesBslmaAllocator<bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR> >
: bsl::is_convertible<Allocator*, ALLOCATOR>
{};
}
} // namespace BloombergLP
namespace bsl {
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator==(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects have the same
// value, and 'false' otherwise. Two 'multimap' objects have the same
// value if they have the same number of key-value pairs, and each
// key-value pair that is contained in one of the objects is also contained
// in the other object. This method requires that the (template parameter)
// types 'KEY' and 'VALUE' both be "equality-comparable" (see {Requirements
// on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator!=(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects do not have the
// same value, and 'false' otherwise. Two 'multimap' objects do not have
// the same value if they do not have the same number of key-value pairs,
// or some key-value pair that is contained in one of the objects is not
// also contained in the other object. This method requires that the
// (template parameter) types 'KEY' and 'VALUE' types both be
// "equality-comparable" (see {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator<(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is less than the specified
// 'rhs' value, and 'false' otherwise. A multimap, 'lhs', has a value that
// is less than that of 'rhs', if, for the first non-equal corresponding
// key-value pairs in their respective sequences, the 'lhs' key-value pair
// is less than the 'rhs' pair, or, if the keys of all of their
// corresponding key-value pairs compare equal, 'lhs' has fewer key-value
// pairs than 'rhs'. This method requires that the (template parameter)
// types 'KEY' and 'VALUE' types both be "less-than-comparable" (see
// {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator>(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is greater than the specified
// 'rhs' value, and 'false' otherwise. A multimap, 'lhs', has a value that
// is greater than that of 'rhs', if, for the first non-equal corresponding
// key-value pairs in their respective sequences, the 'lhs' key-value pair
// is greater than the 'rhs' pair, or, if the keys of all of their
// corresponding key-value pairs compare equal, 'lhs' has more key-value
// pairs than 'rhs'. This method requires that the (template parameter)
// types 'KEY' and 'VALUE' both be "less-than-comparable" (see
// {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator<=(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is less-than or equal-to the
// specified 'rhs' value, and 'false' otherwise. A multimap, 'lhs', has a
// value that is less-than or equal-to that of 'rhs', if, for the first
// non-equal corresponding key-value pairs in their respective sequences,
// the 'lhs' key-value pair is less than the 'rhs' pair, or, if the keys of
// all of their corresponding key-value pairs compare equal, 'lhs' has
// less-than or equal number of key-value pairs as 'rhs'. This method
// requires that the (template parameter) types 'KEY' and 'VALUE' both be
// "less-than-comparable" (see {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator>=(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is greater-than or equal-to
// the specified 'rhs' value, and 'false' otherwise. A multimap, 'lhs',
// has a value that is greater-than or equal-to that of 'rhs', if, for the
// first non-equal corresponding key-value pairs in their respective
// sequences, the 'lhs' key-value pair is greater than the 'rhs' pair, or,
// if the keys of all of their corresponding key-value pairs compare equal,
// 'lhs' has greater-than or equal number of key-value pairs as 'rhs'.
// This method requires that the (template parameter) types 'KEY' and
// 'VALUE' types both be "less-than-comparable" (see {Requirements on 'KEY'
// and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
void swap(multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& a,
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& b);
// Swap both the value and the comparator of the specified 'a' object with
// the value and comparator of the specified 'b' object. Additionally if
// 'bslstl::AllocatorTraits<ALLOCATOR>::propagate_on_container_swap' is
// 'true' then exchange the allocator of 'a' with that of 'b', and do not
// modify either allocator otherwise. This method provides the no-throw
// exception-safety guarantee and guarantees O[1] complexity. The
// behavior is undefined is unless either this object was created with the
// same allocator as 'other' or 'propagate_on_container_swap' is 'true'.
// ===========================================================================
// TEMPLATE AND INLINE FUNCTION DEFINITIONS
// ===========================================================================
// -----------------
// class DataWrapper
// -----------------
// CREATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::DataWrapper::DataWrapper(
const COMPARATOR& comparator,
const ALLOCATOR& allocator)
: ::bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::Comparator(comparator)
, d_pool(allocator)
{
}
// --------------
// class multimap
// --------------
// PRIVATE MANIPULATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::NodeFactory&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::nodeFactory()
{
return d_compAndAlloc.d_pool;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::Comparator&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::comparator()
{
return d_compAndAlloc;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::quickSwap(multimap& other)
{
BloombergLP::bslalg::RbTreeUtil::swap(&d_tree, &other.d_tree);
nodeFactory().swap(other.nodeFactory());
// Work around to avoid the 1-byte swap problem on AIX for an empty class
// under empty-base optimization.
if (sizeof(NodeFactory) != sizeof(DataWrapper)) {
comparator().swap(other.comparator());
}
}
// PRIVATE ACCESSORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
const typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::NodeFactory&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::nodeFactory() const
{
return d_compAndAlloc.d_pool;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
const typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::Comparator&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::comparator() const
{
return d_compAndAlloc;
}
// CREATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
template <class INPUT_ITERATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(
INPUT_ITERATOR first,
INPUT_ITERATOR last,
const COMPARATOR& comparator,
const ALLOCATOR& allocator)
: d_compAndAlloc(comparator, allocator)
, d_tree()
{
if (first != last) {
BloombergLP::bslalg::RbTreeUtilTreeProctor<NodeFactory> proctor(
&d_tree,
&nodeFactory());
// The following loop guarantees amortized linear time to insert an
// ordered sequence of values (as required by the standard). If the
// values are in sorted order, we are guaranteed the next node can be
// inseted as the right child of the previous node, and can call
// 'insertAt' without 'findUniqueInsertLocation'.
insert(*first);
BloombergLP::bslalg::RbTreeNode *prevNode = d_tree.rootNode();
while (++first != last) {
// The values are not in order, so insert them normally.
const value_type& value = *first;
if (this->comparator()(value.first, *prevNode)) {
insert(value);
insert(++first, last);
break;
}
BloombergLP::bslalg::RbTreeNode *node = nodeFactory().createNode(
value);
BloombergLP::bslalg::RbTreeUtil::insertAt(&d_tree,
prevNode,
false,
node);
prevNode = node;
}
proctor.release();
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(const multimap& original)
: d_compAndAlloc(original.comparator().keyComparator(),
AllocatorTraits::select_on_container_copy_construction(
original.nodeFactory().allocator()))
, d_tree()
{
if (0 < original.size()) {
nodeFactory().reserveNodes(original.size());
BloombergLP::bslalg::RbTreeUtil::copyTree(&d_tree,
original.d_tree,
&nodeFactory());
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(
const ALLOCATOR& allocator)
: d_compAndAlloc(COMPARATOR(), allocator)
, d_tree()
{
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(
const multimap& original,
const ALLOCATOR& allocator)
: d_compAndAlloc(original.comparator().keyComparator(), allocator)
, d_tree()
{
if (0 < original.size()) {
nodeFactory().reserveNodes(original.size());
BloombergLP::bslalg::RbTreeUtil::copyTree(&d_tree,
original.d_tree,
&nodeFactory());
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::~multimap()
{
clear();
}
// MANIPULATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::operator=(const multimap& rhs)
{
if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(this != &rhs)) {
if (AllocatorTraits::propagate_on_container_copy_assignment::VALUE) {
multimap other(rhs, rhs.nodeFactory().allocator());
BloombergLP::bslalg::SwapUtil::swap(
&nodeFactory().allocator(),
&other.nodeFactory().allocator());
quickSwap(other);
}
else {
multimap other(rhs, nodeFactory().allocator());
quickSwap(other);
}
}
return *this;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::begin()
{
return iterator(d_tree.firstNode());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::end()
{
return iterator(d_tree.sentinel());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rbegin()
{
return reverse_iterator(end());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rend()
{
return reverse_iterator(begin());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::insert(const value_type& value)
{
bool leftChild;
BloombergLP::bslalg::RbTreeNode *insertLocation =
BloombergLP::bslalg::RbTreeUtil::findInsertLocation(&leftChild,
&d_tree,
this->comparator(),
value.first);
BloombergLP::bslalg::RbTreeNode *node = nodeFactory().createNode(value);
BloombergLP::bslalg::RbTreeUtil::insertAt(&d_tree,
insertLocation,
leftChild,
node);
return iterator(node);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
template <class INPUT_ITERATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::insert(INPUT_ITERATOR first,
INPUT_ITERATOR last)
{
while (first != last) {
insert(*first);
++first;
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::insert(const_iterator hint,
const value_type& value)
{
BloombergLP::bslalg::RbTreeNode *hintNode =
const_cast<BloombergLP::bslalg::RbTreeNode *>(hint.node());
bool leftChild;
BloombergLP::bslalg::RbTreeNode *insertLocation =
BloombergLP::bslalg::RbTreeUtil::findInsertLocation(&leftChild,
&d_tree,
this->comparator(),
value.first,
hintNode);
BloombergLP::bslalg::RbTreeNode *node = nodeFactory().createNode(value);
BloombergLP::bslalg::RbTreeUtil::insertAt(&d_tree,
insertLocation,
leftChild,
node);
return iterator(node);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::erase(const_iterator position)
{
BSLS_ASSERT_SAFE(position != end());
BloombergLP::bslalg::RbTreeNode *node =
const_cast<BloombergLP::bslalg::RbTreeNode *>(position.node());
BloombergLP::bslalg::RbTreeNode *result =
BloombergLP::bslalg::RbTreeUtil::next(node);
BloombergLP::bslalg::RbTreeUtil::remove(&d_tree, node);
nodeFactory().deleteNode(node);
return iterator(result);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::erase(const key_type& key)
{
size_type count = 0;
const_iterator first = find(key);
if (first != end()) {
const_iterator last = upper_bound(key);
while (first != last) {
first = erase(first);
++count;
}
}
return count;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::erase(const_iterator first,
const_iterator last)
{
while (first != last) {
first = erase(first);
}
return iterator(last.node());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::swap(multimap& other)
{
if (AllocatorTraits::propagate_on_container_swap::VALUE) {
BloombergLP::bslalg::SwapUtil::swap(&nodeFactory().allocator(),
&other.nodeFactory().allocator());
quickSwap(other);
}
else {
// C++11 behavior: undefined for unequal allocators
// BSLS_ASSERT(allocator() == other.allocator());
// backward compatible behavior: swap with copies
if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(
nodeFactory().allocator() == other.nodeFactory().allocator())) {
quickSwap(other);
}
else {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
multimap thisCopy(*this, other.nodeFactory().allocator());
multimap otherCopy(other, nodeFactory().allocator());
quickSwap(otherCopy);
other.quickSwap(thisCopy);
}
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::clear()
{
BSLS_ASSERT_SAFE(d_tree.firstNode());
if (d_tree.rootNode()) {
BSLS_ASSERT_SAFE(0 < d_tree.numNodes());
BSLS_ASSERT_SAFE(d_tree.firstNode() != d_tree.sentinel());
BloombergLP::bslalg::RbTreeUtil::deleteTree(&d_tree, &nodeFactory());
}
#if defined(BSLS_ASSERT_SAFE_IS_ACTIVE)
else {
BSLS_ASSERT_SAFE(0 == d_tree.numNodes());
BSLS_ASSERT_SAFE(d_tree.firstNode() == d_tree.sentinel());
}
#endif
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::find(const key_type& key)
{
return iterator(BloombergLP::bslalg::RbTreeUtil::find(d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::lower_bound(const key_type& key)
{
return iterator(BloombergLP::bslalg::RbTreeUtil::lowerBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::upper_bound(const key_type& key)
{
return iterator(BloombergLP::bslalg::RbTreeUtil::upperBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bsl::pair<typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator,
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator>
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::equal_range(const key_type& key)
{
iterator startIt = lower_bound(key);
iterator endIt = startIt;
if (endIt != end() && !comparator()(key, *endIt.node())) {
endIt = upper_bound(key);
}
return bsl::pair<iterator, iterator>(startIt, endIt);
}
// ACCESSORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::allocator_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::get_allocator() const
{
return nodeFactory().allocator();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::begin() const
{
return cbegin();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::end() const
{
return cend();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rbegin() const
{
return crbegin();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rend() const
{
return crend();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::cbegin() const
{
return const_iterator(d_tree.firstNode());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::cend() const
{
return const_iterator(d_tree.sentinel());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::crbegin() const
{
return const_reverse_iterator(end());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::crend() const
{
return const_reverse_iterator(begin());
}
// capacity:
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::empty() const
{
return 0 == d_tree.numNodes();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size() const
{
return d_tree.numNodes();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::max_size() const
{
return AllocatorTraits::max_size(get_allocator());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::key_compare
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::key_comp() const
{
return comparator().keyComparator();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::value_compare
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::value_comp() const
{
return value_compare(key_comp());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::find(const key_type& key) const
{
return const_iterator(
BloombergLP::bslalg::RbTreeUtil::find(d_tree, this->comparator(), key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE,COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::count(const key_type& key) const
{
int cnt = 0;
const_iterator it = lower_bound(key);
while (it != end() && !comparator()(key, *it.node())) {
++it;
++cnt;
}
return cnt;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::lower_bound(
const key_type& key) const
{
return iterator(BloombergLP::bslalg::RbTreeUtil::lowerBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::upper_bound(
const key_type& key) const
{
return const_iterator(BloombergLP::bslalg::RbTreeUtil::upperBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bsl::pair<typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator,
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator>
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::equal_range(
const key_type& key) const
{
const_iterator startIt = lower_bound(key);
const_iterator endIt = startIt;
if (endIt != end() && !comparator()(key, *endIt.node())) {
endIt = upper_bound(key);
}
return bsl::pair<const_iterator, const_iterator>(startIt, endIt);
}
} // close namespace bslstl
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator==(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return BloombergLP::bslalg::RangeCompare::equal(lhs.begin(),
lhs.end(),
lhs.size(),
rhs.begin(),
rhs.end(),
rhs.size());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator!=(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return !(lhs == rhs);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator<(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return 0 > BloombergLP::bslalg::RangeCompare::lexicographical(lhs.begin(),
lhs.end(),
lhs.size(),
rhs.begin(),
rhs.end(),
rhs.size());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator>(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return rhs < lhs;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator<=(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return !(rhs < lhs);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator>=(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return !(lhs < rhs);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void bsl::swap(bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& a,
bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& b)
{
a.swap(b);
}
#endif
// ----------------------------------------------------------------------------
// Copyright (C) 2012 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| [
"abeels@bloomberg.net"
] | abeels@bloomberg.net |
2b53c5a5d0be95e878dae379db37f83fedd95660 | 6d0c83e5935251fca6108c75e19666737edafe29 | /include/frame.hpp | 272973e0e354543a38a8e35ca135e4e6654edca8 | [
"BSD-3-Clause"
] | permissive | ssincak/webmPlayer | 7a64951bbf91e966d76a58134fd6138628c5738b | 45d444f5c6cc2effb8558b3aa77e7ddb9d4296e9 | refs/heads/master | 2023-05-29T17:19:44.849366 | 2021-02-14T20:09:48 | 2021-02-14T20:09:48 | 338,888,425 | 6 | 1 | BSD-3-Clause | 2023-05-16T22:37:48 | 2021-02-14T19:50:43 | C | UTF-8 | C++ | false | false | 1,029 | hpp | #ifndef _UVPX_FRAME_H_
#define _UVPX_FRAME_H_
#include <cstdio>
#include <memory>
#include "dll_defines.hpp"
namespace uvpx
{
class UVPX_EXPORT Frame
{
private:
unsigned char *m_y;
unsigned char *m_u;
unsigned char *m_v;
size_t m_ySize;
size_t m_uvSize;
size_t m_width;
size_t m_height;
size_t m_displayWidth;
size_t m_displayHeight;
double m_time;
public:
Frame(size_t width, size_t height);
~Frame();
void copy(Frame *dst);
unsigned char *y() const;
unsigned char *u() const;
unsigned char *v() const;
size_t ySize() const;
size_t uvSize() const;
size_t yPitch() const;
size_t uvPitch() const;
size_t width() const;
size_t height() const;
size_t displayWidth() const;
size_t displayHeight() const;
void setTime(double time);
double time() const;
};
}
#endif // _UVPX_FRAME_H_
| [
"s.sincak@gmail.com"
] | s.sincak@gmail.com |
75aeb5c350c6ca7a3d61b6653dcdcd76a4dda1db | 9c677a1775705f7c8f683d1f89d47e9ed15a32ee | /ACM/天梯训练赛/天梯训练赛1/a.cpp | 626edcede3d0f320c98d3aa4f93c0bb61497865a | [] | no_license | nc-77/algorithms | 16e00a0f8ce60f9b998b9ee4ccc69bcfdb5aa832 | ced943900a2756a76b2c197002010dc9e08b79c4 | refs/heads/main | 2023-05-26T20:11:25.762015 | 2021-06-08T07:16:30 | 2021-06-08T07:16:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
ll gcd(ll x,ll y)
{
return y==0? x:gcd(y,x%y);
}
int main()
{
int n;
cin>>n;
ll x1,y1;
scanf("%lld/%lld",&x1,&y1);
n--;
while(n--)
{
ll x2,y2;
scanf("%lld/%lld",&x2,&y2);
//cout<<x1<<y1<<x2<<y2<<endl;
ll lcm=y1*y2/gcd(y1,y2);
x1=x1*lcm/y1+x2*lcm/y2;
y1=lcm;
if(x1)
{
ll g=gcd(fabs(x1),fabs(y1));
x1=x1/g;
y1=y1/g;
}
}
if(x1)
{
ll g=gcd(fabs(x1),fabs(y1));
x1=x1/g;
y1=y1/g;
}
ll zs=x1/y1;
x1=x1-zs*y1;
if(zs&&x1)
cout<<fabs(zs)<<" "<<x1<<"/"<<y1<<endl;
if(zs&&!x1) cout<<zs<<endl;
if(!zs&&x1) cout<<x1<<"/"<<y1<<endl;
else if(!zs&&!x1) cout<<"0"<<endl;
}
| [
"291993554@qq.com"
] | 291993554@qq.com |
9765102133079989c7038198ce9f92092215dd10 | 9c22a7f4e39ec744d68eac3d5ea9db5c7b2013d7 | /src/appleseed/renderer/kernel/rendering/final/pixelsampler.h | 153cdbd711137ba30c5b6c9d2c9b7349cd621d93 | [
"MIT"
] | permissive | jotpandher/appleseed | 4b6b7f30ce816280c3502d710920e39c740f5d51 | c74bd03e314d3a9fd7dd0cbaeb2f1374ae4b546f | refs/heads/master | 2021-01-15T12:54:13.278636 | 2014-11-23T14:14:01 | 2014-11-23T14:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,191 | h |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifndef APPLESEED_RENDERER_KERNEL_RENDERING_FINAL_PIXELSAMPLER_H
#define APPLESEED_RENDERER_KERNEL_RENDERING_FINAL_PIXELSAMPLER_H
// appleseed.foundation headers.
#include "foundation/core/concepts/noncopyable.h"
#include "foundation/math/vector.h"
#include "foundation/platform/compiler.h"
// Standard headers.
#include <cstddef>
#include <vector>
namespace renderer
{
//
// A strictly deterministic pixel sampler.
//
// Reference:
//
// Strictly Deterministic Sampling Methods in Computer Graphics
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.88.7937
//
class PixelSampler
: public foundation::NonCopyable
{
public:
// Initialize the pixel sampler for a given subpixel grid size.
void initialize(const size_t subpixel_grid_size);
// Compute the position of a pixel sample and optionally the initial instance
// number of the corresponding sampling context, given the integer coordinates
// of the subpixel grid cell containing the sample. The coordinates of the
// pixel sample are expressed in continous image space
// (https://github.com/appleseedhq/appleseed/wiki/Terminology).
void sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position) const;
void sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position,
size_t& initial_instance) const;
private:
size_t m_subpixel_grid_size;
double m_rcp_subpixel_grid_size; // 1.0 / subpixel_grid_size
double m_rcp_period; // 1.0 / m_period
size_t m_log_period; // log2(m_period)
size_t m_period; // m_sigma.size()
size_t m_period_mask; // m_period - 1
std::vector<size_t> m_sigma; // 2^N * radical_inverse_base2(0..N-1)
};
//
// PixelSampler class implementation.
//
FORCE_INLINE void PixelSampler::sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position) const
{
// Compute the sample coordinates in image space.
if (m_subpixel_grid_size == 1)
{
sample_position[0] = sx + 0.5;
sample_position[1] = sy + 0.5;
}
else
{
const size_t j = sx & m_period_mask;
const size_t k = sy & m_period_mask;
const size_t sigma_j = m_sigma[j];
const size_t sigma_k = m_sigma[k];
sample_position[0] = (sx + sigma_k * m_rcp_period) * m_rcp_subpixel_grid_size;
sample_position[1] = (sy + sigma_j * m_rcp_period) * m_rcp_subpixel_grid_size;
}
}
FORCE_INLINE void PixelSampler::sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position,
size_t& initial_instance) const
{
const size_t j = sx & m_period_mask;
const size_t k = sy & m_period_mask;
const size_t sigma_k = m_sigma[k];
// Compute the initial instance number of the sampling context.
initial_instance = (j << m_log_period) + sigma_k;
// Compute the sample coordinates in image space.
if (m_subpixel_grid_size == 1)
{
sample_position[0] = sx + 0.5;
sample_position[1] = sy + 0.5;
}
else
{
const size_t sigma_j = m_sigma[j];
sample_position[0] = (sx + sigma_k * m_rcp_period) * m_rcp_subpixel_grid_size;
sample_position[1] = (sy + sigma_j * m_rcp_period) * m_rcp_subpixel_grid_size;
}
}
} // namespace renderer
#endif // !APPLESEED_RENDERER_KERNEL_RENDERING_FINAL_PIXELSAMPLER_H
| [
"beaune@aist.enst.fr"
] | beaune@aist.enst.fr |
580e82dd33f2e05f0ec4e86e57394d12b8570e30 | 41704dd9a57c4f84e639e7ee2610e5cd71a5826a | /Castlevania/Boss3.cpp | a1e5eef769eff6ed2173252b9fbde5f6ba08ad89 | [] | no_license | GameCastleVania/CSVNL | b373f213b720c316a5784e7506a7bfaa3edf7723 | 65a452d1b36c8c40ce754fcf5affcab2ac665f24 | refs/heads/master | 2020-06-11T10:12:56.490391 | 2017-01-04T20:28:26 | 2017-01-04T20:28:26 | 75,696,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,295 | cpp | #include "Boss3.h"
extern int Boss3HP;
Boss3::Boss3()
{
}
Boss3::Boss3(float X, float Y)
{
PosX = x = X;
PosY = y = Y + 10;
LRight = true;
exploded = false;
shooting = true;
wasHit = false;
hitTime = 0;
isDead = 0;
type = 4;
HP = 16;
vx = 2;
vy = 0;
CRec = RecF(x, y, 32, 80);
}
Boss3::~Boss3()
{
}
void Boss3::Init(LPDIRECT3DDEVICE9 _d3ddv, CSimon * _simon, BulletManager * _bulletManager, Explosion * _explosion)
{
d3ddv = _d3ddv;
simon = _simon;
bulletManager = _bulletManager;
explosion = _explosion;
Boss3L = new Sprite(d3ddv, "resource\\image\\boss\\BMap3\\BossLv3left.png", 32, 80, 2, 2);
Boss3R = new Sprite(d3ddv, "resource\\image\\boss\\BMap3\\BossLv3right.png", 32, 80, 2, 2);
}
void Boss3::Update()
{
if (stopUpdate == false && _stopUpdate == false)
{
Boss3HP = HP;
float _x = simon->GetX() - 32;
float _y = simon->GetY() - 32;
if (_x > 4900) // o giua 2 con booss
{
ready = true;
}
if (ready)
{
if (!wasHit)
{
if (!checkDir)
{
if (setVel)
{
if (x < _x)
vx = 1.3;
else
vx = -1.3;
setVel = false;
}
if (vx > 0 && x > _x || vx < 0 && x < _x)
{
checkDir = true;
setVel = true;
}
}
else
{
if (setVel)
{
vx = -vx;
setVel = false;
}
_Time++;
if (_Time > 100 || x > 5100 || x < 4700)
{
vx = 0;
if (_Time > 120)
{
checkDir = false;
setVel = true;
if (shooting)
{
if (LRight)
BulletShoot(3.0f, 3.1f);
else
BulletShoot(-3.0f, 3.1f);
}
_Time = 0;
}
}
}
if (vx > 0)
LRight = true;
else
LRight = false;
DWORD now = GetTickCount();
if (now - last_time > 1000 / 5)
{
if (!LRight)
Boss3L->NextRepeat();
else
Boss3R->NextRepeat();
last_time = now;
}
}
else
{
if (vx != 0)
vxbackup = vx;
if (vy != 0)
vybackup = vy;
vx = 0;
vy = 0;
hitTime++;
if (hitTime > 30)
{
hitTime = 0;
vx = vxbackup;
vy = vybackup;
wasHit = false;
Hit = true;
}
}
x += vx;
}
}
if (!exploded && HP <= 0)
{
explosion->Get(11, x, y, 7);
explosion->Get(11, x + 25, y, 7);
explosion->Get(11, x + 50, y, 7);
explosion->Get(11, x, y - 25, 7);
explosion->Get(11, x + 25, y - 25, 7);
explosion->Get(11, x + 50, y - 25, 7);
explosion->Get(12, 4800, 132, 7);
exploded = true;
visible = false;
shooting = false;
ready = false;
}
UpdateRec();
}
void Boss3::UpdateGunPoint()
{
}
void Boss3::Draw(int vpx, int vpy)
{
if (visible)
{
if (!exploded)
{
if (LRight)
Boss3R->Render(x + 32, y + 32, vpx, vpy);
else
Boss3L->Render(x + 32, y + 32, vpx, vpy);
}
}
}
void Boss3::BulletShoot(float _vx, float _vy)
{
bulletManager->Get(3, x, y, _vx, _vy);
}
void Boss3::UpdateRec()
{
if (HP > 0)
{
CRec = RecF(x, y, 32, 80);
}
else
{
CRec = RecF(0, 0, 0, 0);
}
if (visible == false)
CRec = RecF(0, 0, 0, 0);
}
void Boss3::Destroy()
{
HP = 0;
}
| [
"13520592@gm.uit.edu.vn"
] | 13520592@gm.uit.edu.vn |
4bb94af72fc98157a4f731aa605f9edc816b5311 | e8307413bff4b74a4949597d130738b85ad61e0e | /PlateDemo/mythread.cpp | 2abda93884a7e0aea110024aadcc5032ee7dc750 | [] | no_license | isliulin/SCPark | 3ec0b5ddf1ef31b434965b86d70b4ba69851ba40 | e9e83072fa35eff672585fcf3dae94eaee953413 | refs/heads/master | 2021-05-30T04:59:37.253340 | 2016-01-08T02:56:14 | 2016-01-08T02:56:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include "mythread.h"
#include "MainWindow.h"
CMyThread::CMyThread(QObject *parent) :
QThread(parent)
{
}
void CMyThread::run( )
{
MainWindow* pMulti = ( MainWindow* ) parent( );
quint8 data[ 704 * 576 * 4 ];
ULONG lSize = 704 * 576 * 4;
while ( true ) {
pMulti->Recognize( data, lSize );
}
}
| [
"Anne081031@hotmail.com"
] | Anne081031@hotmail.com |
be26d26c67bdb2e48add41007aa9e893e0a126cc | 4d49d4d59c9517fe99884cd69ad88644265c6755 | /week3/Group3/boj4779_seongbin9786.cpp | a1015c8d5eac148327b7f5d8158dd0049782f5b0 | [] | no_license | all1m-algorithm-study/2021-1-Algorithm-Study | 3f34655dc0a3d8765143f4230adaa96055d13626 | 73c7cac1824827cb6ed352d49c0ead7003532a35 | refs/heads/main | 2023-06-03T18:45:28.852381 | 2021-06-11T06:28:44 | 2021-06-11T06:28:44 | 348,433,854 | 8 | 16 | null | 2021-06-11T06:28:45 | 2021-03-16T17:23:37 | Python | UTF-8 | C++ | false | false | 2,576 | cpp | #include <iostream>
#include <math.h>
/*
[Silver 3]
칸토어 집합
칸토어 집합은 0과 1사이의 실수로 이루어진 집합으로,
구간 [0, 1]에서 시작해서 각 구간을 3등분하여 가운데
구간을 반복적으로 제외하는 방식으로 만든다.
집합이 유한
칸토어 집합의 근사
----
걍 - 패턴 구하는 재귀 문제이다.
제거되는 형태가 이진 탐색 (중간은 제거되니깐 삼진 탐색은 아니다.)
----
1. -가 3N개 있는 문자열에서 시작한다. (중간값이 없을 일이 없다.)
2. 문자열을 3등분 한 뒤, 가운데 문자열을 공백으로 바꾼다.
이렇게 하면, 선(문자열) 2개가 남는다.
3. 이제 각 선(문자열)을 3등분 하고, 가운데 문자열을 공백으로 바꾼다.
이 과정은 모든 선의 길이가 1일때 까지 계속 한다.
예를 들어, N=3인 경우, 길이가 27인 문자열로 시작한다.
----
EXAMPLE
NUM=3
N=27
===>1/3을 1/3시점부터 제거한다.
===>27/3=9 => idx=9면, no no
===> idx=8[9번째니까]부터9개 제거
===> 이후 idx=0, idx=17 부터 시작 (ok)
근데 이거 애초에
buf 만들고 지우고 이러지 말고
끝까지 간 다음 출력만 하면 되는 것 아닌가?
----
틀린 이유:
입력을 여러 줄로 이루어져 있다. 각 줄에 N이 주어진다. 파일의 끝에서 입력을 멈춘다. N은 0보다 크거나 같고, 12보다 작거나 같은 정수이다.
입력이 여러 개였음;;
*/
using namespace std;
int N;
void c(int begin, int end, int depth, bool fill)
{
if (depth == 0)
{
while (begin++ < end)
cout << (fill ? '-' : ' '); // 괄호 안 치면 111 로 나오는건 뭐야?
return;
}
int tmp = (end - begin) / 3;
c(begin, begin + tmp, depth - 1, true);
c(begin + tmp, begin + tmp * 2, 0, false); // depth=0으로 바로 줘야 함. 더 깊이 안들어가니까
c(begin + tmp * 2, begin + tmp * 3, depth - 1, true);
}
// 입력 받을 개수를 안 주면 어떻게 함?
// 신기한 거 많네 ㅋㅋ
// 이런식으로 푸는 문제도 있구만
int main()
{
int NUM;
while (true)
{
// cin으로 입력받은 값이 없으면
// cin.eof()는 true를 반환한다. 당연히 그렇지 않으면 false 반환
cin >> N;
if (cin.eof() == true)
break;
NUM = (int)pow(3, N);
c(0, NUM, N, true);
cout << "\n";
}
return 0;
}
| [
"seongbin9786@gmail.com"
] | seongbin9786@gmail.com |
03a5ea2507f3f491900424c757dd0098ff6bfb99 | db1292c07e591e8456f11601dba20c0068c9cecc | /tensorflow/compiler/xla/service/hlo_module_config.h | f375210e65fa6b5c52766e83d8d513336b35056e | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | mkuchnik/PlumberTensorflow | e4c8e66713b9bccfe24c0e80a54794ae2c413e7b | 08bf144ec13b0c27f2a02aaba975546506ee0f6a | refs/heads/main | 2023-04-18T21:08:15.080909 | 2022-02-24T01:12:48 | 2022-02-25T01:26:10 | 459,011,882 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,573 | h | /* Copyright 2017 The TensorFlow Authors. 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.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_CONFIG_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_CONFIG_H_
#include <string>
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/computation_layout.h"
#include "tensorflow/compiler/xla/service/computation_placer.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla.pb.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
namespace xla {
enum class FusionConfigCollection {
kOff, // Do not collect configuration.
kPerEdge, // Collect per-edge configuration.
kPerNode, // Collect per-node configuration.
};
// This class gathers all settings and values which affect the compiled
// executable outside of the HLO code itself. This include layouts of inputs and
// outputs to the module and settings such as HLO profiling. Together the
// HloModule and HloModuleConfig unambiguously determine a particular
// executable.
class HloModuleConfig {
public:
// Represents a pair of input and output of the entry computation that can be
// considered as the original and updated values of a variable maintained by
// the caller, and that can be transparently sharded by XLA as an internal
// optimization. If sharded, XLA will create separate sharding/unsharding
// programs, and the caller is responsible to call the XLA-generated
// sharding/unsharding programs before and after the sharded main program.
//
// If the variable is not updated and there is not a corresponding output, use
// {-1} as the output_shape_index.
//
// The sharding/unsharding programs will include all the input/output pairs in
// shardable_value_update_pairs() as a flat tuple in their inputs/outputs,
// sorted by (input_parameter_number, parameter_shape_index).
//
// A typical usage pattern is to shard the variables first, then repeatedly
// invoke the main program, and finally invoke the unsharding program before
// they are used in full-shape.
struct ShardableValueUpdatePair {
int64 input_parameter_number;
ShapeIndex parameter_shape_index;
ShapeIndex output_shape_index;
};
// A configuration can be created either with, or without an entry
// ComputationLayout. The default ctor creates it without -- in this case
// accessing entry_computation_layout will CHECK-fail. The ctor accepting a
// ProgramShape creates a computation layout using this shape.
// The layouts in the ProgramShape will be reset to default unless
// ignore_layouts is set to false.
HloModuleConfig() { debug_options_ = DefaultDebugOptionsIgnoringFlags(); }
explicit HloModuleConfig(const ProgramShape& program_shape,
bool ignore_layouts = true);
explicit HloModuleConfig(ComputationLayout entry_computation_layout);
// Checks if this config has an entry computation layout already.
bool has_entry_computation_layout() const {
return entry_computation_layout_.has_value();
}
// Sets the entry_computation_layout's parameter and result shapes for this
// config, according to the given program shape. The parameters and result
// are set to default layout.
void SetDefaultComputationLayout(const ProgramShape& program_shape);
// Same as above but if the given program contains layout for parameters or
// result, the entry_computation_layout's layout is updated accordingly.
void SetComputationLayoutIfExists(const ProgramShape& program_shape);
// Returns a constant reference to the layout of the entry computation.
// Assumes the layout was set.
const ComputationLayout& entry_computation_layout() const {
CHECK(entry_computation_layout_.has_value());
return *entry_computation_layout_;
}
// Returns a mutable pointer to the layout of the entry computation.
// Assumes the layout was set.
ComputationLayout* mutable_entry_computation_layout() {
CHECK(entry_computation_layout_.has_value());
return &(*entry_computation_layout_);
}
// Returns whether to enable HLO-level profiling.
bool hlo_profiling_enabled() const {
return debug_options_.xla_hlo_profile();
}
bool cpu_traceme_enabled() const {
return debug_options_.xla_cpu_enable_xprof_traceme();
}
// Sets/returns the module seed set during execution.
void set_seed(uint64 seed) { seed_ = seed; }
uint64 seed() const { return seed_; }
// Set the launch id of the program. Launch id identifies a set of programs
// that should be launched together.
void set_launch_id(uint64 launch_id) { launch_id_ = launch_id; }
int32 launch_id() const { return launch_id_; }
void set_replica_count(int64_t replica_count) {
replica_count_ = replica_count;
}
int64 replica_count() const { return replica_count_; }
void set_num_partitions(int64_t num_partitions) {
num_partitions_ = num_partitions;
}
int64 num_partitions() const { return num_partitions_; }
const std::vector<bool> param_requires_broadcast_via_collectives() const {
return param_requires_broadcast_via_collectives_;
}
void set_param_requires_broadcast_via_collectives(
const std::vector<bool> require_broadcast) {
param_requires_broadcast_via_collectives_ = std::move(require_broadcast);
}
void set_use_spmd_partitioning(bool use_spmd_partitioning) {
use_spmd_partitioning_ = use_spmd_partitioning;
}
bool use_spmd_partitioning() const { return use_spmd_partitioning_; }
// If enabled, deduplicate equivalent hlos into function calls to reduce code
// size.
void set_deduplicate_hlo(bool deduplicate_hlo) {
deduplicate_hlo_ = deduplicate_hlo;
}
bool deduplicate_hlo() const { return deduplicate_hlo_; }
// Return a string which unambiguously represents all the fields of this data
// structure. Used for generating a cache key for storing the compiled
// executable.
string compilation_cache_key() const;
const DebugOptions& debug_options() const { return debug_options_; }
void set_debug_options(const DebugOptions& debug_options) {
debug_options_ = debug_options;
}
// Sets/returns the number of intra op threads for this module.
void set_intra_op_parallelism_threads(
const int intra_op_parallelism_threads) {
intra_op_parallelism_threads_ = intra_op_parallelism_threads;
}
int64 intra_op_parallelism_threads() const {
return intra_op_parallelism_threads_;
}
// Checks if this config has a static device assignment.
bool has_static_device_assignment() const {
return static_device_assignment_.has_value();
}
// Getter and setter of the compile-time known device assignment.
const DeviceAssignment& static_device_assignment() const {
CHECK(static_device_assignment_.has_value());
return *static_device_assignment_;
}
void set_static_device_assignment(const DeviceAssignment& device_assignment) {
static_device_assignment_ = device_assignment;
}
const std::vector<ShardableValueUpdatePair> shardable_value_update_pairs()
const {
return shardable_value_update_pairs_;
}
void set_shardable_value_update_pairs(
std::vector<ShardableValueUpdatePair> pairs) {
shardable_value_update_pairs_ = std::move(pairs);
}
// Whether input and output buffers are aliased if the associated parameter is
// passed-through XLA modules without being changed.
bool alias_passthrough_params() const { return alias_passthrough_params_; }
void set_alias_passthrough_params(bool alias_passthrough_params) {
alias_passthrough_params_ = alias_passthrough_params;
}
bool content_aware_computation_sorting() const {
return content_aware_computation_sorting_;
}
void set_content_aware_computation_sorting(
bool content_aware_computation_sorting) {
content_aware_computation_sorting_ = content_aware_computation_sorting;
}
FusionConfigCollection fusion_config_collection() const {
return fusion_config_collection_;
}
void set_fusion_config_collection(
FusionConfigCollection fusion_config_collection) {
fusion_config_collection_ = fusion_config_collection;
}
const std::vector<std::vector<bool>>& fusion_config() const {
return fusion_config_;
}
std::vector<std::vector<bool>>* mutable_fusion_config() {
return &fusion_config_;
}
const std::vector<std::vector<int64>>& dot_config() const {
return dot_config_;
}
std::vector<std::vector<int64>>* mutable_dot_config() { return &dot_config_; }
const std::vector<std::vector<std::vector<int64>>>& layout_config() const {
return layout_config_;
}
std::vector<std::vector<std::vector<int64>>>* mutable_layout_config() {
return &layout_config_;
}
const std::vector<std::vector<bool>>& phase_ordering_config() const {
return phase_ordering_config_;
}
std::vector<std::vector<bool>>* mutable_phase_ordering_config() {
return &phase_ordering_config_;
}
const int phase_index() const { return phase_index_; }
void set_phase_index(const int phase_index) { phase_index_ = phase_index; }
private:
// If you add new members, be sure to update compilation_cache_key.
absl::optional<ComputationLayout> entry_computation_layout_;
// Module/graph-level seed handle.
uint64 seed_ = 0;
// Program id that identifies a set of program to be launched together.
int32 launch_id_ = 0;
// The number of replicas (data parallelism) to compile this binary for.
int64 replica_count_ = 1;
// The number of partitions (model parallelism) to compile this binary for.
int64 num_partitions_ = 1;
// Whether to broadcast args across all replicas. One entry per arg.
std::vector<bool> param_requires_broadcast_via_collectives_;
// Whether to use SPMD (true) or MPMD (false) when num_partitions_ > 0 and XLA
// needs to partition the module.
bool use_spmd_partitioning_ = false;
// If enabled, deduplicate equivalent hlos into function calls to reduce code
// size.
bool deduplicate_hlo_ = false;
// The target maximum parallelism at which to partition HLOs for parallel
// execution on the CPU backend.
int64 intra_op_parallelism_threads_ = -1;
DebugOptions debug_options_;
// Compile-time known device assignment.
absl::optional<DeviceAssignment> static_device_assignment_;
std::vector<ShardableValueUpdatePair> shardable_value_update_pairs_;
bool alias_passthrough_params_ = false;
bool content_aware_computation_sorting_ = true;
FusionConfigCollection fusion_config_collection_ =
FusionConfigCollection::kOff;
// TODO(b/155665133): Consolidate fusion, dot, and layout config into a proto
// similar to backend config.
// Custom fusion configuration, where fusion_config_[c][v] control if node v
// in computation c must be fused to all its consumers (true) or not (false).
std::vector<std::vector<bool>> fusion_config_;
// Custom dot canonicalization configuration, where dot_config_[v] control
// how to convert dot operation v (sorted topologically and by computation) to
// convolution.
std::vector<std::vector<int64>> dot_config_;
// Layout configuration, where layout_config_[v][i] controls the layout
// decision i of operation v.
std::vector<std::vector<std::vector<int64>>> layout_config_;
// Phase ordering configuration, where phase_ordering_config[v][i] controls
// whether a specific pass with index i (e.g. 0 = DCE, 1 = CSE, etc.) is
// inserted after pass v in pipeline. See tuning::PhaseOrderingConfig for
// details on what indices (i) correspond to which passes.
std::vector<std::vector<bool>> phase_ordering_config_;
// Index (v) corresponding to current passes being added for phase ordering.
// This is the variable that stores state to allow us to use the same
// config across functions during compilation.
int phase_index_;
};
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_CONFIG_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
a42897852f2cda134f5a7ad8403c9e081a62ceda | e000dfb2e1ddfe62598da937d2e0d40d6efff61b | /venusmmi/app/Cosmos/MusicPlayer/vapp_music_player_ncentercell.cpp | 931ce515ee90dfd3eac62b88be2f7053fcd9b72e | [] | no_license | npnet/KJX_K7 | 9bc11e6cd1d0fa5996bb20cc6f669aa087bbf592 | 35dcd3de982792ae4d021e0e94ca6502d1ff876e | refs/heads/master | 2023-02-06T09:17:46.582670 | 2020-12-24T02:55:29 | 2020-12-24T02:55:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,607 | cpp | /*****************************************************************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2008
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
/*******************************************************************************
* Filename:
* ---------
* vapp_music_player_ncentercell.cpp
*
* Project:
* --------
* FTO Music Player notification center cell class
*
* Description:
* ------------
*
*
* Author:
* -------
* -------
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*------------------------------------------------------------------------------
* removed!
*
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#include "mmi_features.h"
#ifdef __COSMOS_MUSICPLY__
#ifdef __MMI_NCENTER_SUPPORT__
/*****************************************************************************
* Include
*****************************************************************************/
#include "vcp_global_popup.h"
#include "vapp_music_player_ncentercell.h"
#include "vapp_music_player.h"
#include "vapp_music_player_util.h"
#include "mmi_rp_vapp_music_player_def.h"
#include "vsrv_ncenter.h"
/* Pluto MMI headers */
#ifdef __cplusplus
extern "C"
{
#endif
#include "UCMSrvGProt.h"
#ifdef __cplusplus
}
#endif
/*****************************************************************************
* Event receiver functions
*****************************************************************************/
VfxBool g_close_exit_popup = TRUE;
#ifdef __cplusplus
extern "C"
{
#endif
void vapp_music_player_update_cell()
{
MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_UPDATE_CELL);
VsrvNGroupSingleTitle *group;
VSRV_NGROUP_CREATE_EX(group, VsrvNGroupSingleTitle, (VAPP_MUSIC_PLAYER));
group->setTitle(VFX_WSTR_RES(STR_ID_VAPP_MUSIC_PLAYER));
VsrvNotificationCustom *notify = NULL;
VSRV_NOTIFICATION_CREATE_EX(notify, VsrvNotificationCustom, (VAPP_MUSIC_PLAYER, 0));
notify->setAutoLaunch(VFX_FALSE);
notify->setAutoClose(VFX_FALSE);
//notify->setIntentCallback(vapp_music_player_Intent_callback, NULL, 0);
notify->addCustomViewInfo(VFX_OBJ_CLASS_INFO(VappMusicPlayerNcenterCustomerCell),VSRV_NVIEWER_TYPE_GENERAL,NULL,0);
notify->setHeight(NCENTER_H);
notify->notify();
}
mmi_ret vapp_music_player_on_open_close(mmi_event_struct *evt)
{
VappMusicPlayerOpenCloseEvtStruct *openCloseEvt = (VappMusicPlayerOpenCloseEvtStruct*) evt;
MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_ON_OPEN_CLOSE, openCloseEvt->isOpen);
if(openCloseEvt->isOpen)
{
// do nothing
}
else
{
VSRV_NOTIFICATION_CLOSE_EX((VsrvNGroupId)VAPP_MUSIC_PLAYER, 0);
}
return MMI_RET_OK;
}
mmi_ret vapp_music_player_on_show_hide(mmi_event_struct *evt)
{
//MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_ON_SHOW_HIDE, showHideEvt->isShow);
vapp_music_player_update_cell();
return MMI_RET_OK;
}
mmi_ret vapp_music_player_on_play_start_stop(mmi_event_struct *evt)
{
VsrvNCenter *srvNCenter = VFX_OBJ_GET_INSTANCE(VsrvNCenter);
if (srvNCenter && !srvNCenter->queryNGroup(VAPP_MUSIC_PLAYER))
{
return MMI_RET_OK;
}
// MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_ON_PLAY_START_STOP, playEvt->isPlayStart);
vapp_music_player_update_cell();
return MMI_RET_OK;
}
#ifdef __cplusplus
}
#endif
static mmi_ret cancel_global_popup(mmi_event_struct *evt)
{
music_player_cancel_popup_event_struct *evnt = (music_player_cancel_popup_event_struct *)evt;
VfxS32 popuphandle = evnt->popup_handle;
if (popuphandle != NULL && g_close_exit_popup)
{
vcp_global_popup_cancel(popuphandle);
}
g_close_exit_popup = TRUE;
return MMI_RET_OK;
}
static MMI_BOOL VappMusicPlayerNCellCallback(mmi_scenario_id scen_id, void *user_data)
{
//dummy
return MMI_TRUE;
}
/*****************************************************************************
* Music Player Widget Base Panel Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappNcenterMusicPlayerBase", VappNcenterMusicPlayerBase, VfxControl);
VappNcenterMusicPlayerBase::~VappNcenterMusicPlayerBase()
{
/* Disconnect app signal */
if(m_mplayerSrv != NULL)
{
m_mplayerSrv->m_signalOnPrevNext.disconnect(this, &VappNcenterMusicPlayerBase::onPrevNext);
}
/* Disconnect playback singal */
if(m_ctrlPlayback != NULL)
{
m_ctrlPlayback->m_signalPlaybackStateChange.disconnect(this, &VappNcenterMusicPlayerBase::onPlaybackStateChange);
m_ctrlPlayback->m_signalMDICallback.disconnect(this, &VappNcenterMusicPlayerBase::onMDICallback);
}
}
void VappNcenterMusicPlayerBase::getAppControl(void)
{
m_mplayerSrv = getMusicPlayerSrv();
if(m_mplayerSrv)
{
m_mplayerSrv->m_signalOnPrevNext.connect(this, &VappNcenterMusicPlayerBase::onPrevNext);
/* Get playback control and connect state change */
m_ctrlPlayback = m_mplayerSrv->getCtrlPlayback();
m_ctrlPlayback->m_signalPlaybackStateChange.connect(this, &VappNcenterMusicPlayerBase::onPlaybackStateChange);
m_ctrlPlayback->m_signalMDICallback.connect(this, &VappNcenterMusicPlayerBase::onMDICallback);
}
}
void VappNcenterMusicPlayerBase::onPlayPause(void)
{
if(m_ctrlPlayback != NULL)
{
m_ctrlPlayback->setIsAppMode(TRUE);
PlaybackStateEnum state;
state = m_ctrlPlayback->getPlayState();
MMI_TRACE(MMI_MEDIA_TRC_G2_APP, TRC_VAPP_WIDGET_MUSICPLY_INFO_PANEL_BTN_CLICK, state);
if(PB_STATE_PLAY == state ||
PB_STATE_PAUSE == state ||
PB_STATE_OPEN == state ||
PB_STATE_STOP == state ||
PB_STATE_CLOSE == state ||
PB_STATE_SWITCHING_PLAY == state ||
PB_STATE_SWITCHING_NOT_PLAY == state ||
PB_STATE_INTERRUPTED == state ||
PB_STATE_BT_CONNECTING_WHILE_PLAYING == state)
{
/* Stop the song if the song is not pausable */
if ((state == PB_STATE_PLAY || state == PB_STATE_BT_CONNECTING_WHILE_PLAYING) &&
!m_ctrlPlayback->isSongPausable(NULL))
{
m_ctrlPlayback->stop();
}
else if (m_ctrlPlayback->m_playStateBeforeSeek == PB_STATE_PAUSE)
{
// do seek while pasued
if(m_mplayerSrv)
{
m_mplayerSrv->setPlayAfterSwitchSong(VFX_TRUE);
}
m_ctrlPlayback->play();
}
else
{
if(m_mplayerSrv)
{
m_mplayerSrv->setPlayAfterSwitchSong(VFX_TRUE);
}
m_ctrlPlayback->playpause();
}
}
}
}
void VappNcenterMusicPlayerBase::onPrev(void)
{
if(m_mplayerSrv != NULL && isValidState())
{
/* Control music player to previous song */
m_mplayerSrv->onPrev(VFX_TRUE);
}
}
void VappNcenterMusicPlayerBase::onNext(void)
{
if(m_mplayerSrv != NULL && isValidState())
{
/* Control music player to next song */
m_mplayerSrv->onNext(NEXT, VFX_TRUE);
}
}
VfxBool VappNcenterMusicPlayerBase::isValidState(void)
{
if((m_mplayerSrv == NULL) || (m_mplayerSrv && (m_mplayerSrv->getActiveCount() == 0)))
{
return VFX_FALSE;
}
return VFX_TRUE;
}
/*****************************************************************************
* Music PlayerVappNcenterMusicPlayerInfoPanel Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappNcenterMusicPlayerInfoPanel", VappNcenterMusicPlayerInfoPanel, VappNcenterMusicPlayerBase)
VappNcenterMusicPlayerInfoPanel::~VappNcenterMusicPlayerInfoPanel()
{
/* Deregister app event callback */
mmi_frm_cb_dereg_event(EVT_ID_SRV_UCM_STATUS_CHANGE,(mmi_proc_func)&VappNcenterMusicPlayerInfoPanel::staticEventHandler, this);
}
void VappNcenterMusicPlayerInfoPanel::onInit()
{
VfxFrame::onInit();
initUI();
getAppControl();
updateButton();
updatePanel();
mmi_frm_cb_reg_event(EVT_ID_SRV_UCM_STATUS_CHANGE,(mmi_proc_func)&VappNcenterMusicPlayerInfoPanel::staticEventHandler, this);
}
void VappNcenterMusicPlayerInfoPanel::initUI()
{
this->setPos(PANEL_X, PANEL_Y);
this->setSize(NCENTER_PANEL_W, NCENTER_PANEL_H);
this->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE);
VFX_OBJ_CREATE(m_background, VfxImageFrame, this);
m_background->setResId(IMG_ID_VAPP_MUSICPLY_BTN_BG_PANEL_NC);
m_background->setRect(0, 0, this->getSize().width, this->getSize().height);
m_background->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE);
m_background->setContentPlacement(VFX_FRAME_CONTENT_PLACEMENT_TYPE_RESIZE);
// icon
VFX_OBJ_CREATE(m_icon, VfxImageFrame, this);
m_icon->setPos(ICON_X, ICON_Y);
m_icon->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_NONE,VFX_FRAME_ALIGNER_MODE_NONE);
m_icon->setResId(IMG_ID_VAPP_MUSICPLY_NCENTER_ICON);
// btn_close
VFX_OBJ_CREATE(m_close_btn, VcpImageButton, this);
m_close_btn->setAnchor(1.0f, 0.0f);
m_close_btn->setPos(NCENTER_PANEL_W-ICON_X, ICON_Y);
m_close_btn->setSize(VAPP_NCENTER_ONGOING_CELL_CLOSE_BUTTON_WIDTH,VAPP_NCENTER_ONGOING_CELL_CLOSE_BUTTON_HEIGHT);
m_close_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_NONE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_NONE);
m_close_btn->setId(BTN_COLSE);
m_close_btn->setImage(VcpStateImage(VAPP_IMG_NCENTER_CLOSE_ICON));
m_close_btn->m_signalClicked.connect(this,&VappNcenterMusicPlayerInfoPanel::onButtonClicked);
// Song title
VFX_OBJ_CREATE(m_textTitle, VfxTextFrame, this);
m_textTitle->setSize(NCENTER_PANEL_W-TEXT_X*2,m_textTitle->getSize().height);
m_textTitle->setFont(VfxFontDesc(VFX_FONT_DESC_VF_SIZE(FONT_SIZE)));
m_textTitle->setPos(TEXT_X, TEXT_Y);
m_textTitle->setTruncateMode(VfxTextFrame::TRUNCATE_MODE_END);
m_textTitle->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_NONE);
/* Create button */
VFX_OBJ_CREATE(m_prev_btn,VcpButton,this);
m_prev_btn->setId(BTN_PREV);
m_prev_btn->setPos(PRAV_NEXT_BTN_X, PRAV_NEXT_BTN_Y);
m_prev_btn->setImage(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_PREV_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PREV_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PREV_D_NC, 0));
m_prev_btn->setBgImageList(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_D_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, 0));
m_prev_btn->setSize(PRAV_NEXT_BTN_SIZE, PRAV_NEXT_BTN_SIZE);
m_prev_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_MID, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_NONE, VFX_FRAME_ALIGNER_MODE_NONE);
m_prev_btn->setPlacement(VCP_BUTTON_PLACEMENT_IMAGE_ONLY);
m_prev_btn->setMargin(0,0,0,0);
m_prev_btn->m_signalClicked.connect(this, &VappNcenterMusicPlayerInfoPanel::onButtonClicked);
m_prev_btn->setFuzzy(VFX_FALSE);
VFX_OBJ_CREATE(m_play_btn,VcpButton,this);
m_play_btn->setId(BTN_PLAY);
m_play_btn->setAnchor(0.5f, 0.0f);
m_play_btn->setPos(VAPP_NCENTER_ONGOING_CELL_WIDTH/2, PLAY_BTN_Y);
m_play_btn->setImage(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0));
m_play_btn->setBgImageList(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_BG1_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG1_D_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG1_N_NC, 0));
m_play_btn->setSize(PLAY_BTN_W, PLAY_BTN_H);
m_play_btn->setIsAutoResized(VFX_FALSE);
m_play_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_MID, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_NONE, VFX_FRAME_ALIGNER_MODE_NONE);
m_play_btn->setPlacement(VCP_BUTTON_PLACEMENT_IMAGE_ONLY);
m_play_btn->setMargin(0,0,0,0);
m_play_btn->m_signalClicked.connect(this, &VappNcenterMusicPlayerInfoPanel::onButtonClicked);
m_play_btn->setFuzzy(VFX_FALSE);
VFX_OBJ_CREATE(m_next_btn,VcpButton,this);
m_next_btn->setId(BTN_NEXT);
m_next_btn->setAnchor(1.0f, 0.0f);
m_next_btn->setPos(NCENTER_PANEL_W-PRAV_NEXT_BTN_X, PRAV_NEXT_BTN_Y);
m_next_btn->setImage(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_NEXT_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_NEXT_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_NEXT_D_NC, 0));
m_next_btn->setBgImageList(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_D_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, 0));
m_next_btn->setSize(PRAV_NEXT_BTN_SIZE, PRAV_NEXT_BTN_SIZE);
m_next_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_NONE, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_MID, VFX_FRAME_ALIGNER_MODE_NONE);
m_next_btn->setPlacement(VCP_BUTTON_PLACEMENT_IMAGE_ONLY);
m_next_btn->setMargin(0,0,0,0);
m_next_btn->m_signalClicked.connect(this, &VappNcenterMusicPlayerInfoPanel::onButtonClicked);
m_next_btn->setFuzzy(VFX_FALSE);
}
void VappNcenterMusicPlayerInfoPanel::destroyUI()
{
VFX_OBJ_CLOSE(m_textTitle);
VFX_OBJ_CLOSE(m_background);
VFX_OBJ_CLOSE(m_icon);
VFX_OBJ_CLOSE(m_close_btn);
VFX_OBJ_CLOSE(m_play_btn);
VFX_OBJ_CLOSE(m_prev_btn);
VFX_OBJ_CLOSE(m_next_btn);
sendPostCloseExitpopup();
}
void VappNcenterMusicPlayerInfoPanel::sendPostCloseExitpopup()
{
if ( m_popup_id != NULL)
{
music_player_cancel_popup_event_struct postInvoke;
MMI_FRM_INIT_EVENT(&postInvoke, 0);
postInvoke.popup_handle = m_popup_id;
MMI_FRM_POST_EVENT(&postInvoke, (mmi_proc_func)&cancel_global_popup, NULL);
}
}
void VappNcenterMusicPlayerInfoPanel::onButtonClicked(VfxObject* obj, VfxId id)
{
/* if(srv_ucm_query_call_count(SRV_UCM_CALL_STATE_ALL, SRV_UCM_CALL_TYPE_NO_CSD, NULL) > 0)
{
return;
}*/
switch(id)
{
case BTN_PLAY:
onPlayPause();
break;
case BTN_PREV:
onPrev();
break;
case BTN_NEXT:
onNext();
break;
case BTN_COLSE:
onCloseButtonClick();
default:
break;
}
}
void VappNcenterMusicPlayerInfoPanel::onPlaybackStateChange(PlaybackStateEnum state)
{
switch(state)
{
case PB_STATE_NONE:
/* Check if app clear its active list */
if(!isValidState())
{
updatePanel();
return;
}
break;
case PB_STATE_OPEN:
updatePanel();
break;
case PB_STATE_PLAY:
updateButton();
break;
case PB_STATE_PAUSE:
updateButton();
break;
case PB_STATE_STOP:
updateButton();
break;
case PB_STATE_CLOSE:
updatePanel();
break;
case PB_STATE_PLAYBACK_FAIL:
updateButton();
break;
default:
updateButton();
break;
}
}
void VappNcenterMusicPlayerInfoPanel::onMDICallback(VfxS32 result)
{
switch (result)
{
case VAPP_MUSICPLY_INTERRUPT_CB_RESUME:
if(m_popup_id != NULL)
{
g_close_exit_popup = FALSE;
}
break;
default:
break;
}
}
void VappNcenterMusicPlayerInfoPanel::onCloseButtonClick()
{
mmi_frm_nmgr_notify_by_app(MMI_SCENARIO_ID_DEFAULT, MMI_EVENT_WARNING, &VappMusicPlayerNCellCallback, this);
m_popup_id = vcp_global_popup_show_confirm_two_button_id(
GRP_ID_ROOT,
VCP_POPUP_TYPE_WARNING,
STR_ID_VAPP_MUSIC_PLAYER_POPUP_CLOSE_HINT,
STR_GLOBAL_OK,
STR_GLOBAL_CANCEL,
VCP_POPUP_BUTTON_TYPE_WARNING,
VCP_POPUP_BUTTON_TYPE_CANCEL,
&VappNcenterMusicPlayerInfoPanel::onConfirmButtonClick,
(void*)this);
}
VfxS32 VappNcenterMusicPlayerInfoPanel::getPopupID()
{
return m_popup_id;
}
void VappNcenterMusicPlayerInfoPanel::updatePanel()
{
if(isValidState())
{
srv_plst_media_details_struct detail_info;
//VFX_ALLOC_MEM(detail_info, sizeof(srv_plst_media_details_struct), this);
if(m_mplayerSrv->getCurrDetailInfo(&detail_info))
{
m_textTitle->setString(VFX_WSTR_MEM(detail_info.title));
}
else
{
m_textTitle->setString(STR_ID_VAPP_MUSIC_PLAYER_PLAYLIST_NO_SONG);
}
//VFX_FREE_MEM(detail_info);
}
else
{
m_textTitle->setString(STR_ID_VAPP_MUSIC_PLAYER_PLAYLIST_NO_SONG);
}
updateButton();
}
void VappNcenterMusicPlayerInfoPanel::onConfirmButtonClick(VfxId id, void *userData)
{
VappNcenterMusicPlayerInfoPanel *cell =(VappNcenterMusicPlayerInfoPanel*)userData;
if (id == VCP_CONFIRM_POPUP_BUTTON_USER_1)
{
// close APP
VappMusicPlayerApp *app = getMusicPlayerApp();
if (app)
{
app->goToRoot();
}
VappMusicPlayerService *srv = getMusicPlayerSrv();
if (srv)
{
srv->closeMusicPlayer();
}
}
else if (id == VCP_CONFIRM_POPUP_BUTTON_USER_2)
{
vcp_global_popup_cancel(cell->getPopupID());
}
}
void VappNcenterMusicPlayerInfoPanel::updateButton(void)
{
VcpStateImage imgListPlayBtn;
VfxBool in_call = VFX_FALSE;
if(srv_ucm_query_call_count(SRV_UCM_CALL_STATE_ALL, SRV_UCM_CALL_TYPE_NO_CSD, NULL) > 0)
{
in_call = VFX_TRUE;
}
if(in_call || (m_ctrlPlayback == NULL) || !isValidState())
{
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0);
m_play_btn->setIsDisabled(VFX_TRUE);
m_prev_btn->setIsDisabled(VFX_TRUE);
m_next_btn->setIsDisabled(VFX_TRUE);
}
else
{
VfxBool isPlayImage = VFX_TRUE;
if (m_ctrlPlayback)
{
isPlayImage = m_ctrlPlayback->getPlayPauseState();
}
if(isPlayImage)
{
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0);
}
else
{
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PAUSE_NC, IMG_ID_VAPP_MUSICPLY_BTN_PAUSE_NC, 0, 0);
}
// Check if need to disable play icon
// Playback fail or interrupted in playback fail state, do not enable UI
InterruptStruct interrupt = m_ctrlPlayback->getInterruptedInfo();
PlaybackStateEnum state = m_ctrlPlayback->getPlayState();
if (( state == PB_STATE_PLAYBACK_FAIL) || (interrupt.isInterrupted && (interrupt.state == PB_STATE_PLAYBACK_FAIL)))
{
m_play_btn->setIsDisabled(VFX_TRUE);
}
else
{
m_play_btn->setIsDisabled(VFX_FALSE);
}
// Set button unhittable when switching play
if (state == PB_STATE_SWITCHING_PLAY || state == PB_STATE_SWITCHING_NOT_PLAY || state == PB_STATE_SEEKING)
{
// Make button up when change song
m_play_btn->setState(VCP_BUTTON_STATE_NORMAL);
m_play_btn->setIsUnhittable(VFX_TRUE);
m_prev_btn->setState(VCP_BUTTON_STATE_NORMAL);
m_prev_btn->setIsUnhittable(VFX_TRUE);
m_next_btn->setState(VCP_BUTTON_STATE_NORMAL);
m_next_btn->setIsUnhittable(VFX_TRUE);
}
else
{
m_play_btn->setIsUnhittable(VFX_FALSE);
m_prev_btn->setIsUnhittable(VFX_FALSE);
m_next_btn->setIsUnhittable(VFX_FALSE);
}
m_prev_btn->setIsDisabled(VFX_FALSE);
m_next_btn->setIsDisabled(VFX_FALSE);
}
m_play_btn->setImage(imgListPlayBtn);
}
mmi_ret VappNcenterMusicPlayerInfoPanel::staticEventHandler(mmi_event_struct *evt)
{
switch(evt->evt_id)
{
case EVT_ID_SRV_UCM_STATUS_CHANGE:
{
VappNcenterMusicPlayerInfoPanel* ncenter = (VappNcenterMusicPlayerInfoPanel*) evt->user_data;
if(ncenter->m_play_btn)
{
VcpStateImage imgListPlayBtn;
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0);
ncenter->m_play_btn->setImage(imgListPlayBtn);
if(srv_ucm_query_call_count(SRV_UCM_CALL_STATE_ALL, SRV_UCM_CALL_TYPE_NO_CSD, NULL) > 0)
{
ncenter->m_play_btn->setIsDisabled(VFX_TRUE);
ncenter->m_prev_btn->setIsDisabled(VFX_TRUE);
ncenter->m_next_btn->setIsDisabled(VFX_TRUE);
}
else
{
if(ncenter->isValidState())
{
ncenter->m_play_btn->setIsDisabled(VFX_FALSE);
ncenter->m_prev_btn->setIsDisabled(VFX_FALSE);
ncenter->m_next_btn->setIsDisabled(VFX_FALSE);
}
}
}
break;
}
default:
break;
}
return MMI_RET_OK;
}
/*****************************************************************************
* Music Player NCenter BaseCell Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappMusicPlayerNcenterCustomerCell",VappMusicPlayerNcenterCustomerCell, VsrvNCell);
void VappMusicPlayerNcenterCustomerCell::onCreateView(void *viewData,VfxU32 viewDataSize)
{
VsrvNCell::onCreateView(viewData, viewDataSize);
this->setSize(VAPP_NCENTER_ONGOING_CELL_WIDTH, NCENTER_H);
VFX_OBJ_CREATE(m_playback_panel, VappNcenterMusicPlayerInfoPanel, this);
}
void VappMusicPlayerNcenterCustomerCell::onCloseView()
{
m_playback_panel->destroyUI();
VFX_OBJ_CLOSE(m_playback_panel);
VsrvNCell::onCloseView();
}
#endif//__MMI_NCENTER_SUPPORT
#endif //__COSMOS_MUSICPLY__
| [
"3447782@qq.com"
] | 3447782@qq.com |
3db517066a1a2416324e8d3150c4f15e966385b0 | 7bd42fe780d5da06e52799fae4983fbd2606475b | /OOS_HA2/Aufg.1/Labyrinth.cpp | 020fde50cd625d95e064c330cd628897fbd8a1c9 | [] | no_license | encoit01/Cpp | 3f699d4e6a411392f7fa1474f2baec77bf6e78b3 | b8f63dc83e7148bd65201fffae35651c3ac1386e | refs/heads/main | 2023-04-18T22:41:40.600556 | 2021-05-08T13:44:39 | 2021-05-08T13:44:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,275 | cpp |
#include "Labyrinth.hpp"
#include <iostream>
using namespace std;
void Labyrinth::initialisieren()
{
for (int i = 0; i < kZeilen; i++) {
for (int j = 0; j < kSpalten; j++) {
labyrinth[i][j] = MAUER;
}
}
for (int i = 0; i < kZeilen; i++) {
labyrinth[i][kSpalten] = NL;
}
for (int i = 0; i < kSpalten; i++) {
labyrinth[i][kSpalten + 1] = EOS;
}
}
void Labyrinth::drucken()
{
system("cls");
for (int i = 0; i < kZeilen;i++) {
for (int j = 0; j < kSpalten + 1; j++) {
cout << labyrinth[i][j];
}
}
Labyrinth::legeMuenzen();
}
void Labyrinth::erzeugen()
{
char c = 'x';
int posx = kSpalten / 2;
int posy = kZeilen / 2;
labyrinth[posy][posx] = ICH;
drucken();
while (c != 'q') {
drucken();
cout << "Laufen mit Pfeiltasten. Beenden mit q." << endl;
labyrinth[posy][posx] = WEG;
c = _getch();
switch (int(c)) {
// oben
case 72: posy = max(1, posy - 1); break;
// links
case 75: posx = max(1, posx - 1); break;
// rechts
case 77: posx = min(kSpalten - 2, posx + 1); break;
// unten
case 80: posy = min(kZeilen - 2, posy + 1); break;
// q = quit
case 113: break;
}
labyrinth[posy][posx] = ICH;
}
}
Labyrinth::Labyrinth()
{
labSpalten = kSpalten;
labZeilen = kZeilen;
labAnzGeister = kAnzGeister;
muenzen = 0;
initialisieren();
}
int Labyrinth::getZeilen()
{
return labZeilen;
}
int Labyrinth::getSpalten()
{
return labSpalten;
}
int Labyrinth::getAnzGeister()
{
return labAnzGeister;
}
int Labyrinth::getMuenzen()
{
return muenzen;
}
void Labyrinth::legeMuenzen()
{
for (int i = 0; i < kZeilen; i++) {
for (int j = 0; j < kSpalten; j++) {
if (labyrinth[i][j] == WEG)
{
labyrinth[i][j] = MUENZE;
muenzen++;
}
}
}
}
void Labyrinth::zeichneChar(char c, Position pos)
{
labyrinth[pos.posx][pos.posy] = c;
}
void Labyrinth::zeichneChar(char c, Position posalt, Position posneu)
{
zeichneChar(c, posneu);
labyrinth[posalt.posx][posalt.posy] = WEG;
}
char Labyrinth::getZeichenAnPos(Position pos)
{
char erg = labyrinth[pos.posx][pos.posy];
return erg;
}
bool Labyrinth::istMuenzeAnPos(Position pos)
{
if (labyrinth[pos.posx][pos.posy] == MUENZE)
{
return true;
}
else
{
return false;
}
} | [
"encoit01@hs-esslingen.de"
] | encoit01@hs-esslingen.de |
7430fb9858dfabc056d089e86b467b5e1eb5d934 | 53da158ef8f73d422fde06c5a711b81b40e5ef0b | /ModuleTextures.cpp | 493a3ff95294dcdaa391bbb0615af5894ddd2518 | [] | no_license | lluissr/Graphics | 843fa4779bd071088f5ed8ddaa19384e43fa13ce | 48c6f762a3cc53643331c1a020e1ab95963b4d54 | refs/heads/master | 2020-04-01T11:30:37.186561 | 2018-10-15T19:25:59 | 2018-10-15T19:25:59 | 153,165,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,582 | cpp | #include "Globals.h"
#include "Application.h"
#include "ModuleRender.h"
#include "ModuleTextures.h"
#include "SDL/include/SDL.h"
#include "SDL_image/include/SDL_image.h"
#pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" )
using namespace std;
ModuleTextures::ModuleTextures()
{
}
// Destructor
ModuleTextures::~ModuleTextures()
{
IMG_Quit();
}
// Called before render is available
bool ModuleTextures::Init()
{
LOG("Init Image library");
bool ret = true;
// load support for the PNG image format
int flags = IMG_INIT_PNG;
int init = IMG_Init(flags);
if((init & flags) != flags)
{
LOG("Could not initialize Image lib. IMG_Init: %s", IMG_GetError());
ret = false;
}
return ret;
}
bool ModuleTextures::Start()
{
return true;
}
// Called before quitting
bool ModuleTextures::CleanUp()
{
LOG("Freeing textures and Image library");
for(list<SDL_Texture*>::iterator it = textures.begin(); it != textures.end(); ++it)
SDL_DestroyTexture(*it);
textures.clear();
return true;
}
// Load new texture from file path
SDL_Texture* const ModuleTextures::Load(const char* path)
{
SDL_Texture* texture = NULL;
SDL_Surface* surface = IMG_Load(path);
if(surface == NULL)
{
LOG("Could not load surface with path: %s. IMG_Load: %s", path, IMG_GetError());
}
else
{
texture = SDL_CreateTextureFromSurface(App->renderer->renderer, surface);
if(texture == NULL)
{
LOG("Unable to create texture from surface! SDL Error: %s\n", SDL_GetError());
}
else
{
textures.push_back(texture);
}
SDL_FreeSurface(surface);
}
return texture;
}
| [
"lluissr@gmail.com"
] | lluissr@gmail.com |
e86c7181b12fb9c4309776318dbca661480d4c7a | a00f687b64637c80e88166ee4b0f957ef705b9c1 | /src/qt/askpassphrasedialog.cpp | 9621f60e783699dc9c4153c137851f1ec43828c7 | [
"MIT"
] | permissive | xenixcoin/xenixcoin | 9e7b95f48968c16ea9f135fdf865557a8e4ceb71 | 99d9eda1489d6e43a3c00225165506c61e480b20 | refs/heads/master | 2020-07-01T21:45:09.865765 | 2017-02-01T04:07:39 | 2017-02-01T04:07:39 | 74,255,598 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,001 | cpp | #include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("xenixcoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"xenixcoin@mail.com"
] | xenixcoin@mail.com |
fe883928796c1fd961e88a56d7ef30a692af7dcb | e3adfda1a3873b2eeec04eed34a9e0cf007760a7 | /CRM-system/CRM-system_client/include/CRM-system_client.h | 8d0cf12e5b5c5befeb0a5cef43f159802239cfd1 | [
"MIT"
] | permissive | polupanovaanna/CRM-system | 0ebc9a6eae68f6c1a994396bf929dd94144fee41 | d08e7b37e24ec514a45ea664d4ad775bed085480 | refs/heads/master | 2023-05-04T14:39:41.506201 | 2021-05-28T20:40:34 | 2021-05-28T20:40:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,413 | h | #ifndef CRM_SYSTEM_STORAGEDATABASE_H
#define CRM_SYSTEM_STORAGEDATABASE_H
#include <iostream>
#include <memory>
#include <string>
#include <cstdio>
#include <vector>
#include "people.h"
#include <grpc++/grpc++.h>
#include "CRM-system.grpc.pb.h"
#include <stdexcept>
#include "storage.h"
namespace repositories {
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using namespace crm_system;
struct DataExistsException : StorageException{
explicit DataExistsException(const std::string& arg);
};
struct DataNotExistsException : StorageException{
explicit DataNotExistsException(const std::string& arg);
};
struct ManagerException : std::runtime_error{
explicit ManagerException(const std::string& arg);
};
struct ClientException : std::runtime_error{
explicit ClientException(const std::string& arg);
};
struct ManagerDataBase_client : ManagerRepository {
private:
std::unique_ptr<CRMService::Stub> stub_;
public:
ManagerDataBase_client();
// ManagerDataBase_client(std::shared_ptr<Channel> channel);
void addManager(const people::Manager &manager) const override;
void getManager(people::Manager &inputManager, const std::string &inputEmail) const override;
[[nodiscard]] bool isCorrectPassword(const std::string &inputEmail, const std::string &inputPassword) const override;
std::string managerInfo(people::Manager &manager) const override;
~ManagerDataBase_client() override = default;
};
struct ClientDataBase_client : ClientRepository {
private:
std::unique_ptr<CRMService::Stub> stub_;
public:
ClientDataBase_client();
// ClientDataBase_client(std::shared_ptr<Channel> channel);
void addClient(const people::Client &client, const std::string &managerEmail) const override;
void deleteClient(const std::string &clientEmail, const std::string &managerEmail) const override;
void updateAllClients(people::Manager &manager) const override;
[[nodiscard]] std::string clientInfo(const people::Client &client) const override;
[[nodiscard]] std::vector<std::string> getDealProcess(const people::Client &client) const override;
~ClientDataBase_client() override = default;
};
} // namespace repositories
#endif //CRM_SYSTEM_STORAGEDATABASE_H
| [
"ddemon2002@mail.ru"
] | ddemon2002@mail.ru |
78c99dff372d89ccd5e36d8a9f82b99c6d7358d5 | 9de18ef120a8ae68483b866c1d4c7b9c2fbef46e | /third_party/concurrentqueue/benchmarks/boost/type_traits/is_rvalue_reference.hpp | 93cd0bf187047d4930ad02d98a1724c349761a0d | [
"BSL-1.0",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown",
"Zlib"
] | permissive | google/orbit | 02a5b4556cd2f979f377b87c24dd2b0a90dff1e2 | 68c4ae85a6fe7b91047d020259234f7e4961361c | refs/heads/main | 2023-09-03T13:14:49.830576 | 2023-08-25T06:28:36 | 2023-08-25T06:28:36 | 104,358,587 | 2,680 | 325 | BSD-2-Clause | 2023-08-25T06:28:37 | 2017-09-21T14:28:35 | C++ | UTF-8 | C++ | false | false | 882 | hpp |
// (C) John Maddock 2010.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_IS_RVALUE_REFERENCE_HPP_INCLUDED
#define BOOST_TT_IS_RVALUE_REFERENCE_HPP_INCLUDED
#include <boost/type_traits/config.hpp>
// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>
namespace boost {
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_rvalue_reference,T,false)
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC1_1(typename T,is_rvalue_reference,T&&,true)
#endif
} // namespace boost
#include <boost/type_traits/detail/bool_trait_undef.hpp>
#endif // BOOST_TT_IS_REFERENCE_HPP_INCLUDED
| [
"pierric.gimmig@gmail.com"
] | pierric.gimmig@gmail.com |
6427094ae25268a18c99a84737d009687fb23a4c | 108c8fa38da3371571068f353888f20d8fd729c0 | /voxel-cutting/Transformer_Cutting/OpenGLView/processHoleMesh.h | 05e83c2acf3a3de3e0fe28224e3f68c36663d78f | [] | no_license | pigoblock/TFYP | 2dd0acf1bb5591fb31b2d78a1bed764cd4a7d166 | 11ba29fd0d75a6b92080fd80b24064898b8f980f | refs/heads/master | 2021-01-17T10:07:10.149542 | 2016-04-19T07:41:53 | 2016-04-19T07:41:53 | 41,845,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | h | #pragma once
#include "Graphics\Surfaceobj.h"
class processHoleMesh
{
public:
processHoleMesh();
~processHoleMesh();
void processMeshSTL(char* path);
SurfaceObj * getBiggestWaterTightPart();
void drawSeparatePart() const;
private:
SurfaceObjPtr originalSurface;
std::vector<arrayInt> independentObj;
std::vector<bool> isWaterTightArray;
};
typedef std::shared_ptr<processHoleMesh> processHoleMeshPtr; | [
"kowanling@hotmail.com"
] | kowanling@hotmail.com |
d1f54a7b90e1f26ee95b9cb428eb77f382c2d04b | dffec5fe339883a8b84be0122eef6a3c64a4fa07 | /src/ctrl/colorpicker.h | 6df1264df4cce43af021633f8b9d3cceae8c8cdf | [] | no_license | ongbe/Memmon | 0e346b161c9b6538f6135eb87a60c14648de7e27 | 6bfbc6158a9b6d0d39ff4795a47501071855454f | refs/heads/master | 2021-01-18T14:29:45.299538 | 2013-02-17T14:51:01 | 2013-02-17T14:51:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | #ifndef COLORPICKER_H
#define COLORPICKER_H
#include <QObject>
#include <QColor>
#include <QTime>
#define COLORPICKER_INCREMENT 5
#define COLORPICKER_INIT_INDEX 10
class ColorPicker
{
public:
ColorPicker();
QColor GetColor();
void Reset();
int m_nIndex;
QList<QColor> m_clrList;
void SetStartIndex(int index);
};
#endif // COLORPICKER_H
| [
"kimtaikee@gmail.com"
] | kimtaikee@gmail.com |
712ce1ac0b05b218e7ea51a70df3d8ae87a087f7 | 3c6331c46dbf3537ef9a1d382f2121bd98299abb | /ReferenceSwap/ReferenceSwap/ReferenceSwap.cpp | daace0b11da1d256f23e70fe3e99710510a6da0a | [] | no_license | awbwd4/jaekk | 179b1e98b89561a4cd1fd55dd688bee9eb914254 | ddd65f717bdea093e6625a99672a59fb7a29ada2 | refs/heads/master | 2021-10-09T15:11:39.278530 | 2018-12-30T07:03:18 | 2018-12-30T07:03:18 | 112,326,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | cpp | // ReferenceSwap.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include "pch.h"
#include <iostream>
using namespace std;
//참조 전달이므로 호출자 변수의 값을 변경할 수 있다.
void Swap(int &a, int &b) {
int nTmp = a;
a = b;
b = nTmp;
}
int main()
{
int x = 10, y = 20;
Swap(x, y);
cout << "x : " << x << endl;
cout << "y : " << y << endl;
return 0;
//포인터는 앵간하면 사용하지 말자!!!
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| [
"awbwd4@gmail.com"
] | awbwd4@gmail.com |
a6d833e83b9e83fb852dd8fa42629044deb22a43 | 75c587b8ff471dcf12500fe80895a579c402bf9a | /test/QTestableAutomationRequestTest.cpp | 66740a114cfcd30b482d09b143304664e66cac1b | [] | no_license | gja/qTestable | ebaf7e9769b637a5add5ad86db5193e32ec2b67b | b545a78657634922a23271200edb9d663464ae8d | refs/heads/master | 2021-01-13T01:49:05.923575 | 2011-03-20T05:49:38 | 2011-03-20T05:49:38 | 1,386,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,925 | cpp | #include <QTest>
#include "QTestableAutomationRequest.h"
using namespace QTestable;
class QTestableAutomationRequestTest : public QObject
{
Q_OBJECT
private slots:
void ShouldBeAbleToParseARequestWithoutArguments_data()
{
QTest::addColumn<QString>("request");
QTest::addColumn<bool>("isValid");
QTest::addColumn<QString>("targetClass");
QTest::addColumn<QString>("targetObject");
QTest::addColumn<QString>("command");
QTest::newRow("An Empty Request")<<""<<false<<""<<""<<"";
QTest::newRow("An Request Without Arguments")<<"button/click/myButton"<<true<<"button"<<"myButton"<<"click";
QTest::newRow("An Request Child In The Target")<<"button/click/myButton/child"<<true<<"button"<<"myButton/child"<<"click";
QTest::newRow("An Request With Arguments To be ignored")<<"button/click/myButton?foo=bar"<<true<<"button"<<"myButton"<<"click";
}
void ShouldBeAbleToParseARequestWithoutArguments()
{
QFETCH(QString, request);
QFETCH(bool, isValid);
QFETCH(QString, targetClass);
QFETCH(QString, targetObject);
QFETCH(QString, command);
QTestableAutomationRequest parser(request);
QCOMPARE(isValid, parser.isValid());
QCOMPARE(targetClass, parser.targetClass());
QCOMPARE(targetObject, parser.targetObject());
QCOMPARE(command, parser.command());
QCOMPARE(request, parser.originalRequest());
QCOMPARE(isValid ? QString("") : QString("Invalid Request"), parser.errorMessage());
}
void ShouldBeAbleToParseARequestWithArguments()
{
QTestableAutomationRequest request("foo/bar/baz?q1=a1&q2=a2");
QCOMPARE(request.argument("q1"), QString("a1"));
QCOMPARE(request.argument("q2"), QString("a2"));
QCOMPARE(request.argument("invalid"), QString(""));
}
};
QTEST_MAIN(QTestableAutomationRequestTest)
#include "QTestableAutomationRequestTest.moc"
| [
"tejas@gja.in"
] | tejas@gja.in |
257e9409fcbf13082f3e0367bed0cd614d57a42e | 5997e1375927f887e4fc1e5b06cc16edc069a395 | /hdf5_wrapper/template/src/write_attribute.inc | 64e15e306ea9dff3a8877b2f17a0d2d54d0031b8 | [
"MIT"
] | permissive | galtay/urchin | 1f37d42c1cfdf7902942b04efbaff114a2c43538 | fc111c16065f58141bc9d9b2629ee058c41df2db | refs/heads/main | 2022-12-05T10:40:46.246680 | 2020-09-04T21:19:33 | 2020-09-04T21:19:33 | 292,947,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,883 | inc | subroutine SUB_NAME (ifile,name,arr,overwrite)
!
! Read an n-D array dataset from an open file. This assumes some
! preprocessor variables have been set - see
! write_attribute_preprocessor.F90.
!
implicit none
integer, parameter :: LEN_STR = 256
integer, parameter :: MAX_NEST = 10
character(len=*), intent(in) :: name
integer,intent(in) :: ifile
integer :: hdf_err
integer(hid_t) :: loc_id, attr_id, dspace_id
integer(hid_t) :: dtype_id
#ifndef SCALAR
integer(hsize_t) :: dimensions(NDIMS)
ARR_TYPE , dimension ARRAY_DIM :: arr
#else
ARR_TYPE :: arr
#endif
character(len=LEN_STR) :: loc_name
character(len=LEN_STR) :: attr_name
integer :: nslash
integer :: itype,i
logical, optional :: overwrite
!
if(ifile.lt.1.or.ifile.gt.nfilemax)call hdf5_abort( &
'Invalid file handle in write_attribute',name=name)
if(file_id(ifile).lt.0) then
call hdf5_abort('File is not open in hdf5_write_attribute()!',&
name=name)
endif
!
if(read_only(ifile))call hdf5_abort( &
"Attempt to write attribute to read only file!", &
name=name,fname=fname_table(ifile))
! Generate array of dimensions:
#ifndef SCALAR
do i=1,NDIMS
dimensions(i) = ubound(arr,i) - lbound(arr,i) + 1
enddo
#endif
! Split name into path and attribute name
nslash=index(name,"/",.true.)
if(nslash.eq.0) then
call hdf5_abort('Invalid attribute name in write_attribute!', &
name=name,fname=fname_table(ifile))
endif
loc_name=name(1:nslash-1)
attr_name=name(nslash+1:len_trim(name))
! Try to open loc_name as a group and as a dataset
itype=1
call h5eset_auto_f(0, hdf_err)
call h5dopen_f(file_id(ifile),loc_name,loc_id,hdf_err)
if(hdf_err.lt.0)then
call h5gopen_f(file_id(ifile),loc_name, loc_id, hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to open attribute parent object in write_attribute!', &
name=name,fname=fname_table(ifile))
endif
itype=2
end if
if (HDF_ERROR_SUPPRESS .eq. 0) call h5eset_auto_f(1, hdf_err)
! Now we can write the data:
#ifndef SCALAR
call h5screate_simple_f(NDIMS,dimensions,dspace_id,hdf_err)
#else
call h5screate_f(H5S_SCALAR_F, dspace_id, hdf_err)
#endif
if(hdf_err.lt.0)call hdf5_abort('Unable to open dataspace in write_data()!', &
name=name,fname=fname_table(ifile))
#ifndef STRING
call h5tcopy_f( NATIVE_TYPE, dtype_id, hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to open datatype in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
#else
call h5tcopy_f( H5T_NATIVE_CHARACTER, dtype_id, hdf_err)
call h5tset_size_f(dtype_id, INT(LEN(arr),KIND=SIZE_T), hdf_err)
#endif
! If overwrite is set, delete any attribute at this location
if(present(overwrite))then
if(overwrite)then
call h5eset_auto_f(0, hdf_err)
call h5adelete_f(loc_id,attr_name,hdf_err)
if (HDF_ERROR_SUPPRESS .eq. 0) call h5eset_auto_f(1, hdf_err)
endif
endif
call h5acreate_f(loc_id, attr_name, dtype_id, dspace_id, &
attr_id, hdf_err, H5P_DEFAULT_F)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to open attribute in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
!Here we call the C version of the routine
CALL write_hdf5_attribute(attr_id, dtype_id, arr,hdf_err)
if (HDF_VERBOSITY .ge. 1) then
write(*,*)'[hdf5_write_attribute] Writing attribute ',trim(attr_name)
endif
if(hdf_err.lt.0) then
call hdf5_abort('Unable to write attribute in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
if(itype.eq.1)then
call h5dclose_f(loc_id,hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to close dataset in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
else
call h5gclose_f(loc_id,hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to close group in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
end if
call h5tclose_f(dtype_id,hdf_err)
call h5sclose_f(dspace_id,hdf_err)
call h5aclose_f(attr_id, hdf_err)
end subroutine SUB_NAME
| [
"gabriel@kensho.com"
] | gabriel@kensho.com |
cca95cc4f2ab243cde8f0712ed0cdecf4720df05 | fec25167d6f425342cd26be40050131bfff34b49 | /shared/hamming.cpp | 235629d4436938206ee2b5554221f47744412e9e | [
"Unlicense"
] | permissive | DeNiCoN/TIK | 65accae707cfb847583719e496cb7857c2983d9d | 3f622e1a18cc217ff702020f065587e3d10ad1e3 | refs/heads/main | 2023-04-21T22:54:03.399766 | 2021-05-19T08:10:37 | 2021-05-19T08:10:37 | 357,243,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,433 | cpp | #include "hamming.hpp"
#include <bitset>
#include <fstream>
#include "bit_getter.hpp"
#include "bit_writer.hpp"
namespace tik
{
namespace hamming
{
enum class Type
{
NORMAL,
EXTENDED
};
void encode(const std::filesystem::path& from,
const std::filesystem::path& to)
{
std::ifstream input(from, std::ios::binary);
std::ofstream output(to, std::ios::binary);
output.put(char(Type::EXTENDED));
utils::BitGetter bit_getter(input);
while (bit_getter)
{
std::bitset<4> code;
std::bitset<16> out;
for (unsigned i = 0; i < 11; ++i)
{
if (bit_getter.get())
{
unsigned mapped;
if (i == 0)
mapped = 3;
else if (i < 4)
mapped = i + 4;
else
mapped = i + 5;
out[mapped] = true;
code ^= mapped;
}
}
out[1] = code[0];
out[2] = code[1];
out[4] = code[2];
out[8] = code[3];
out[0] = out.count() % 2;
uint16_t o = out.to_ulong();
output.write(reinterpret_cast<const char*>(&o), sizeof(o));
}
}
void encode_not_extended(const std::filesystem::path& from,
const std::filesystem::path& to)
{
std::ifstream input(from, std::ios::binary);
std::ofstream output(to, std::ios::binary);
output.put(char(Type::NORMAL));
utils::BitGetter bit_getter(input);
while (bit_getter)
{
std::bitset<4> code;
std::bitset<16> out;
for (unsigned i = 0; i < 11; ++i)
{
if (bit_getter.get())
{
unsigned mapped;
if (i == 0)
mapped = 3;
else if (i < 4)
mapped = i + 4;
else
mapped = i + 5;
out[mapped] = true;
code ^= mapped;
}
}
out[1] = code[0];
out[2] = code[1];
out[4] = code[2];
out[8] = code[3];
uint16_t o = out.to_ulong();
output.write(reinterpret_cast<const char*>(&o), sizeof(o));
}
}
void decode(const std::filesystem::path& from,
const std::filesystem::path& to)
{
std::ifstream input(from, std::ios::binary);
std::ofstream output(to, std::ios::binary);
utils::BitWriter bit_writer(output);
bit_writer.discard_last() = true;
unsigned char type_char = input.get();
if (type_char > 2)
{
std::cerr << "Unknown type" << std::endl;
throw std::exception();
}
Type type = static_cast<Type>(type_char);
uint16_t current;
while(input.read(reinterpret_cast<char*>(¤t), sizeof(current)))
{
std::bitset<sizeof(current) * 8> current_set = current;
std::size_t flip = 0;
for (std::size_t i = 0; i < current_set.size(); ++i)
{
if (current_set[i])
flip ^= i;
}
if (type == Type::NORMAL)
{
current_set.flip(flip);
}
else if(type == Type::EXTENDED)
{
if (current_set.count() % 2)
{
//single error
current_set.flip(flip);
}
else
{
if (flip)
{
//double
std::cerr << "double error" << std::endl;
}
}
}
std::bitset<11> result;
result[0] = current_set[3];
result[1] = current_set[5];
result[2] = current_set[6];
result[3] = current_set[7];
result[4] = current_set[9];
result[5] = current_set[10];
result[6] = current_set[11];
result[7] = current_set[12];
result[8] = current_set[13];
result[9] = current_set[14];
result[10] = current_set[15];
bit_writer.write(result);
}
}
void check(const std::filesystem::path& input_file, std::ostream& log_stream)
{
std::ifstream input(input_file, std::ios::binary);
unsigned char type_char = input.get();
if (type_char > 2)
{
log_stream << "Wrong header\n";
return;
}
Type type = static_cast<Type>(type_char);
if (type == Type::NORMAL)
{
log_stream << "Hamming(15, 11)\n";
}
else
{
log_stream << "Hamming(16, 11)\n";
}
uint16_t current;
std::size_t cur_code_index = 0;
while(input.read(reinterpret_cast<char*>(¤t), sizeof(current)))
{
std::bitset<sizeof(current) * 8> current_set = current;
std::size_t flip = 0;
for (std::size_t i = 0; i < current_set.size(); ++i)
{
if (current_set[i])
flip ^= i;
}
if (type == Type::NORMAL)
{
if (flip)
{
log_stream << "Single error at codeword " << cur_code_index + 1
<< " bit " << flip << " (" << cur_code_index * 16 + flip
<< ")\n";
}
}
else if(type == Type::EXTENDED)
{
if (current_set.count() % 2)
{
//single error
if (flip)
{
log_stream << "Single error at codeword " << cur_code_index + 1
<< " bit " << flip << " (" << cur_code_index * 16 + flip
<< ")\n";
}
}
else
{
if (flip)
{
log_stream << "Double error at codeword " << cur_code_index + 1
<< "\n";
}
}
}
cur_code_index++;
}
}
}
}
| [
"denicon1234@gmail.com"
] | denicon1234@gmail.com |
226017edc0e5b4ff31b7768be38abdba9d537036 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-17222.cpp | 92849642b5b422ab961b14e59f26c544761781b1 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,402 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1 : virtual c0
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
c0 *p0_0 = (c0*)(c1*)(this);
tester0(p0_0);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
if (p->active0)
p->f0();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c0, virtual c1
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c2*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c2*)(this);
tester1(p1_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : c2, virtual c0
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c2*)(c3*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c2*)(c3*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c3*)(this);
tester0(p0_2);
c1 *p1_0 = (c1*)(c2*)(c3*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active2)
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c2
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c1*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c2*)(c4*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c1*)(c2*)(c4*)(this);
tester0(p0_2);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c2*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c1*)(new c1());
ptrs0[2] = (c0*)(c2*)(new c2());
ptrs0[3] = (c0*)(c1*)(c2*)(new c2());
ptrs0[4] = (c0*)(c2*)(c3*)(new c3());
ptrs0[5] = (c0*)(c1*)(c2*)(c3*)(new c3());
ptrs0[6] = (c0*)(c3*)(new c3());
ptrs0[7] = (c0*)(c1*)(c4*)(new c4());
ptrs0[8] = (c0*)(c2*)(c4*)(new c4());
ptrs0[9] = (c0*)(c1*)(c2*)(c4*)(new c4());
for (int i=0;i<10;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c2*)(new c2());
ptrs1[2] = (c1*)(c2*)(c3*)(new c3());
ptrs1[3] = (c1*)(c4*)(new c4());
ptrs1[4] = (c1*)(c2*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
7ece2a2d0cec39b419ef176054d383f24a2df42a | 3538f87f9f3c2797455902ed229c0d747a890850 | /src/HTTP/UrlClient.h | 5f737b057ff4ebca2ceed5329b4099bb2aa40b12 | [
"Apache-2.0"
] | permissive | cflep/cuberite | fb2103460067fbf6949858880f7fabde8cd80e2e | 6bbbc52d0201493a9bf4c1f5b1d05dd76240c4bf | refs/heads/master | 2023-08-10T18:10:16.132234 | 2021-09-23T20:49:34 | 2021-09-23T20:49:34 | 317,042,628 | 1 | 0 | NOASSERTION | 2021-02-11T12:36:46 | 2020-11-29T21:03:50 | C++ | UTF-8 | C++ | false | false | 6,180 | h |
// UrlClient.h
// Declares the cUrlClient class for high-level URL interaction
/*
Options that can be set via the Options parameter to the cUrlClient calls:
"MaxRedirects": The maximum number of allowed redirects before the client refuses a redirect with an error
"OwnCert": The client certificate to use, if requested by the server. Any string that can be parsed by cX509Cert.
"OwnPrivKey": The private key appropriate for OwnCert. Any string that can be parsed by cCryptoKey.
"OwnPrivKeyPassword": The password for OwnPrivKey. If not present or empty, no password is assumed.
Behavior:
- If a redirect is received, and redirection is allowed, the redirection is reported via OnRedirecting() callback
and the request is restarted at the redirect URL, without reporting any of the redirect's headers nor body
- If a redirect is received and redirection is not allowed (maximum redirection attempts have been reached),
the OnRedirecting() callback is called with the redirect URL and then the request terminates with an OnError() callback,
without reporting the redirect's headers nor body.
*/
#pragma once
#include "../OSSupport/Network.h"
class cUrlClient
{
public:
/** Callbacks that are used for progress and result reporting. */
class cCallbacks
{
public:
// Force a virtual destructor in descendants:
virtual ~cCallbacks() {}
/** Called when the TCP connection is established. */
virtual void OnConnected(cTCPLink & a_Link) {}
/** Called for TLS connections, when the server certificate is received.
Return true to continue with the request, false to abort.
The default implementation does nothing and continues with the request.
TODO: The certificate parameter needs a representation! */
virtual bool OnCertificateReceived() { return true; }
/** Called for TLS connections, when the TLS handshake has been completed.
An empty default implementation is provided so that clients don't need to reimplement it unless they are interested in the event. */
virtual void OnTlsHandshakeCompleted() { }
/** Called after the entire request has been sent to the remote peer. */
virtual void OnRequestSent() {}
/** Called after the first line of the response is parsed, unless the response is an allowed redirect. */
virtual void OnStatusLine(const AString & a_HttpVersion, int a_StatusCode, const AString & a_Rest) {}
/** Called when a single HTTP header is received and parsed, unless the response is an allowed redirect
Called once for each incoming header. */
virtual void OnHeader(const AString & a_Key, const AString & a_Value) {}
/** Called when the HTTP headers have been fully parsed, unless the response is an allowed redirect.
There will be no more OnHeader() calls. */
virtual void OnHeadersFinished() {}
/** Called when the next fragment of the response body is received, unless the response is an allowed redirect.
This can be called multiple times, as data arrives over the network. */
virtual void OnBodyData(const void * a_Data, size_t a_Size) {}
/** Called after the response body has been fully reported by OnBody() calls, unless the response is an allowed redirect.
There will be no more OnBody() calls. */
virtual void OnBodyFinished() {}
/** Called when an asynchronous error is encountered. */
virtual void OnError(const AString & a_ErrorMsg) {}
/** Called when a redirect is to be followed.
This is called even if the redirecting is prohibited by the options; in such an event, this call will be
followed by OnError().
If a response indicates a redirect (and the request allows redirecting), the regular callbacks
OnStatusLine(), OnHeader(), OnHeadersFinished(), OnBodyData() and OnBodyFinished() are not called
for such a response; instead, the redirect is silently attempted. */
virtual void OnRedirecting(const AString & a_NewLocation) {}
};
typedef std::unique_ptr<cCallbacks> cCallbacksPtr;
/** Used for HTTP status codes. */
enum eHTTPStatus
{
HTTP_STATUS_OK = 200,
HTTP_STATUS_MULTIPLE_CHOICES = 300, // MAY have a redirect using the "Location" header
HTTP_STATUS_MOVED_PERMANENTLY = 301, // redirect using the "Location" header
HTTP_STATUS_FOUND = 302, // redirect using the "Location" header
HTTP_STATUS_SEE_OTHER = 303, // redirect using the "Location" header
HTTP_STATUS_TEMPORARY_REDIRECT = 307, // redirect using the "Location" header
};
/** Makes a network request to the specified URL, using the specified method (if applicable).
The response is reported via the a_ResponseCallback callback, in a single call.
The metadata about the response (HTTP headers) are reported via a_InfoCallback before the a_ResponseCallback call.
If there is an asynchronous error, it is reported in via the a_ErrorCallback.
If there is an immediate error (misformatted URL etc.), the function returns false and an error message.
a_Headers contains additional headers to use for the request.
a_Body specifies optional body to include with the request, if applicable.
a_Options contains various options for the request that govern the request behavior, but aren't sent to the server,
such as the proxy server, whether to follow redirects, and client certificate for TLS. */
static std::pair<bool, AString> Request(
const AString & a_Method,
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap && a_Headers,
AString && a_Body,
AStringMap && a_Options
);
/** Alias for Request("GET", ...) */
static std::pair<bool, AString> Get(
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap a_Headers = AStringMap(),
const AString & a_Body = AString(),
AStringMap a_Options = AStringMap()
);
/** Alias for Request("POST", ...) */
static std::pair<bool, AString> Post(
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap && a_Headers,
AString && a_Body,
AStringMap && a_Options
);
/** Alias for Request("PUT", ...) */
static std::pair<bool, AString> Put(
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap && a_Headers,
AString && a_Body,
AStringMap && a_Options
);
};
| [
"github@xoft.cz"
] | github@xoft.cz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.