hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
97fcf84aeade82751ece864173c2ab4e874befb6
| 1,415
|
hpp
|
C++
|
include/synthizer/downsampler.hpp
|
wiresong/synthizer
|
d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420
|
[
"Unlicense"
] | 25
|
2020-09-05T18:21:21.000Z
|
2021-12-05T02:47:42.000Z
|
include/synthizer/downsampler.hpp
|
wiresong/synthizer
|
d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420
|
[
"Unlicense"
] | 77
|
2020-07-08T23:33:46.000Z
|
2022-03-19T05:34:26.000Z
|
include/synthizer/downsampler.hpp
|
wiresong/synthizer
|
d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420
|
[
"Unlicense"
] | 9
|
2020-07-08T18:16:53.000Z
|
2022-03-02T21:35:28.000Z
|
#pragma once
#include <algorithm>
#include <cstddef>
#include <type_traits>
#include "synthizer/filter_design.hpp"
#include "synthizer/iir_filter.hpp"
#include "synthizer/types.hpp"
namespace synthizer {
/*
* A downsampler. Requires that the size be a power of 2 for the time being.
*
* We use this for efficient delays, so that the delay lines themselves never have to deal with fractional values:
* we can filter once at the end of processing instead.
*
* For instance 44100 oversampled by a factor of 4 (for HRTF) gives delays of 2 microseconds,
*
* The tick method consumes AMOUNT frames from the input, and produces 1 frame in the output.
* */
template <std::size_t LANES, std::size_t AMOUNT, typename enabled = void> class Downsampler;
template <std::size_t LANES, std::size_t AMOUNT>
class Downsampler<LANES, AMOUNT, All<void, PowerOfTwo<AMOUNT>, std::enable_if_t<AMOUNT != 1>>> {
private:
IIRFilter<LANES, 81, 3> filter;
public:
Downsampler() {
// 0.6 is a rough approximation of a magic constant from WDL's resampler.
// We want to pull the filter down so that frequencies just above nyquist don't alias.
filter.setParameters(designSincLowpass<9>(1.0 / AMOUNT / 2));
}
void tick(float *in, float *out) {
float tmp[LANES];
filter.tick(in, out);
for (int i = 1; i < AMOUNT; i++) {
filter.tick(in + LANES * i, tmp);
}
}
};
} // namespace synthizer
| 30.106383
| 114
| 0.7053
|
wiresong
|
3f05727f9a934649f20584837066023f36e7ee0f
| 1,075
|
hpp
|
C++
|
src/Core/CCubeMap.hpp
|
Sebajuste/Omeglond3D
|
28a3910b47490ec837a29e40e132369f957aedc7
|
[
"MIT"
] | 1
|
2019-06-14T08:24:17.000Z
|
2019-06-14T08:24:17.000Z
|
src/Core/CCubeMap.hpp
|
Sebajuste/Omeglond3D
|
28a3910b47490ec837a29e40e132369f957aedc7
|
[
"MIT"
] | null | null | null |
src/Core/CCubeMap.hpp
|
Sebajuste/Omeglond3D
|
28a3910b47490ec837a29e40e132369f957aedc7
|
[
"MIT"
] | null | null | null |
#ifndef _DEF_OMEGLOND3D_CCUBEMAP_HPP
#define _DEF_OMEGLOND3D_CCUBEMAP_HPP
#include "ICubeMap.hpp"
namespace OMGL3D
{
namespace CORE
{
class CCubeMap : public ICubeMap
{
public:
CCubeMap(const std::string &name);
virtual ~CCubeMap();
unsigned int GetBpp() const;
unsigned int GetWidth() const;
unsigned int GetHeight() const;
void SetTexture(const CubeMapOrientation & orient, const std::string & picture_name) const;
virtual void SetTexture(const CubeMapOrientation &orient, const CPicture &picture) const=0;
virtual void Enable(unsigned int position=0, const TextureEnvironement &texEnv=OMGL_TEXENV_STANDART) const=0;
virtual void Disable(unsigned int position=0) const=0;
virtual void GenerateTexCoord(unsigned int position, const TexCoordPlane *planes, std::size_t size)=0;
private:
unsigned int _bpp, _width, _height;
};
}
}
#endif
| 25
| 122
| 0.623256
|
Sebajuste
|
3f134aa5421e484b68023bceb8870003b3d9790d
| 568
|
cpp
|
C++
|
references/zeoslib/packages/cbuilder6/ZTestPerformance.cpp
|
athiffau/alcinoe
|
4e59270f6a9258beed02676c698829e83e636b51
|
[
"Apache-2.0"
] | 851
|
2018-02-05T09:54:56.000Z
|
2022-03-24T23:13:10.000Z
|
references/zeoslib/packages/cbuilder6/ZTestPerformance.cpp
|
azrael11/alcinoe
|
98e92421321ef5df4be876f8d818dbfdfdca6757
|
[
"Apache-2.0"
] | 200
|
2018-02-06T18:52:39.000Z
|
2022-03-24T19:59:14.000Z
|
references/zeoslib/packages/cbuilder6/ZTestPerformance.cpp
|
azrael11/alcinoe
|
98e92421321ef5df4be876f8d818dbfdfdca6757
|
[
"Apache-2.0"
] | 197
|
2018-03-20T20:49:55.000Z
|
2022-03-21T17:38:14.000Z
|
//---------------------------------------------------------------------------
#include <vcl.h>
#include <TextTestRunner.hpp>
#include <ZPerformanceTestCase.hpp>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
Texttestrunner::RunRegisteredTests(rxbContinue);
PerformanceResultProcessor->ProcessResults();
PerformanceResultProcessor->PrintResults();
return 0;
}
//---------------------------------------------------------------------------
| 28.4
| 78
| 0.426056
|
athiffau
|
3f1ab60a81464b8c1978ae75ddbec6c47fb91e20
| 557
|
cpp
|
C++
|
exam2/passFunction.cpp
|
WeiChienHsu/CS165
|
65e95efc90415c8acc707e2d544eb384d3982e18
|
[
"MIT"
] | 1
|
2019-01-06T22:36:01.000Z
|
2019-01-06T22:36:01.000Z
|
exam2/passFunction.cpp
|
WeiChienHsu/CS165
|
65e95efc90415c8acc707e2d544eb384d3982e18
|
[
"MIT"
] | null | null | null |
exam2/passFunction.cpp
|
WeiChienHsu/CS165
|
65e95efc90415c8acc707e2d544eb384d3982e18
|
[
"MIT"
] | null | null | null |
#include <iostream>
int compare(int a, int b) {
if(a > b) return -1;
else return 1;
}
void bubbleSort(int *arr, int size, int (*compare)(int, int)) {
for(int i = 0; i < size; i++) {
for(int j = 0; j < size - 1; j++) {
if(compare(arr[j], arr[j+1]) > 0) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
const int SIZE = 5;
int arr[SIZE] = {1, 5, 3, 4, 2};
bubbleSort(arr, SIZE, compare);
for(int i = 0; i <SIZE; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
| 19.892857
| 63
| 0.490126
|
WeiChienHsu
|
3f1f01df324be4a85eb5e2553fc4dd56bb914c35
| 40,024
|
cpp
|
C++
|
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/KeyEvent.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 7
|
2017-07-13T10:34:54.000Z
|
2021-04-16T05:40:35.000Z
|
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/KeyEvent.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | null | null | null |
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/KeyEvent.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 9
|
2017-07-13T12:33:20.000Z
|
2021-06-19T02:46:48.000Z
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.Droid.Accounts.h"
#include "Elastos.Droid.App.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.Location.h"
#include "Elastos.Droid.Os.h"
#include "Elastos.Droid.Text.h"
#include "Elastos.Droid.Widget.h"
#include "elastos/droid/view/KeyEvent.h"
#include "elastos/droid/view/CKeyEvent.h"
#include "elastos/droid/view/KeyCharacterMap.h"
#include "elastos/droid/utility/CSparseInt32Array.h"
#include <input/Input.h>
#include <elastos/core/StringBuilder.h>
#include <elastos/utility/logging/Logger.h>
#include <elastos/core/StringUtils.h>
#include <elastos/core/AutoLock.h>
using Elastos::Core::AutoLock;
using Elastos::Droid::Text::Method::IMetaKeyKeyListener;
using Elastos::Droid::Utility::CSparseInt32Array;
using Elastos::Core::StringUtils;
using Elastos::Core::StringBuilder;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace View {
const Boolean KeyEvent::DEBUG = FALSE;
const String KeyEvent::TAG("KeyEvent");
const Int32 KeyEvent::LAST_KEYCODE = IKeyEvent::KEYCODE_HELP;
const String KeyEvent::META_SYMBOLIC_NAMES[] = {
String("META_SHIFT_ON"),
String("META_ALT_ON"),
String("META_SYM_ON"),
String("META_FUNCTION_ON"),
String("META_ALT_LEFT_ON"),
String("META_ALT_RIGHT_ON"),
String("META_SHIFT_LEFT_ON"),
String("META_SHIFT_RIGHT_ON"),
String("META_CAP_LOCKED"),
String("META_ALT_LOCKED"),
String("META_SYM_LOCKED"),
String("0x00000800"),
String("META_CTRL_ON"),
String("META_CTRL_LEFT_ON"),
String("META_CTRL_RIGHT_ON"),
String("0x00008000"),
String("META_META_ON"),
String("META_META_LEFT_ON"),
String("META_META_RIGHT_ON"),
String("0x00080000"),
String("META_CAPS_LOCK_ON"),
String("META_NUM_LOCK_ON"),
String("META_SCROLL_LOCK_ON"),
String("0x00800000"),
String("0x01000000"),
String("0x02000000"),
String("0x04000000"),
String("0x08000000"),
String("0x10000000"),
String("0x20000000"),
String("0x40000000"),
String("0x80000000"),
};
const String KeyEvent::LABEL_PREFIX("KEYCODE_");
const Int32 KeyEvent::META_MODIFIER_MASK =
META_SHIFT_ON | META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON
| META_ALT_ON | META_ALT_LEFT_ON | META_ALT_RIGHT_ON
| META_CTRL_ON | META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON
| META_META_ON | META_META_LEFT_ON | META_META_RIGHT_ON
| META_SYM_ON | META_FUNCTION_ON;
const Int32 KeyEvent::META_LOCK_MASK =
META_CAPS_LOCK_ON | META_NUM_LOCK_ON | META_SCROLL_LOCK_ON;
const Int32 KeyEvent::META_ALL_MASK = META_MODIFIER_MASK | META_LOCK_MASK;
const Int32 KeyEvent::META_SYNTHETIC_MASK =
META_CAP_LOCKED | META_ALT_LOCKED | META_SYM_LOCKED | META_SELECTING;
const Int32 KeyEvent::META_INVALID_MODIFIER_MASK = META_LOCK_MASK | META_SYNTHETIC_MASK;
const Int32 KeyEvent::MAX_RECYCLED = 10;
Object KeyEvent::gRecyclerLock;
Int32 KeyEvent::gRecyclerUsed;
AutoPtr<IKeyEvent> KeyEvent::gRecyclerTop;
/* KeyEvent::DispatcherState */
CAR_INTERFACE_IMPL(KeyEvent::DispatcherState, Object, IDispatcherState);
KeyEvent::DispatcherState::DispatcherState()
: mDownKeyCode(0)
{
CSparseInt32Array::New((ISparseInt32Array**)&mActiveLongPresses);
}
KeyEvent::DispatcherState::~DispatcherState()
{
}
ECode KeyEvent::DispatcherState::constructor()
{
return NOERROR;
}
ECode KeyEvent::DispatcherState::Reset()
{
if (DEBUG)
Logger::D(KeyEvent::TAG, "Reset: %p", this);
mDownKeyCode = 0;
mDownTarget = NULL;
mActiveLongPresses->Clear();
return NOERROR;
}
ECode KeyEvent::DispatcherState::Reset(
/* [in] */ IInterface* target)
{
if (mDownTarget.Get() == target) {
if (DEBUG)
Logger::D(TAG, "Reset in %p, %p", target, this);
mDownKeyCode = 0;
mDownTarget = NULL;
}
return NOERROR;
}
ECode KeyEvent::DispatcherState::StartTracking(
/* [in] */ IKeyEvent* event,
/* [in] */ IInterface* target)
{
Int32 action;
event->GetAction(&action);
if (action != IKeyEvent::ACTION_DOWN) {
Logger::E(
KeyEvent::TAG, "Can only start tracking on a down event");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
if (DEBUG)
Logger::D(KeyEvent::TAG, "Start trackingt in %p : %p", target, this);
event->GetKeyCode(&mDownKeyCode);
mDownTarget = target;
return NOERROR;
}
ECode KeyEvent::DispatcherState::IsTracking(
/* [in] */ IKeyEvent* event,
/* [out] */ Boolean* isTracking)
{
if (isTracking == NULL) {
return E_INVALID_ARGUMENT;
}
assert(event);
Int32 keyCode;
event->GetKeyCode(&keyCode);
*isTracking = mDownKeyCode == keyCode;
return NOERROR;
}
ECode KeyEvent::DispatcherState::PerformedLongPress(
/* [in] */ IKeyEvent* event)
{
assert(event);
Int32 keyCode;
event->GetKeyCode(&keyCode);
mActiveLongPresses->Put(keyCode, 1);
return NOERROR;
}
ECode KeyEvent::DispatcherState::HandleUpEvent(
/* [in] */ IKeyEvent* event)
{
Int32 keyCode;
event->GetKeyCode(&keyCode);
if (KeyEvent::DEBUG) {
Logger::V(KeyEvent::TAG, "Handle key up :%p", event);
}
Int32 index;
mActiveLongPresses->IndexOfKey(keyCode, &index);
if (index >= 0) {
if (KeyEvent::DEBUG) {
Logger::V(KeyEvent::TAG, " Index: %d ", index);
}
((KeyEvent*)event)->mFlags |=
IKeyEvent::FLAG_CANCELED | IKeyEvent::FLAG_CANCELED_LONG_PRESS;
mActiveLongPresses->RemoveAt(index);
}
if (mDownKeyCode == keyCode) {
if (KeyEvent::DEBUG) {
Logger::V(KeyEvent::TAG, " Tracking!");
}
((KeyEvent*)event)->mFlags |= IKeyEvent::FLAG_TRACKING;
mDownKeyCode = 0;
mDownTarget = NULL;
}
return NOERROR;
}
/* KeyEvent */
CAR_INTERFACE_IMPL(KeyEvent, InputEvent, IKeyEvent);
KeyEvent::KeyEvent()
: mDeviceId(0)
, mSource(0)
, mMetaState(0)
, mAction(0)
, mKeyCode(0)
, mScanCode(0)
, mRepeatCount(0)
, mFlags(0)
, mDownTime(0ll)
, mEventTime(0ll)
, mCharacters(NULL)
{}
KeyEvent::~KeyEvent()
{}
ECode KeyEvent::constructor()
{
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int32 action,
/* [in] */ Int32 code)
{
mAction = action;
mKeyCode = code;
mRepeatCount = 0;
mDeviceId = IKeyCharacterMap::VIRTUAL_KEYBOARD;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int64 downTime,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 action,
/* [in] */ Int32 code,
/* [in] */ Int32 repeat)
{
mDownTime = downTime;
mEventTime = eventTime;
mAction = action;
mKeyCode = code;
mRepeatCount = repeat;
mDeviceId = IKeyCharacterMap::VIRTUAL_KEYBOARD;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int64 downTime,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 action,
/* [in] */ Int32 code,
/* [in] */ Int32 repeat,
/* [in] */ Int32 metaState)
{
mDownTime = downTime;
mEventTime = eventTime;
mAction = action;
mKeyCode = code;
mRepeatCount = repeat;
mMetaState = metaState;
mDeviceId = IKeyCharacterMap::VIRTUAL_KEYBOARD;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int64 downTime,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 action,
/* [in] */ Int32 code,
/* [in] */ Int32 repeat,
/* [in] */ Int32 metaState,
/* [in] */ Int32 deviceId,
/* [in] */ Int32 scancode)
{
mDownTime = downTime;
mEventTime = eventTime;
mAction = action;
mKeyCode = code;
mRepeatCount = repeat;
mMetaState = metaState;
mDeviceId = deviceId;
mScanCode = scancode;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int64 downTime,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 action,
/* [in] */ Int32 code,
/* [in] */ Int32 repeat,
/* [in] */ Int32 metaState,
/* [in] */ Int32 deviceId,
/* [in] */ Int32 scancode,
/* [in] */ Int32 flags)
{
mDownTime = downTime;
mEventTime = eventTime;
mAction = action;
mKeyCode = code;
mRepeatCount = repeat;
mMetaState = metaState;
mDeviceId = deviceId;
mScanCode = scancode;
mFlags = flags;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int64 downTime,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 action,
/* [in] */ Int32 code,
/* [in] */ Int32 repeat,
/* [in] */ Int32 metaState,
/* [in] */ Int32 deviceId,
/* [in] */ Int32 scancode,
/* [in] */ Int32 flags,
/* [in] */ Int32 source)
{
mDownTime = downTime;
mEventTime = eventTime;
mAction = action;
mKeyCode = code;
mRepeatCount = repeat;
mMetaState = metaState;
mDeviceId = deviceId;
mScanCode = scancode;
mFlags = flags;
mSource = source;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ Int64 time,
/* [in] */ const String& characters,
/* [in] */ Int32 deviceId,
/* [in] */ Int32 flags)
{
mDownTime = time;
mEventTime = time;
mCharacters = characters;
mAction = ACTION_MULTIPLE;
mKeyCode = KEYCODE_UNKNOWN;
mRepeatCount = 0;
mDeviceId = deviceId;
mFlags = flags;
mSource = IInputDevice::SOURCE_KEYBOARD;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ IKeyEvent* origEvent)
{
if (origEvent == NULL) {
return E_INVALID_ARGUMENT;
}
AutoPtr<KeyEvent> event = (KeyEvent*)origEvent;
mDownTime = event->mDownTime;
mEventTime = event->mEventTime;
mAction = event->mAction;
mKeyCode = event->mKeyCode;
mRepeatCount = event->mRepeatCount;
mMetaState = event->mMetaState;
mDeviceId = event->mDeviceId;
mSource = event->mSource;
mScanCode = event->mScanCode;
mFlags = event->mFlags;
mCharacters = event->mCharacters;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ IKeyEvent* origEvent,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 newRepeat)
{
if (origEvent == NULL) {
return E_INVALID_ARGUMENT;
}
AutoPtr<KeyEvent> event = (KeyEvent*)origEvent;
mDownTime = event->mDownTime;
mEventTime = eventTime;
mAction = event->mAction;
mKeyCode = event->mKeyCode;
mRepeatCount = newRepeat;
mMetaState = event->mMetaState;
mDeviceId = event->mDeviceId;
mSource = event->mSource;
mScanCode = event->mScanCode;
mFlags = event->mFlags;
mCharacters = event->mCharacters;
return NOERROR;
}
ECode KeyEvent::constructor(
/* [in] */ IKeyEvent* origEvent,
/* [in] */ Int32 action)
{
if (origEvent == NULL) {
return E_INVALID_ARGUMENT;
}
AutoPtr<KeyEvent> event = (KeyEvent*)origEvent;
mDownTime = event->mDownTime;
mEventTime = event->mEventTime;
mAction = action;
mKeyCode = event->mKeyCode;
mRepeatCount = event->mRepeatCount;
mMetaState = event->mMetaState;
mDeviceId = event->mDeviceId;
mSource = event->mSource;
mScanCode = event->mScanCode;
mFlags = event->mFlags;
// Don't copy mCharacters, since one way or the other we'll lose it
// when changing the action.
return NOERROR;
}
AutoPtr<IKeyEvent> KeyEvent::Obtain()
{
AutoPtr<IKeyEvent> ev;
{ AutoLock syncLock(gRecyclerLock);
ev = gRecyclerTop;
if (ev == NULL) {
CKeyEvent::New((IKeyEvent**)&ev);
return ev;
}
AutoPtr<KeyEvent> _event = (KeyEvent*)ev.Get();
gRecyclerTop = _event->mNext;
gRecyclerUsed -= 1;
}
AutoPtr<KeyEvent> _event = (KeyEvent*)ev.Get();
_event->mNext = NULL;
_event->PrepareForReuse();
return ev;
}
Int32 KeyEvent::GetMaxKeyCode()
{
return LAST_KEYCODE;
}
Int32 KeyEvent::GetDeadChar(
/* [in] */ Int32 accent,
/* [in] */ Int32 c)
{
return KeyCharacterMap::GetDeadChar(accent, c);
}
AutoPtr<IKeyEvent> KeyEvent::Obtain(
/* [in] */ Int64 downTime,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 action,
/* [in] */ Int32 code,
/* [in] */ Int32 repeat,
/* [in] */ Int32 metaState,
/* [in] */ Int32 deviceId,
/* [in] */ Int32 scancode,
/* [in] */ Int32 flags,
/* [in] */ Int32 source,
/* [in] */ const String& characters)
{
AutoPtr<IKeyEvent> ev = Obtain();
AutoPtr<KeyEvent> _ev = (KeyEvent*)ev.Get();
_ev->mDownTime = downTime;
_ev->mEventTime = eventTime;
_ev->mAction = action;
_ev->mKeyCode = code;
_ev->mRepeatCount = repeat;
_ev->mMetaState = metaState;
_ev->mDeviceId = deviceId;
_ev->mScanCode = scancode;
_ev->mFlags = flags;
_ev->mSource = source;
_ev->mCharacters = characters;
return ev;
}
AutoPtr<IKeyEvent> KeyEvent::Obtain(
/* [in] */ IKeyEvent* otherEvent)
{
AutoPtr<KeyEvent> other = (KeyEvent*)otherEvent;
AutoPtr<IKeyEvent> ev = Obtain();
AutoPtr<KeyEvent> _ev = (KeyEvent*)ev.Get();
_ev->mDownTime = other->mDownTime;
_ev->mEventTime = other->mEventTime;
_ev->mAction = other->mAction;
_ev->mKeyCode = other->mKeyCode;
_ev->mRepeatCount = other->mRepeatCount;
_ev->mMetaState = other->mMetaState;
_ev->mDeviceId = other->mDeviceId;
_ev->mScanCode = other->mScanCode;
_ev->mFlags = other->mFlags;
_ev->mSource = other->mSource;
_ev->mCharacters = other->mCharacters;
return ev;
}
ECode KeyEvent::Copy(
/* [out] */ IInputEvent** event)
{
VALIDATE_NOT_NULL(event);
AutoPtr<IInputEvent> temp = IInputEvent::Probe(Obtain(this));
*event = temp;
REFCOUNT_ADD(*event);
return NOERROR;
}
ECode KeyEvent::Recycle()
{
InputEvent::Recycle();
mCharacters = NULL;
{ AutoLock syncLock(gRecyclerLock);
if (gRecyclerUsed < MAX_RECYCLED) {
gRecyclerUsed++;
mNext = gRecyclerTop;
gRecyclerTop = this;
}
}
return NOERROR;
}
ECode KeyEvent::RecycleIfNeededAfterDispatch()
{
// Do nothing.
return NOERROR;
}
ECode KeyEvent::ChangeTimeRepeat(
/* [in] */ IKeyEvent* event,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 newRepeat,
/* [out] */ IKeyEvent** newEvent)
{
VALIDATE_NOT_NULL(newEvent);
return CKeyEvent::New(event, eventTime, newRepeat, newEvent);
}
ECode KeyEvent::ChangeTimeRepeat(
/* [in] */ IKeyEvent* event,
/* [in] */ Int64 eventTime,
/* [in] */ Int32 newRepeat,
/* [in] */ Int32 newFlags,
/* [out] */ IKeyEvent** newEvent)
{
VALIDATE_NOT_NULL(newEvent);
AutoPtr<IKeyEvent> ret;
ECode ec = CKeyEvent::New(event, eventTime, newRepeat, (IKeyEvent**)&ret);
if (FAILED(ec)) {
return ec;
}
AutoPtr<KeyEvent> _ret = (KeyEvent*)ret.Get();
_ret->mEventTime = eventTime;
_ret->mRepeatCount = newRepeat;
_ret->mFlags = newFlags;
*newEvent = ret;
REFCOUNT_ADD(*newEvent);
return NOERROR;
}
ECode KeyEvent::ChangeAction(
/* [in] */ IKeyEvent* event,
/* [in] */ Int32 action,
/* [out] */ IKeyEvent** newEvent)
{
VALIDATE_NOT_NULL(newEvent);
return CKeyEvent::New(event, action, newEvent);
}
ECode KeyEvent::ChangeFlags(
/* [in] */ IKeyEvent* event,
/* [in] */ Int32 flags,
/* [out] */ IKeyEvent** newEvent)
{
VALIDATE_NOT_NULL(newEvent);
ECode ec = CKeyEvent::New(event, newEvent);
if (FAILED(ec)) {
return ec;
}
((KeyEvent*)*newEvent)->mFlags = flags;
return NOERROR;
}
ECode KeyEvent::IsTainted(
/* [out] */ Boolean* isTainted)
{
VALIDATE_NOT_NULL(isTainted);
*isTainted = (mFlags & FLAG_TAINTED) != 0;
return NOERROR;
}
ECode KeyEvent::SetTainted(
/* [in] */ Boolean tainted)
{
mFlags = tainted ? mFlags | FLAG_TAINTED : mFlags & ~FLAG_TAINTED;
return NOERROR;
}
ECode KeyEvent::IsDown(
/* [out] */ Boolean* isDown)
{
VALIDATE_NOT_NULL(isDown);
*isDown = (mAction == ACTION_DOWN);
return NOERROR;
}
ECode KeyEvent::IsSystem(
/* [out] */ Boolean* isSystem)
{
VALIDATE_NOT_NULL(isSystem);
*isSystem = IsSystemKey(mKeyCode);
return NOERROR;
}
ECode KeyEvent::IsWakeKey(
/* [out] */ Boolean* wakeKey)
{
VALIDATE_NOT_NULL(wakeKey);
*wakeKey = IsWakeKey(mKeyCode);
return NOERROR;
}
Boolean KeyEvent::IsGamepadButton(
/* [in] */ Int32 keyCode)
{
switch (keyCode) {
case IKeyEvent::KEYCODE_BUTTON_A:
case IKeyEvent::KEYCODE_BUTTON_B:
case IKeyEvent::KEYCODE_BUTTON_C:
case IKeyEvent::KEYCODE_BUTTON_X:
case IKeyEvent::KEYCODE_BUTTON_Y:
case IKeyEvent::KEYCODE_BUTTON_Z:
case IKeyEvent::KEYCODE_BUTTON_L1:
case IKeyEvent::KEYCODE_BUTTON_R1:
case IKeyEvent::KEYCODE_BUTTON_L2:
case IKeyEvent::KEYCODE_BUTTON_R2:
case IKeyEvent::KEYCODE_BUTTON_THUMBL:
case IKeyEvent::KEYCODE_BUTTON_THUMBR:
case IKeyEvent::KEYCODE_BUTTON_START:
case IKeyEvent::KEYCODE_BUTTON_SELECT:
case IKeyEvent::KEYCODE_BUTTON_MODE:
case IKeyEvent::KEYCODE_BUTTON_1:
case IKeyEvent::KEYCODE_BUTTON_2:
case IKeyEvent::KEYCODE_BUTTON_3:
case IKeyEvent::KEYCODE_BUTTON_4:
case IKeyEvent::KEYCODE_BUTTON_5:
case IKeyEvent::KEYCODE_BUTTON_6:
case IKeyEvent::KEYCODE_BUTTON_7:
case IKeyEvent::KEYCODE_BUTTON_8:
case IKeyEvent::KEYCODE_BUTTON_9:
case IKeyEvent::KEYCODE_BUTTON_10:
case IKeyEvent::KEYCODE_BUTTON_11:
case IKeyEvent::KEYCODE_BUTTON_12:
case IKeyEvent::KEYCODE_BUTTON_13:
case IKeyEvent::KEYCODE_BUTTON_14:
case IKeyEvent::KEYCODE_BUTTON_15:
case IKeyEvent::KEYCODE_BUTTON_16:
return TRUE;
default:
return FALSE;
}
}
Boolean KeyEvent::IsConfirmKey(
/* [in] */ Int32 keyCode)
{
switch (keyCode) {
case IKeyEvent::KEYCODE_DPAD_CENTER:
case IKeyEvent::KEYCODE_ENTER:
return TRUE;
default:
return FALSE;
}
}
Boolean KeyEvent::IsMediaKey(
/* [in] */ Int32 keyCode)
{
switch (keyCode) {
case IKeyEvent::KEYCODE_MEDIA_PLAY:
case IKeyEvent::KEYCODE_MEDIA_PAUSE:
case IKeyEvent::KEYCODE_MEDIA_PLAY_PAUSE:
case IKeyEvent::KEYCODE_MUTE:
case IKeyEvent::KEYCODE_HEADSETHOOK:
case IKeyEvent::KEYCODE_MEDIA_STOP:
case IKeyEvent::KEYCODE_MEDIA_NEXT:
case IKeyEvent::KEYCODE_MEDIA_PREVIOUS:
case IKeyEvent::KEYCODE_MEDIA_REWIND:
case IKeyEvent::KEYCODE_MEDIA_RECORD:
case IKeyEvent::KEYCODE_MEDIA_FAST_FORWARD:
return TRUE;
}
return FALSE;
}
Boolean KeyEvent::IsSystemKey(
/* [in] */ Int32 keyCode)
{
switch (keyCode) {
case IKeyEvent::KEYCODE_MENU:
case IKeyEvent::KEYCODE_SOFT_RIGHT:
case IKeyEvent::KEYCODE_HOME:
case IKeyEvent::KEYCODE_BACK:
case IKeyEvent::KEYCODE_CALL:
case IKeyEvent::KEYCODE_ENDCALL:
case IKeyEvent::KEYCODE_VOLUME_UP:
case IKeyEvent::KEYCODE_VOLUME_DOWN:
case IKeyEvent::KEYCODE_VOLUME_MUTE:
case IKeyEvent::KEYCODE_MUTE:
case IKeyEvent::KEYCODE_POWER:
case IKeyEvent::KEYCODE_HEADSETHOOK:
case IKeyEvent::KEYCODE_MEDIA_PLAY:
case IKeyEvent::KEYCODE_MEDIA_PAUSE:
case IKeyEvent::KEYCODE_MEDIA_PLAY_PAUSE:
case IKeyEvent::KEYCODE_MEDIA_STOP:
case IKeyEvent::KEYCODE_MEDIA_NEXT:
case IKeyEvent::KEYCODE_MEDIA_PREVIOUS:
case IKeyEvent::KEYCODE_MEDIA_REWIND:
case IKeyEvent::KEYCODE_MEDIA_RECORD:
case IKeyEvent::KEYCODE_MEDIA_FAST_FORWARD:
case IKeyEvent::KEYCODE_CAMERA:
case IKeyEvent::KEYCODE_FOCUS:
case IKeyEvent::KEYCODE_SEARCH:
case IKeyEvent::KEYCODE_BRIGHTNESS_DOWN:
case IKeyEvent::KEYCODE_BRIGHTNESS_UP:
case IKeyEvent::KEYCODE_MEDIA_AUDIO_TRACK:
return TRUE;
}
return FALSE;
}
Boolean KeyEvent::IsWakeKey(
/* [in] */ Int32 keyCode)
{
switch (keyCode) {
case IKeyEvent::KEYCODE_BACK:
case IKeyEvent::KEYCODE_POWER:
case IKeyEvent::KEYCODE_MENU:
case IKeyEvent::KEYCODE_SLEEP:
case IKeyEvent::KEYCODE_WAKEUP:
case IKeyEvent::KEYCODE_PAIRING:
case IKeyEvent::KEYCODE_VOLUME_UP:
case IKeyEvent::KEYCODE_VOLUME_DOWN:
case IKeyEvent::KEYCODE_VOLUME_MUTE:
return TRUE;
}
return FALSE;
}
Boolean KeyEvent::IsMetaKey(
/* [in] */ Int32 keyCode)
{
return keyCode == IKeyEvent::KEYCODE_META_LEFT || keyCode == IKeyEvent::KEYCODE_META_RIGHT;
}
ECode KeyEvent::GetDeviceId(
/* [out] */ Int32* deviceId)
{
VALIDATE_NOT_NULL(deviceId);
*deviceId = mDeviceId;
return NOERROR;
}
ECode KeyEvent::GetDevice(
/* [out] */ IInputDevice** device)
{
VALIDATE_NOT_NULL(device);
return InputEvent::GetDevice(device);
}
ECode KeyEvent::GetSource(
/* [out] */ Int32* source)
{
VALIDATE_NOT_NULL(source);
*source = mSource;
return NOERROR;
}
ECode KeyEvent::SetSource(
/* [in] */ Int32 source)
{
mSource = source;
return NOERROR;
}
ECode KeyEvent::GetMetaState(
/* [out] */ Int32* metaState)
{
VALIDATE_NOT_NULL(metaState);
*metaState = mMetaState;
return NOERROR;
}
ECode KeyEvent::GetModifiers(
/* [out] */ Int32* modifiers)
{
VALIDATE_NOT_NULL(modifiers);
*modifiers = NormalizeMetaState(mMetaState) & META_MODIFIER_MASK;
return NOERROR;
}
ECode KeyEvent::GetFlags(
/* [out] */ Int32* flags)
{
VALIDATE_NOT_NULL(flags);
*flags = mFlags;
return NOERROR;
}
Int32 KeyEvent::GetModifierMetaStateMask()
{
return META_MODIFIER_MASK;
}
Boolean KeyEvent::IsModifierKey(
/* [in] */ Int32 keyCode)
{
switch (keyCode) {
case KEYCODE_SHIFT_LEFT:
case KEYCODE_SHIFT_RIGHT:
case KEYCODE_ALT_LEFT:
case KEYCODE_ALT_RIGHT:
case KEYCODE_CTRL_LEFT:
case KEYCODE_CTRL_RIGHT:
case KEYCODE_META_LEFT:
case KEYCODE_META_RIGHT:
case KEYCODE_SYM:
case KEYCODE_NUM:
case KEYCODE_FUNCTION:
return TRUE;
default:
return FALSE;
}
}
Int32 KeyEvent::NormalizeMetaState(
/* [in] */ Int32 metaState)
{
if ((metaState & (META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON)) != 0) {
metaState |= META_SHIFT_ON;
}
if ((metaState & (META_ALT_LEFT_ON | META_ALT_RIGHT_ON)) != 0) {
metaState |= META_ALT_ON;
}
if ((metaState & (META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON)) != 0) {
metaState |= META_CTRL_ON;
}
if ((metaState & (META_META_LEFT_ON | META_META_RIGHT_ON)) != 0) {
metaState |= META_META_ON;
}
if ((metaState & IMetaKeyKeyListener::META_CAP_LOCKED) != 0) {
metaState |= META_CAPS_LOCK_ON;
}
if ((metaState & IMetaKeyKeyListener::META_ALT_LOCKED) != 0) {
metaState |= META_ALT_ON;
}
if ((metaState & IMetaKeyKeyListener::META_SYM_LOCKED) != 0) {
metaState |= META_SYM_ON;
}
return metaState & META_ALL_MASK;
}
Boolean KeyEvent::MetaStateHasNoModifiers(
/* [in] */ Int32 metaState)
{
return (NormalizeMetaState(metaState) & META_MODIFIER_MASK) == 0;
}
ECode KeyEvent::MetaStateHasModifiers(
/* [in] */ Int32 metaState,
/* [in] */ Int32 modifiers,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
// Note: For forward compatibility, we allow the parameter to contain meta states
// that we do not recognize but we explicitly disallow meta states that
// are not valid modifiers.
if ((modifiers & META_INVALID_MODIFIER_MASK) != 0) {
Logger::E(TAG, String("modifiers must not contain ")
+ "META_CAPS_LOCK_ON, META_NUM_LOCK_ON, META_SCROLL_LOCK_ON, "
+ "META_CAP_LOCKED, META_ALT_LOCKED, META_SYM_LOCKED, "
+ "or META_SELECTING");
return E_ILLEGAL_ARGUMENT_EXCEPTION ;
}
metaState = NormalizeMetaState(metaState) & META_MODIFIER_MASK;
FAIL_RETURN(MetaStateFilterDirectionalModifiers(metaState, modifiers,
META_SHIFT_ON, META_SHIFT_LEFT_ON, META_SHIFT_RIGHT_ON, &metaState));
FAIL_RETURN(MetaStateFilterDirectionalModifiers(metaState, modifiers,
META_ALT_ON, META_ALT_LEFT_ON, META_ALT_RIGHT_ON, &metaState));
FAIL_RETURN(MetaStateFilterDirectionalModifiers(metaState, modifiers,
META_CTRL_ON, META_CTRL_LEFT_ON, META_CTRL_RIGHT_ON, &metaState));
FAIL_RETURN(MetaStateFilterDirectionalModifiers(metaState, modifiers,
META_META_ON, META_META_LEFT_ON, META_META_RIGHT_ON, &metaState));
*res = metaState == modifiers;
return NOERROR;
}
ECode KeyEvent::MetaStateFilterDirectionalModifiers(
/* [in] */ Int32 metaState,
/* [in] */ Int32 modifiers,
/* [in] */ Int32 basic,
/* [in] */ Int32 left,
/* [in] */ Int32 right,
/* [out] */ Int32* ret)
{
VALIDATE_NOT_NULL(ret);
Boolean wantBasic = (modifiers & basic) != 0;
Int32 directional = left | right;
Boolean wantLeftOrRight = (modifiers & directional) != 0;
if (wantBasic) {
if (wantLeftOrRight) {
Logger::E(TAG, String("modifiers must not contain ")
+ MetaStateToString(basic) + " combined with "
+ MetaStateToString(left) + " or " + MetaStateToString(right));
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
*ret = metaState & ~directional;
}
else if (wantLeftOrRight) {
*ret = metaState & ~basic;
}
else {
*ret = metaState;
}
return NOERROR;
}
ECode KeyEvent::HasNoModifiers(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = MetaStateHasNoModifiers(mMetaState);
return NOERROR;
}
ECode KeyEvent::HasModifiers(
/* [in] */ Int32 modifiers,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
return MetaStateHasModifiers(mMetaState, modifiers, res);
}
ECode KeyEvent::IsAltPressed(
/* [out] */ Boolean* isAltPressed)
{
VALIDATE_NOT_NULL(isAltPressed);
*isAltPressed = (mMetaState & META_ALT_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsShiftPressed(
/* [out] */ Boolean* isShiftPressed)
{
VALIDATE_NOT_NULL(isShiftPressed);
*isShiftPressed = (mMetaState & META_SHIFT_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsSymPressed(
/* [out] */ Boolean* isSymPressed)
{
VALIDATE_NOT_NULL(isSymPressed);
*isSymPressed = (mMetaState & META_SYM_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsCtrlPressed(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = (mMetaState & META_CTRL_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsMetaPressed(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = (mMetaState & META_META_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsFunctionPressed(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = (mMetaState & META_FUNCTION_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsCapsLockOn(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = (mMetaState & META_CAPS_LOCK_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsNumLockOn(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = (mMetaState & META_NUM_LOCK_ON) != 0;
return NOERROR;
}
ECode KeyEvent::IsScrollLockOn(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = (mMetaState & META_SCROLL_LOCK_ON) != 0;
return NOERROR;
}
ECode KeyEvent::GetAction(
/* [out] */ Int32* action)
{
VALIDATE_NOT_NULL(action);
*action = mAction;
return NOERROR;
}
ECode KeyEvent::IsCanceled(
/* [out] */ Boolean* isCanceled)
{
VALIDATE_NOT_NULL(isCanceled);
*isCanceled = (mFlags&FLAG_CANCELED) != 0;
return NOERROR;
}
ECode KeyEvent::StartTracking()
{
mFlags |= FLAG_START_TRACKING;
return NOERROR;
}
ECode KeyEvent::IsTracking(
/* [out] */ Boolean* isTracking)
{
VALIDATE_NOT_NULL(isTracking);
*isTracking = (mFlags&FLAG_TRACKING) != 0;
return NOERROR;
}
ECode KeyEvent::IsLongPress(
/* [out] */ Boolean* isLongPress)
{
VALIDATE_NOT_NULL(isLongPress);
*isLongPress = (mFlags&FLAG_LONG_PRESS) != 0;
return NOERROR;
}
ECode KeyEvent::GetKeyCode(
/* [out] */ Int32* keyCode)
{
VALIDATE_NOT_NULL(keyCode);
*keyCode = mKeyCode;
return NOERROR;
}
ECode KeyEvent::GetCharacters(
/* [out] */ String* characters)
{
VALIDATE_NOT_NULL(characters);
*characters = mCharacters;
return NOERROR;
}
ECode KeyEvent::GetScanCode(
/* [out] */ Int32* scanCode)
{
VALIDATE_NOT_NULL(scanCode);
*scanCode = mScanCode;
return NOERROR;
}
ECode KeyEvent::GetRepeatCount(
/* [out] */ Int32* repeatCount)
{
VALIDATE_NOT_NULL(repeatCount);
*repeatCount = mRepeatCount;
return NOERROR;
}
ECode KeyEvent::GetDownTime(
/* [out] */ Int64* downTime)
{
VALIDATE_NOT_NULL(downTime);
*downTime = mDownTime;
return NOERROR;
}
ECode KeyEvent::GetEventTime(
/* [out] */ Int64* eventTime)
{
VALIDATE_NOT_NULL(eventTime);
*eventTime = mEventTime;
return NOERROR;
}
ECode KeyEvent::GetEventTimeNano(
/* [out] */ Int64* eventTimeNano)
{
VALIDATE_NOT_NULL(eventTimeNano);
*eventTimeNano = mEventTime * 1000000L;
return NOERROR;
}
ECode KeyEvent::GetSequenceNumber(
/* [out] */ Int32* seq)
{
VALIDATE_NOT_NULL(seq);
return InputEvent::GetSequenceNumber(seq);
}
ECode KeyEvent::GetKeyboardDevice(
/* [out] */ Int32* deviceId)
{
VALIDATE_NOT_NULL(deviceId);
*deviceId = mDeviceId;
return NOERROR;
}
ECode KeyEvent::GetKeyCharacterMap(
/* [out] */ IKeyCharacterMap** kcm)
{
return KeyCharacterMap::Load(mDeviceId, kcm);
}
ECode KeyEvent::GetDisplayLabel(
/* [out] */ Char32* displayLabel)
{
VALIDATE_NOT_NULL(displayLabel);
AutoPtr<IKeyCharacterMap> kcm;
FAIL_RETURN(GetKeyCharacterMap((IKeyCharacterMap**)&kcm));
return kcm->GetDisplayLabel(mKeyCode, displayLabel);
}
ECode KeyEvent::GetUnicodeChar(
/* [out] */ Int32* unicodeChar)
{
return GetUnicodeChar(mMetaState, unicodeChar);
}
ECode KeyEvent::GetUnicodeChar(
/* [in] */ Int32 metaState,
/* [out] */ Int32* unicodeChar)
{
VALIDATE_NOT_NULL(unicodeChar);
AutoPtr<IKeyCharacterMap> kcm;
FAIL_RETURN(GetKeyCharacterMap((IKeyCharacterMap**)&kcm));
return kcm->Get(mKeyCode, metaState, unicodeChar);
}
ECode KeyEvent::GetKeyData(
/* [in] */ IKeyData* keyData,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
AutoPtr<IKeyCharacterMap> kcm;
FAIL_RETURN(GetKeyCharacterMap((IKeyCharacterMap**)&kcm));
return kcm->GetKeyData(mKeyCode, keyData, res);
}
ECode KeyEvent::GetMatch(
/* [in] */ ArrayOf<Char32>* chars,
/* [out] */ Char32* match)
{
return GetMatch(chars, 0, match);
}
ECode KeyEvent::GetMatch(
/* [in] */ ArrayOf<Char32>* chars,
/* [in] */ Int32 modifiers,
/* [out] */ Char32* match)
{
VALIDATE_NOT_NULL(match);
AutoPtr<IKeyCharacterMap> kcm;
FAIL_RETURN(GetKeyCharacterMap((IKeyCharacterMap**)&kcm));
return kcm->GetMatch(mKeyCode, chars, modifiers, match);
}
ECode KeyEvent::GetNumber(
/* [out] */ Char32* ch)
{
VALIDATE_NOT_NULL(ch);
AutoPtr<IKeyCharacterMap> kcm;
FAIL_RETURN(GetKeyCharacterMap((IKeyCharacterMap**)&kcm));
return kcm->GetNumber(mKeyCode, ch);
}
ECode KeyEvent::IsPrintingKey(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
AutoPtr<IKeyCharacterMap> kcm;
FAIL_RETURN(GetKeyCharacterMap((IKeyCharacterMap**)&kcm));
return kcm->IsPrintingKey(mKeyCode, res);
}
ECode KeyEvent::Dispatch(
/* [in] */ IKeyEventCallback* receiver,
/* [out] */ Boolean* res)
{
return Dispatch(receiver, NULL, NULL, res);
}
ECode KeyEvent::Dispatch(
/* [in] */ IKeyEventCallback* receiver,
/* [in] */ IDispatcherState* state,
/* [in] */ IInterface* target,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
if (DEBUG) {
Logger::D(TAG, "Key down to %p in %p, mAction:%d", target, state, mAction);
}
Boolean res = FALSE;
switch (mAction) {
case ACTION_DOWN: {
mFlags &= ~FLAG_START_TRACKING;
receiver->OnKeyDown(mKeyCode, this, &res);
if (state != NULL) {
Boolean isLongPress;
Boolean isTracking;
if (res && mRepeatCount == 0
&& (mFlags & FLAG_START_TRACKING) != 0) {
if (DEBUG)
Logger::D(TAG, " Start tracking!");
state->StartTracking(this, target);
}
else if ((IsLongPress(&isLongPress), isLongPress)
&& (state->IsTracking(this, &isTracking), isTracking)) {
receiver->OnKeyLongPress(mKeyCode, this, &res);
if (res) {
if (DEBUG) {
Logger::D(TAG, " Clear from Int64 press!");
}
state->PerformedLongPress(this);
}
}
}
}
break;
case ACTION_UP: {
if (state != NULL) {
state->HandleUpEvent(this);
}
FAIL_RETURN(receiver->OnKeyUp(mKeyCode, this, &res));
}
break;
case ACTION_MULTIPLE: {
Int32 count = mRepeatCount;
Int32 code = mKeyCode;
receiver->OnKeyMultiple(code, count, this, &res);
if (res) {
break;
}
if (code != KEYCODE_UNKNOWN) {
mAction = ACTION_DOWN;
mRepeatCount = 0;
Boolean handled = FALSE;
receiver->OnKeyDown(code, this, &handled);
if (handled) {
mAction = ACTION_UP;
receiver->OnKeyUp(code, this, &res);
}
mAction = ACTION_MULTIPLE;
mRepeatCount = count;
res = handled;
}
}
break;
default:
break;
}
*result = res;
return NOERROR;
}
ECode KeyEvent::ToString(
/* [out] */ String* info)
{
VALIDATE_NOT_NULL(info)
StringBuilder msg;
msg.Append("KeyEvent { action=");
msg.Append(ActionToString(mAction));
msg.Append(", keyCode=");
msg.Append(KeyCodeToString(mKeyCode));
msg.Append(", scanCode=");
msg.Append(mScanCode);
if (!mCharacters.IsNull()) {
msg.Append(", characters=\"");
msg.Append(mCharacters);
msg.Append("\"");
}
msg.Append(", metaState=");
msg.Append(MetaStateToString(mMetaState));
msg.Append(", flags=0x");
msg.Append(StringUtils::ToHexString(mFlags));
msg.Append(", repeatCount=");
msg.Append(mRepeatCount);
msg.Append(", eventTime=");
msg.Append(mEventTime);
msg.Append(", downTime=");
msg.Append(mDownTime);
msg.Append(", deviceId=");
msg.Append(mDeviceId);
msg.Append(", source=0x");
msg.Append(StringUtils::ToHexString(mSource));
msg.Append(" }");
*info = msg.ToString();
return NOERROR;
}
String KeyEvent::ActionToString(
/* [in] */ Int32 action)
{
switch (action) {
case ACTION_DOWN:
return String("ACTION_DOWN");
case ACTION_UP:
return String("ACTION_UP");
case ACTION_MULTIPLE:
return String("ACTION_MULTIPLE");
default:
return StringUtils::ToString(action);
}
}
String KeyEvent::KeyCodeToString(
/* [in] */ Int32 keyCode)
{
String symbolicName = NativeKeyCodeToString(keyCode);
return symbolicName.IsNull() ? StringUtils::ToString(keyCode) : LABEL_PREFIX + symbolicName;
}
ECode KeyEvent::KeyCodeFromString(
/* [in] */ const String& symbolicName,
/* [out] */ Int32* keyCode)
{
VALIDATE_NOT_NULL(keyCode);
String name(symbolicName);
if (name.StartWith(LABEL_PREFIX)) {
name = symbolicName.Substring(LABEL_PREFIX.GetLength());
Int32 data = NativeKeyCodeFromString(name);
if (data > 0) {
*keyCode = data;
return NOERROR;
}
}
*keyCode = StringUtils::ParseInt32(name, 10);
return NOERROR;
// try {
// return Integer.parseInt(symbolicName, 10);
// } catch (NumberFormatException ex) {
// return KEYCODE_UNKNOWN;
// }
}
String KeyEvent::MetaStateToString(
/* [in] */ Int32 metaState)
{
if (metaState == 0) {
return String("0");
}
AutoPtr<StringBuilder> result;
Int32 i = 0;
while (metaState != 0) {
Boolean isSet = (metaState & 1) != 0;
metaState = ((UInt32)metaState) >> 1; // unsigned shift!
if (isSet) {
String name = META_SYMBOLIC_NAMES[i];
if (result == NULL) {
if (metaState == 0) {
return name;
}
result = new StringBuilder(name);
}
else {
result->AppendChar('|');
result->Append(name);
}
}
i += 1;
}
return result->ToString();
}
ECode KeyEvent::CreateFromParcelBody(
/* [in] */ IParcel* in,
/* [out] */ IKeyEvent** newEvent)
{
VALIDATE_NOT_NULL(newEvent)
AutoPtr<CKeyEvent> event;
CKeyEvent::NewByFriend((CKeyEvent**)&event);
event->ReadFromParcel(in);
*newEvent = (IKeyEvent*)event.Get();
REFCOUNT_ADD(*newEvent);
return NOERROR;
}
ECode KeyEvent::ReadFromParcel(
/* [in] */ IParcel *source)
{
VALIDATE_NOT_NULL(source);
Int32 token;
FAIL_RETURN(source->ReadInt32(&token));
FAIL_RETURN(source->ReadInt32(&mDeviceId));
FAIL_RETURN(source->ReadInt32(&mSource));
FAIL_RETURN(source->ReadInt32(&mAction));
FAIL_RETURN(source->ReadInt32(&mKeyCode));
FAIL_RETURN(source->ReadInt32(&mRepeatCount));
FAIL_RETURN(source->ReadInt32(&mMetaState));
FAIL_RETURN(source->ReadInt32(&mScanCode));
FAIL_RETURN(source->ReadInt32(&mFlags));
FAIL_RETURN(source->ReadInt64(&mDownTime));
FAIL_RETURN(source->ReadInt64(&mEventTime));
return NOERROR;
}
ECode KeyEvent::WriteToParcel(
/* [in] */ IParcel* dest)
{
VALIDATE_NOT_NULL(dest);
FAIL_RETURN(dest->WriteInt32(PARCEL_TOKEN_KEY_EVENT));
FAIL_RETURN(dest->WriteInt32(mDeviceId));
FAIL_RETURN(dest->WriteInt32(mSource));
FAIL_RETURN(dest->WriteInt32(mAction));
FAIL_RETURN(dest->WriteInt32(mKeyCode));
FAIL_RETURN(dest->WriteInt32(mRepeatCount));
FAIL_RETURN(dest->WriteInt32(mMetaState));
FAIL_RETURN(dest->WriteInt32(mScanCode));
FAIL_RETURN(dest->WriteInt32(mFlags));
FAIL_RETURN(dest->WriteInt64(mDownTime));
FAIL_RETURN(dest->WriteInt64(mEventTime));
return NOERROR;
}
String KeyEvent::NativeKeyCodeToString(
/* [in] */ Int32 keyCode)
{
return String(android::KeyEvent::getLabel(keyCode));
}
Int32 KeyEvent::NativeKeyCodeFromString(
/* [in] */ const String& keyCode)
{
return android::KeyEvent::getKeyCodeFromLabel(keyCode.string());
}
} //namespace View
} //namespace Droid
} //namespace Elastos
| 25.235813
| 96
| 0.628273
|
jingcao80
|
3f287ae5781c2e83cdbfb3b931b466c1bbf094b0
| 1,120
|
cpp
|
C++
|
platform/qt/test/headless_backend_qt.cpp
|
followtherider/mapbox-gl-native
|
62b56b799a7d4fcd1a8f151eed878054b862da5b
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
platform/qt/test/headless_backend_qt.cpp
|
followtherider/mapbox-gl-native
|
62b56b799a7d4fcd1a8f151eed878054b862da5b
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
platform/qt/test/headless_backend_qt.cpp
|
followtherider/mapbox-gl-native
|
62b56b799a7d4fcd1a8f151eed878054b862da5b
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
#include <mbgl/platform/default/headless_backend.hpp>
#include <mbgl/platform/default/headless_display.hpp>
#include <QApplication>
#include <QGLContext>
#include <QGLWidget>
#if QT_VERSION >= 0x050000
#include <QOpenGLContext>
#endif
namespace mbgl {
gl::glProc HeadlessBackend::initializeExtension(const char* name) {
#if QT_VERSION >= 0x050000
QOpenGLContext* thisContext = QOpenGLContext::currentContext();
return thisContext->getProcAddress(name);
#else
const QGLContext* thisContext = QGLContext::currentContext();
return reinterpret_cast<mbgl::gl::glProc>(thisContext->getProcAddress(name));
#endif
}
void HeadlessBackend::createContext() {
static const char* argv[] = { "mbgl" };
static int argc = 1;
static auto* app = new QApplication(argc, const_cast<char**>(argv));
Q_UNUSED(app);
glContext = new QGLWidget;
}
void HeadlessBackend::destroyContext() {
delete glContext;
}
void HeadlessBackend::activateContext() {
glContext->makeCurrent();
}
void HeadlessBackend::deactivateContext() {
glContext->doneCurrent();
}
} // namespace mbgl
| 23.829787
| 85
| 0.721429
|
followtherider
|
3f293f21d797a9eb2e8670cba5b2222d05fb82cc
| 954
|
cpp
|
C++
|
Codechef/Compete/Long Challenge/November Challenge 2020/Restore sequence.cpp
|
mohitkhedkar/Competitive-programming
|
85d08791002363c6a1104b6b51bf049489fd5257
|
[
"MIT"
] | 2
|
2020-10-22T15:37:14.000Z
|
2020-12-11T06:45:02.000Z
|
Codechef/Compete/Long Challenge/November Challenge 2020/Restore sequence.cpp
|
mohitkhedkar/Competitive-programming
|
85d08791002363c6a1104b6b51bf049489fd5257
|
[
"MIT"
] | null | null | null |
Codechef/Compete/Long Challenge/November Challenge 2020/Restore sequence.cpp
|
mohitkhedkar/Competitive-programming
|
85d08791002363c6a1104b6b51bf049489fd5257
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--) {
int n,j=1;
cin>>n;
int b[100000];
for(int i=1;i<=n;i++) {
cin>>b[i];
}
int a[100000];
int status = 1, num = 2, count, c;
if (n>= 1) {
a[1]=2;
}
for (count = 1; count <=n; ) {
for (c = 2; c <= (int)sqrt(num); c++) {
if (num%c == 0) {
status = 0;
break;
}
}
if (status != 0) {
a[j]=num;
count++;
j++;
}
status = 1;
num++;
}
int arr[10];
for(int i=1;i<=n;i++) {
if(i==b[i]) {
arr[i]=a[i];
}else {
arr[i]=a[b[i]];
}
cout<<arr[i]<<" ";
}
cout<<endl;
}
return 0;
}
| 17.666667
| 49
| 0.301887
|
mohitkhedkar
|
3f2c1ac046105797fe34a37395d66b2f99694bc9
| 7,704
|
cc
|
C++
|
onnxruntime/core/optimizer/gemm_sum_fusion.cc
|
lchang20/onnxruntime
|
97b8f6f394ae02c73ed775f456fd85639c91ced1
|
[
"MIT"
] | 669
|
2018-12-03T22:00:31.000Z
|
2019-05-06T19:42:49.000Z
|
onnxruntime/core/optimizer/gemm_sum_fusion.cc
|
lchang20/onnxruntime
|
97b8f6f394ae02c73ed775f456fd85639c91ced1
|
[
"MIT"
] | 440
|
2018-12-03T21:09:56.000Z
|
2019-05-06T20:47:23.000Z
|
onnxruntime/core/optimizer/gemm_sum_fusion.cc
|
lchang20/onnxruntime
|
97b8f6f394ae02c73ed775f456fd85639c91ced1
|
[
"MIT"
] | 140
|
2018-12-03T21:15:28.000Z
|
2019-05-06T18:02:36.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/optimizer/gemm_sum_fusion.h"
#include "core/graph/graph_utils.h"
#include "core/optimizer/initializer.h"
#include "core/optimizer/utils.h"
using namespace ONNX_NAMESPACE;
using namespace onnxruntime::common;
namespace onnxruntime {
Status GemmSumFusion::Apply(Graph& graph, Node& gemm_node, RewriteRuleEffect& modified, const logging::Logger&) const {
// Get currently set attributes of Gemm. Beta will become 1.0.
const bool transA = static_cast<bool>(gemm_node.GetAttributes().at("transA").i());
const bool transB = static_cast<bool>(gemm_node.GetAttributes().at("transB").i());
const float alpha = gemm_node.GetAttributes().at("alpha").f();
constexpr float beta = 1.0f;
Node& sum_node = *graph.GetNode(gemm_node.OutputEdgesBegin()->GetNode().Index());
// The first two input defs for our new gemm (aka tensor A and tensor B in GemmSumFusion's
// documentation) are exactly the same as the old gemm's input defs.
std::vector<NodeArg*> new_gemm_input_defs = gemm_node.MutableInputDefs();
// The other new gemm's input def is the old sum's other input def (aka tensor C in
// GemmSumFusion's documentation).
if (sum_node.InputDefs()[0]->Name() == gemm_node.OutputDefs()[0]->Name()) {
new_gemm_input_defs.push_back(sum_node.MutableInputDefs()[1]);
} else {
new_gemm_input_defs.push_back(sum_node.MutableInputDefs()[0]);
}
ORT_ENFORCE(new_gemm_input_defs.size() == 3);
std::vector<NodeArg*> new_gemm_output_defs = sum_node.MutableOutputDefs();
ORT_ENFORCE(new_gemm_output_defs.size() == 1);
Node& new_gemm_node = graph.AddNode(graph.GenerateNodeName(gemm_node.Name() + "_sum_transformed"),
gemm_node.OpType(),
"Fused Gemm with Sum",
new_gemm_input_defs,
new_gemm_output_defs,
{},
gemm_node.Domain());
new_gemm_node.AddAttribute("transA", static_cast<int64_t>(transA));
new_gemm_node.AddAttribute("transB", static_cast<int64_t>(transB));
new_gemm_node.AddAttribute("alpha", alpha);
new_gemm_node.AddAttribute("beta", beta);
// Move both input edges from original gemm to new gemm.
for (auto gemm_input_edge : graph_utils::GraphEdge::GetNodeInputEdges(gemm_node)) {
ORT_ENFORCE(gemm_input_edge.src_arg_index < 2);
graph.AddEdge(gemm_input_edge.src_node, new_gemm_node.Index(), gemm_input_edge.src_arg_index, gemm_input_edge.dst_arg_index);
graph.RemoveEdge(gemm_input_edge.src_node, gemm_input_edge.dst_node, gemm_input_edge.src_arg_index, gemm_input_edge.dst_arg_index);
}
// Move all output edges from sum to new gemm.
for (auto sum_output_edge : graph_utils::GraphEdge::GetNodeOutputEdges(sum_node)) {
ORT_ENFORCE(sum_output_edge.src_arg_index == 0);
graph.AddEdge(new_gemm_node.Index(), sum_output_edge.dst_node, sum_output_edge.src_arg_index, sum_output_edge.dst_arg_index);
graph.RemoveEdge(sum_output_edge.src_node, sum_output_edge.dst_node, sum_output_edge.src_arg_index, sum_output_edge.dst_arg_index);
}
// Finally, move the other sum input edge to "C" for the new gemm node.
// If The other sum input def is a a graph input, there is no edge to move.
bool sum_input_moved = false;
for (auto sum_input_edge : graph_utils::GraphEdge::GetNodeInputEdges(sum_node)) {
// The C tensor in GemmSumFusion's documentation is the sum output which does not come from
// the fused gemm. The following condition will be true when seeing the input of C to sum.
if (sum_input_edge.src_node != gemm_node.Index()) {
ORT_ENFORCE(!sum_input_moved);
graph.AddEdge(sum_input_edge.src_node, new_gemm_node.Index(), sum_input_edge.src_arg_index, 2);
graph.RemoveEdge(sum_input_edge.src_node, sum_input_edge.dst_node, sum_input_edge.src_arg_index, sum_input_edge.dst_arg_index);
sum_input_moved = true;
}
}
// Old gemm node output is no longer needed. It was previously fed into the
// sum node which is now also handled by the new gemm. Remove this output edge
// to allow the node to be removed from the graph.
graph_utils::RemoveNodeOutputEdges(graph, gemm_node);
ORT_ENFORCE(graph.RemoveNode(gemm_node.Index()));
// All output edges of the sum node should have been removed already, so we can
// remove it from the graph.
ORT_ENFORCE(sum_node.GetOutputEdgesCount() == 0);
ORT_ENFORCE(graph.RemoveNode(sum_node.Index()));
modified = RewriteRuleEffect::kRemovedCurrentNode;
return Status::OK();
}
bool GemmSumFusion::SatisfyCondition(const Graph& graph, const Node& node, const logging::Logger&) const {
// Perform a series of checks. If any fail, fusion may not be performed.
// Original gemm's C must be missing for this fusion pattern to be valid.
// Supported for Opset >=11 as earlier opsets have C as a required input
if (!graph_utils::IsSupportedOptypeVersionAndDomain(node, "Gemm", {11, 13}) ||
graph.NodeProducesGraphOutput(node) ||
// 2 inputs means that the gemm has A and B present, but not C.
node.InputDefs().size() != 2) {
return false;
}
// This gemm node must have exactly one output for this fusion pattern to be valid. We have already
// verified that this node does not produce any graph outputs, so we can check output edges.
if (node.GetOutputEdgesCount() != 1) {
return false;
}
const NodeArg* node_output = node.OutputDefs()[0];
const Node& output_node = node.OutputEdgesBegin()->GetNode();
// Fusion can be applied if the only output node is a Sum with exactly two inputs.
if (
!graph_utils::IsSupportedOptypeVersionAndDomain(output_node, "Sum", {1, 6, 8, 13}) ||
output_node.InputDefs().size() != 2 ||
// Make sure the two nodes do not span execution providers.
output_node.GetExecutionProviderType() != node.GetExecutionProviderType()) {
return false;
}
// Sum must have the same input types, data types do not need to be checked.
// Get the other sum input.
const NodeArg* other_sum_input = nullptr;
if (output_node.InputDefs()[0]->Name() == node_output->Name()) {
other_sum_input = output_node.InputDefs()[1];
} else {
other_sum_input = output_node.InputDefs()[0];
}
ORT_ENFORCE(other_sum_input != nullptr);
// valid bias_shapes are (N) or (1, N) or (M, 1) or (M, N) as
// GEMM only supports unidirectional broadcast on the bias input C
//
// TODO: verify if scalar shape works here together with matmul_add_fusion.
if (!other_sum_input->Shape()) {
return false;
}
if (!node_output->Shape() || node_output->Shape()->dim_size() != 2) {
return false;
}
const auto& bias_shape = *other_sum_input->Shape();
const auto& matmul_output_shape = *node_output->Shape();
const auto& M = matmul_output_shape.dim()[0];
const auto& N = matmul_output_shape.dim()[1];
auto dim_has_value_1 = [](const TensorShapeProto_Dimension& dim) {
return dim.has_dim_value() && dim.dim_value() == 1;
};
const bool valid = ((bias_shape.dim_size() == 1 && bias_shape.dim()[0] == N) ||
(bias_shape.dim_size() == 2 && dim_has_value_1(bias_shape.dim()[0]) && bias_shape.dim()[1] == N) ||
(bias_shape.dim_size() == 2 && bias_shape.dim()[0] == M &&
(dim_has_value_1(bias_shape.dim()[1]) || bias_shape.dim()[1] == N)));
if (!valid) {
return false;
}
// If none of the above checks specify render this fusion invalid, fusion is valid.
return true;
}
} // namespace onnxruntime
| 45.857143
| 135
| 0.697819
|
lchang20
|
3f2d6500f38024628daad9287e1fb6cc9e21d5b0
| 12,101
|
cpp
|
C++
|
thirdparty/geogram/src/lib/exploragram/hexdom/mesh_inspector.cpp
|
AmericaMakes/OASIS-marcwang
|
7aa10040251d7a1b807a773a45d123e1a52faac5
|
[
"BSD-2-Clause"
] | 1
|
2021-03-07T14:47:09.000Z
|
2021-03-07T14:47:09.000Z
|
thirdparty/geogram/src/lib/exploragram/hexdom/mesh_inspector.cpp
|
AmericaMakes/OASIS-marcwang
|
7aa10040251d7a1b807a773a45d123e1a52faac5
|
[
"BSD-2-Clause"
] | null | null | null |
thirdparty/geogram/src/lib/exploragram/hexdom/mesh_inspector.cpp
|
AmericaMakes/OASIS-marcwang
|
7aa10040251d7a1b807a773a45d123e1a52faac5
|
[
"BSD-2-Clause"
] | 1
|
2021-03-07T00:24:57.000Z
|
2021-03-07T00:24:57.000Z
|
/*
* OGF/Graphite: Geometry and Graphics Programming Library + Utilities
* Copyright (C) 2000-2015 INRIA - Project ALICE
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact for Graphite: Bruno Levy - Bruno.Levy@inria.fr
* Contact for this Plugin: Nicolas Ray - nicolas.ray@inria.fr
*
* Project ALICE
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
* Note that the GNU General Public License does not permit incorporating
* the Software into proprietary programs.
*
* As an exception to the GPL, Graphite can be linked with the following
* (non-GPL) libraries:
* Qt, tetgen, SuperLU, WildMagic and CGAL
*/
#include <exploragram/hexdom/mesh_inspector.h>
#include <exploragram/hexdom/basic.h>
#include <exploragram/hexdom/extra_connectivity.h>
#include <geogram/mesh/mesh_tetrahedralize.h>
#include <geogram/delaunay/delaunay.h>
namespace GEO {
bool volume_boundary_is_manifold(Mesh* m, std::string& msg) {
m->cells.compute_borders();
if (!surface_is_manifold(m, msg)) {
return false;
}
m->facets.clear();
return true;
}
bool have_negative_tet_volume(Mesh*m) {
FOR(c, m->cells.nb()) {
vec3 A = X(m)[m->cells.vertex(c, 0)];
vec3 B = X(m)[m->cells.vertex(c, 1)];
vec3 C = X(m)[m->cells.vertex(c, 2)];
vec3 D = X(m)[m->cells.vertex(c, 3)];
double vol = dot(cross(B - A, C - A), D - A);
if (vol < 0) {
Attribute<double> signed_volume(m->cells.attributes(), "signed_volume");
signed_volume[c] = vol;
return true;
}
}
return false;
}
bool surface_is_tetgenifiable(Mesh* m) {
Mesh copy;
copy.copy(*m);
create_non_manifold_facet_adjacence(©);
copy.facets.triangulate();
try {
mesh_tetrahedralize(copy, false, false, 1.);
}
catch (const GEO::Delaunay::InvalidInput& error_report) {
FOR(i, error_report.invalid_facets.size()) {
plop(error_report.invalid_facets[i]);
}
return false;
}
return true;
}
bool volume_is_tetgenifiable(Mesh* m) {
Mesh copy;
copy.copy(*m);
copy.edges.clear();
copy.cells.compute_borders();
copy.cells.clear();
return surface_is_tetgenifiable(©);
}
bool surface_is_manifold(Mesh* m, std::string& msg) {
if (m->facets.nb() == 0) return true;
{
// check for duplicated corners around a face
FOR(f, m->facets.nb()) FOR(fc, m->facets.nb_corners(f))
if (m->facets.vertex(f, fc) == m->facets.vertex(f, next_mod(fc, m->facets.nb_corners(f)))) {
msg = "duplicated corner detected on (face = " + String::to_string(f) + " , local corner = " + String::to_string(fc) + " , vertex = " +
String::to_string(m->facets.vertex(f, fc));
return false;
}
// output the type of surface
index_t nb_edges_par_facets = m->facets.nb_corners(0);
FOR(f, m->facets.nb()) if (m->facets.nb_corners(f) != nb_edges_par_facets) nb_edges_par_facets = index_t(-1);
if (nb_edges_par_facets != index_t(-1)) plop(nb_edges_par_facets);
// check if the mesh is manifold
Attribute<int> nb_opp(m->facet_corners.attributes(), "nb_opp");
Attribute<int> nb_occ(m->facet_corners.attributes(), "nb_occ");
FOR(h, m->facet_corners.nb()) { nb_opp[h] = 0; nb_occ[h] = 0; }
// edge connectivity
FacetsExtraConnectivity fec(m);
int nb_0_opp = 0;
int nb_1_opp = 0;
int nb_multiple_opp = 0;
int nb_duplicated_edge = 0;
FOR(h, m->facet_corners.nb()) {
index_t cir = h;
index_t result = NOT_AN_ID; // not found
do {
index_t candidate = fec.prev(cir);
if ((fec.org(candidate) == fec.dest(h)) && (fec.dest(candidate) == fec.org(h))) {
nb_opp[h]++;
if (result == NOT_AN_ID) result = candidate;
else nb_multiple_opp++;
}
if (cir != h && fec.dest(h) == fec.dest(cir)) {
nb_duplicated_edge++;
nb_occ[h]++;
}
cir = fec.c2c[cir];
} while (cir != h);
if (result == NOT_AN_ID)nb_0_opp++;
else nb_1_opp++;
}
if (nb_0_opp > 0) {
msg = "surface have halfedges without opposite, nb= " + String::to_string(nb_0_opp);
return false;
}
if (nb_multiple_opp > 0) {
msg = "surface have halfedge with more than 2 opposites, nb= " + String::to_string(nb_multiple_opp);
return false;
}
if (nb_duplicated_edge > 0) {
msg = "halfedge appears in more than one facet, nb= " + String::to_string(nb_duplicated_edge);
return false;
}
// check for non manifold vertices
Attribute<bool> nonmanifold(m->vertices.attributes(), "nonmanifold");
FOR(v, m->vertices.nb()) nonmanifold[v] = false;
FOR(h, m->facet_corners.nb()) {
if (nb_opp[h] != 1 || nb_occ[h] != 0)
nonmanifold[fec.org(h)] = true;
}
vector<int> val(m->vertices.nb(), 0);
FOR(f, m->facets.nb()) FOR(lc, m->facets.nb_vertices(f)) val[m->facets.vertex(f, lc)]++;
FOR(h, m->facet_corners.nb()) {
int nb = 0;
index_t cir = h;
do {
nb++;
cir = fec.next_around_vertex(cir);// fec.c2c[cir];
} while (cir != h);
if (nb != val[fec.org(h)]) {
msg = "Vertex " + String::to_string(fec.org(h)) + " is non manifold ";
return false;
}
}
}
m->vertices.attributes().delete_attribute_store("nonmanifold");
m->facet_corners.attributes().delete_attribute_store("nb_opp");
m->facet_corners.attributes().delete_attribute_store("nb_occ");
return true;
}
void get_facet_stats(Mesh* m, const char * msg, bool export_attribs) {
geo_argused(export_attribs);
GEO::Logger::out("HexDom") << "-----------------------------------------" << std::endl;
GEO::Logger::out("HexDom") << "get_facet_stats " << msg << std::endl;
GEO::Logger::out("HexDom") << "-----------------------------------------" << std::endl;
{
Attribute<int> nb_opp(m->facet_corners.attributes(), "nb_opp");
Attribute<int> nb_occ(m->facet_corners.attributes(), "nb_occ");
FOR(h, m->facet_corners.nb()) nb_opp[h] = 0;
// edge connectivity
FacetsExtraConnectivity fec(m);
int nb_0_opp = 0;
int nb_1_opp = 0;
int nb_multiple_opp = 0;
int nb_duplicated_edge = 0;
FOR(h, m->facet_corners.nb()) {
index_t cir = h;
index_t result = NOT_AN_ID; // not found
do {
index_t candidate = fec.prev(cir);
if ((fec.org(candidate) == fec.dest(h)) && (fec.dest(candidate) == fec.org(h))) {
nb_opp[h]++;
if (result == NOT_AN_ID) result = candidate;
else nb_multiple_opp++;
}
if (cir != h && fec.dest(h) == fec.dest(cir)) {
nb_duplicated_edge++;
nb_occ[h]++;
}
cir = fec.c2c[cir];
} while (cir != h);
if (result == NOT_AN_ID)nb_1_opp++;
else nb_0_opp++;
}
FOR(f, m->facets.nb()) FOR(fc, m->facets.nb_corners(f))
if (m->facets.vertex(f, fc) == m->facets.vertex(f, next_mod(fc, m->facets.nb_corners(f))))
GEO::Logger::out("HexDom") << "Duplicated vertex found at facet #" << f << ", local corner= " << fc << " and vertex is " << m->facets.vertex(f, fc) << std::endl;
plop(nb_0_opp);
plop(nb_1_opp);
plop(nb_multiple_opp);
plop(nb_duplicated_edge);
// check for non manifold vertices
Attribute<bool> nonmanifold(m->vertices.attributes(), "nonmanifold");
FOR(v, m->vertices.nb()) nonmanifold[v] = false;
FOR(h, m->facet_corners.nb()) {
if (nb_opp[h] != 1 || nb_occ[h] != 0)
nonmanifold[fec.org(h)] = true;
}
vector<int> val(m->vertices.nb(), 0);
FOR(f, m->facets.nb()) FOR(lc, m->facets.nb_vertices(f)) val[m->facets.vertex(f, lc)]++;
FOR(h, m->facet_corners.nb()) {
int nb = 0;
index_t cir = h;
do {
nb++;
cir = fec.c2c[cir];
} while (cir != h);
if (nb != val[fec.org(h)]) {
GEO::Logger::out("HexDom") << "Vertex " << fec.org(h) << " is non-manifold !!" << std::endl;
nonmanifold[fec.org(h)] = true;
}
}
}
m->vertices.attributes().delete_attribute_store("nonmanifold");
m->facet_corners.attributes().delete_attribute_store("nb_opp");
m->facet_corners.attributes().delete_attribute_store("nb_occ");
}
double tet_vol(vec3 A, vec3 B, vec3 C, vec3 D) {
B = B - A;
C = C - A;
D = D - A;
return (1. / 6.)*dot(D, cross(B, C));
}
void get_hex_proportion(Mesh*m, double &nb_hex_prop, double &vol_hex_prop) {
int nb_tets = 0;
int nb_hexs = 0;
double vol_tets = 0;
double vol_hexs = 0;
FOR(c, m->cells.nb()) if (m->cells.nb_facets(c) == 4) {
vol_tets += tet_vol(X(m)[m->cells.vertex(c, 0)], X(m)[m->cells.vertex(c, 1)], X(m)[m->cells.vertex(c, 2)], X(m)[m->cells.vertex(c, 3)]);
nb_tets++;
}
FOR(c, m->cells.nb()) if (m->cells.nb_facets(c) == 6) {
vector<vec3> P(8);
FOR(cv, 8) P[cv] = X(m)[m->cells.vertex(c, cv)];
vol_hexs += tet_vol(P[0], P[3], P[2], P[6]);
vol_hexs += tet_vol(P[0], P[7], P[3], P[6]);
vol_hexs += tet_vol(P[0], P[7], P[6], P[4]);
vol_hexs += tet_vol(P[0], P[1], P[3], P[7]);
vol_hexs += tet_vol(P[0], P[1], P[7], P[5]);
vol_hexs += tet_vol(P[0], P[5], P[7], P[4]);
nb_hexs++;
}
if (nb_hexs + nb_tets>0) nb_hex_prop = double(nb_hexs) / double(nb_hexs + nb_tets);
if (nb_hexs + nb_tets>0) vol_hex_prop = double(vol_hexs) / double(vol_hexs + vol_tets);
}
}
| 40.471572
| 184
| 0.514338
|
AmericaMakes
|
3f3428b521990d6815e3af30a408b9e17e03bd96
| 4,464
|
cpp
|
C++
|
sources/cpp/omp/omp003.cpp
|
xunilrj/sandbox
|
f92c12f83433cac01a885585e41c02bb5826a01f
|
[
"Apache-2.0"
] | 7
|
2017-04-01T17:18:35.000Z
|
2022-01-12T05:23:23.000Z
|
sources/cpp/omp/omp003.cpp
|
xunilrj/sandbox
|
f92c12f83433cac01a885585e41c02bb5826a01f
|
[
"Apache-2.0"
] | 6
|
2020-05-24T13:36:50.000Z
|
2022-02-15T06:44:20.000Z
|
sources/cpp/omp/omp003.cpp
|
xunilrj/sandbox
|
f92c12f83433cac01a885585e41c02bb5826a01f
|
[
"Apache-2.0"
] | 2
|
2018-09-20T01:07:39.000Z
|
2019-02-22T14:55:38.000Z
|
#include <iostream>
#include <sstream>
#include <omp.h>
#include <atomic>
void runIncrement()
{
const int LOOPSIZE = 1000000;
int A = 0;
int B = 0;
int C = 0;
std::atomic<int> D {0}; //https://stackoverflow.com/questions/21554099/can-stdatomic-be-safely-used-with-openmp
std::cout << "Increment ------------------------------" << std::endl;
#pragma omp parallel for shared(A,B,C,D)
for (int i = 0;i < LOOPSIZE; ++i)
{
++A;
#pragma omp critical
{
++B;
}
#pragma omp atomic
++C;
++D;
}
std::cout << "correct: " << LOOPSIZE << std::endl;
std::cout << "A: " << A << " [" << (A == LOOPSIZE) << "]" << std::endl;
std::cout << "B: " << B << " [" << (B == LOOPSIZE) << "]" << std::endl;
std::cout << "C: " << C << " [" << (C == LOOPSIZE) << "]" << std::endl;
std::cout << "D: " << D << " [" << (D == LOOPSIZE) << "]" << std::endl;
}
void runBinaryOperatorEqual()
{
const int LOOPSIZE = 1000000;
srand(time(NULL));
int step = rand() % 9 + 1;
int A = 0;
int B = 0;
int C = 0;
std::atomic<int> D {0}; //https://stackoverflow.com/questions/21554099/can-stdatomic-be-safely-used-with-openmp
std::cout << "BinaryOperatorEqual ------------------------------" << std::endl;
#pragma omp parallel for shared(A,B,C,D)
for (int i = 0;i < LOOPSIZE; ++i)
{
A+=step;
#pragma omp critical
{
B+=step;
}
#pragma omp atomic
C+=step;
D+=step;
}
std::cout << "correct: " << LOOPSIZE*step << std::endl;
std::cout << "A: " << A << " [" << (A == LOOPSIZE*step) << "]" << std::endl;
std::cout << "B: " << B << " [" << (B == LOOPSIZE*step) << "]" << std::endl;
std::cout << "C: " << C << " [" << (C == LOOPSIZE*step) << "]" << std::endl;
std::cout << "D: " << D << " [" << (D == LOOPSIZE*step) << "]" << std::endl;
}
void runReadModifyWrite()
{
const int LOOPSIZE = 1000000;
srand(time(NULL));
int step = rand() % 9 + 1;
int A = 0;
int B = 0;
int C = 0;
std::atomic<int> D {0}; //https://stackoverflow.com/questions/21554099/can-stdatomic-be-safely-used-with-openmp
std::atomic<int> E {0};
std::atomic<int> ECount {0};
std::cout << "ReadModifyWrite ------------------------------" << std::endl;
#pragma omp parallel for shared(A,B,C,D)
for (int i = 0;i < LOOPSIZE; ++i)
{
A = A + step + 10;
#pragma omp critical
{
B = B + step + 10;
}
//omp003.cpp:99:24: error: the statement for 'atomic' must be an
//expression statement of form '++x;', '--x;', 'x++;', 'x--;',
//'x binop= expr;', 'x = x binop expr' or 'x = expr binop x',
// where x is an l-value expression with scalar type
//#pragma omp atomic
//C = (C + step) * 2;
// Incorrect use of atomic in this case
// others are fine.
// See correcy way below.
D = D + step + 10;
//https://stackoverflow.com/questions/25199838/understanding-stdatomiccompare-exchange-weak-in-c11
//https://preshing.com/20150402/you-can-do-any-kind-of-atomic-read-modify-write-operation/
int oldE = E.load();
int newE;
do
{
++ECount; // <- measure how many times compare_exchange_weak will fail
newE = oldE + step + 10; // <- what we really want to do
} while(!E.compare_exchange_weak(oldE, newE));
}
std::cout << "correct: " << LOOPSIZE*(step+10) << std::endl;
std::cout << "A: " << A << " [" << (A == LOOPSIZE*(step+10)) << "]" << std::endl;
std::cout << "B: " << B << " [" << (B == LOOPSIZE*(step+10)) << "]" << std::endl;
std::cout << "C: " << C << " [" << (C == LOOPSIZE*(step+10)) << "]" << std::endl;
std::cout << "D: " << D << " [" << (D == LOOPSIZE*(step+10)) << "]" << std::endl;
std::cout << "E: " << E << " [" << (E == LOOPSIZE*(step+10)) << "]" << std::endl;
std::cout << "E conflicts: " << ECount - LOOPSIZE << "(" << (ECount - LOOPSIZE) * 100.0 / LOOPSIZE << "%)" << std::endl;
}
int main(int argc, char** argv)
{
if(argc > 1)
{
std::stringstream ss;
ss << argv[1];
int numThreads;
ss >> numThreads;
omp_set_num_threads(numThreads);
}
runIncrement();
runBinaryOperatorEqual();
runReadModifyWrite();
}
| 30.367347
| 126
| 0.482751
|
xunilrj
|
27862f8f6280f51ab208695ec87fcc1b07641033
| 2,059
|
hh
|
C++
|
libsrc/spatialdata/spatialdb/TimeHistoryIO.hh
|
jedbrown/spatialdata
|
f18d34d92253986e8018f393201bf901e9667c2a
|
[
"MIT"
] | null | null | null |
libsrc/spatialdata/spatialdb/TimeHistoryIO.hh
|
jedbrown/spatialdata
|
f18d34d92253986e8018f393201bf901e9667c2a
|
[
"MIT"
] | null | null | null |
libsrc/spatialdata/spatialdb/TimeHistoryIO.hh
|
jedbrown/spatialdata
|
f18d34d92253986e8018f393201bf901e9667c2a
|
[
"MIT"
] | null | null | null |
// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
/** @file libsrc/spatialdb/TimeHistoryIO.h
*
* @brief C++ object for reading/writing time history files.
*/
#if !defined(spatialdata_spatialdb_timehistoryio_hh)
#define spatialdata_spatialdb_timehistoryio_hh
#include "spatialdbfwd.hh"
/// C++ object for reading/writing time history files.
class spatialdata::spatialdb::TimeHistoryIO
{ // class TimeHistoryIO
public :
// PUBLIC METHODS /////////////////////////////////////////////////////
/** Read time history file.
*
* @param time Time stamps.
* @param amplitude Amplitude values in time history.
* @param npts Number of points in time history.
* @param filename Filename for time history.
*/
static
void read(double** time,
double** amplitude,
int* npts,
const char* filename);
/** Read time history file. Number of time history points given by
* nptsT must equal nptsA.
*
* @param time Time stamps.
* @param nptsT Number of points in time history.
* @param amplitude Amplitude values in time history.
* @param nptsA Number of points in time history.
* @param timeUnits Units associated with time stamps.
* @param filename Filename for time history.
*/
static
void write(const double* time,
const int nptsT,
const double* amplitude,
const int nptsA,
const char* timeUnits,
const char* filename);
private :
// PRIVATE MEMBERS ////////////////////////////////////////////////////
static const char* HEADER; ///< Header for time history files.
}; // class TimeHistoryIO
#endif // spatialdata_spatialdb_timehistoryio_hh
// End of file
| 27.092105
| 73
| 0.605634
|
jedbrown
|
278b96e92f4373c89dc965d0fbee66db9fe66e19
| 1,067
|
hpp
|
C++
|
src/demo/fly_sorter/identity_tracker.hpp
|
hhhHanqing/bias
|
ac409978ac0bfc6bc4cf8570bf7ce7509e81a219
|
[
"Apache-2.0"
] | 5
|
2020-07-23T18:59:08.000Z
|
2021-12-14T02:56:12.000Z
|
src/demo/fly_sorter/identity_tracker.hpp
|
hhhHanqing/bias
|
ac409978ac0bfc6bc4cf8570bf7ce7509e81a219
|
[
"Apache-2.0"
] | 4
|
2020-08-30T13:55:22.000Z
|
2022-03-24T21:14:15.000Z
|
src/demo/fly_sorter/identity_tracker.hpp
|
hhhHanqing/bias
|
ac409978ac0bfc6bc4cf8570bf7ce7509e81a219
|
[
"Apache-2.0"
] | 3
|
2020-10-04T17:53:15.000Z
|
2022-02-24T05:55:53.000Z
|
#ifndef IDENTITY_TRACKKER_HPP
#define IDENTITY_TRACKKER_HPP
#include "parameters.hpp"
#include "blob_finder.hpp"
#include <vector>
#include <memory>
#include <map>
class IdentityTracker
{
public:
IdentityTracker();
IdentityTracker(IdentityTrackerParam param);
void setParam(IdentityTrackerParam param);
void update(BlobFinderData &blodFinderData);
private:
bool isFirst_;
long idCounter_;
IdentityTrackerParam param_;
BlobFinderData blobFinderDataPrev_;
void assignBlobsGreedy(BlobFinderData &blobfinderData);
std::vector<std::vector<float>> getCostMatrix(BlobFinderData &blobFinderData);
float getCost(BlobData blobCurr, BlobData blobPrev);
std::map<int,BlobDataList::iterator> getIndexToBlobDataMap(
BlobFinderData &blobFinderData
);
};
int getNumberOkItems(BlobDataList blobDataList);
void printMatrix(std::vector<std::vector<float>> matrix);
#endif // ifndef IDENTITY_TRACKER_HPP
| 27.358974
| 87
| 0.686036
|
hhhHanqing
|
278ed8f8742fd69407d3c303a6a78863e35ff914
| 8,207
|
cpp
|
C++
|
NLoader/loadermain.cpp
|
NellaR1/NEPS
|
f8ea7181449a858bf660f58ef7c40c11d04b8bf1
|
[
"BSD-2-Clause"
] | null | null | null |
NLoader/loadermain.cpp
|
NellaR1/NEPS
|
f8ea7181449a858bf660f58ef7c40c11d04b8bf1
|
[
"BSD-2-Clause"
] | null | null | null |
NLoader/loadermain.cpp
|
NellaR1/NEPS
|
f8ea7181449a858bf660f58ef7c40c11d04b8bf1
|
[
"BSD-2-Clause"
] | null | null | null |
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#ifdef REQ_NET
#include "curl/curl.h"
#endif // REQ_NET
#include "resource.h"
#include "version.hpp"
using namespace std;
typedef HMODULE(__stdcall *PLOADLIBRARY)(LPCSTR);
typedef FARPROC(__stdcall *PGETPROCADDRESS)(HMODULE, LPCSTR);
typedef BOOL(__stdcall *DLLMAIN)(HMODULE, DWORD, LPVOID);
struct LOADERDATA
{
LPVOID ImageBase;
PIMAGE_NT_HEADERS NtHeaders;
PIMAGE_BASE_RELOCATION BaseReloc;
PIMAGE_IMPORT_DESCRIPTOR ImportDirectory;
PLOADLIBRARY fnLoadLibraryA;
PGETPROCADDRESS fnGetProcAddress;
};
static DWORD FindPID(wstring processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processSnapshot == INVALID_HANDLE_VALUE)
return 0;
Process32First(processSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processSnapshot);
return 0;
}
#ifdef REQ_NET
static BOOL RequestBinary(LPVOID out)
{
auto curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "");
curl_easy_cleanup(curl);
}
}
#endif // REQ_NET
BOOL __stdcall LibraryLoader(LPVOID memory)
{
LOADERDATA *LoaderParams = (LOADERDATA *)memory;
// Call TLS callbacks
#ifdef CALL_TLS
IMAGE_DATA_DIRECTORY pIDD = LoaderParams->NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
if (pIDD.VirtualAddress)
{
PIMAGE_TLS_DIRECTORY pITD = (PIMAGE_TLS_DIRECTORY)((LPBYTE)LoaderParams->ImageBase + pIDD.VirtualAddress);
if (pITD)
{
PIMAGE_TLS_CALLBACK *pITC = (PIMAGE_TLS_CALLBACK *)pITD->AddressOfCallBacks;
if (pITC)
{
while (*pITC)
{
(*pITC)((LPVOID)LoaderParams->ImageBase, DLL_PROCESS_ATTACH, NULL);
pITC++;
}
}
}
}
#endif // CALL_TLS
// ???1
PIMAGE_BASE_RELOCATION pIBR = LoaderParams->BaseReloc;
// Calculate the delta
DWORD delta = (DWORD)((LPBYTE)LoaderParams->ImageBase - LoaderParams->NtHeaders->OptionalHeader.ImageBase);
// ???1
while (pIBR->VirtualAddress)
{
if (pIBR->SizeOfBlock >= sizeof(IMAGE_BASE_RELOCATION))
{
int count = (pIBR->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
PWORD list = (PWORD)(pIBR + 1);
for (int i = 0; i < count; i++)
{
if (list[i])
{
PDWORD ptr = (PDWORD)((LPBYTE)LoaderParams->ImageBase + (pIBR->VirtualAddress + (list[i] & 0xFFF)));
*ptr += delta;
}
}
}
pIBR = (PIMAGE_BASE_RELOCATION)((LPBYTE)pIBR + pIBR->SizeOfBlock);
}
// Resolve DLL imports
PIMAGE_IMPORT_DESCRIPTOR pIID = LoaderParams->ImportDirectory;
while (pIID->Characteristics)
{
PIMAGE_THUNK_DATA OrigFirstThunk = (PIMAGE_THUNK_DATA)((LPBYTE)LoaderParams->ImageBase + pIID->OriginalFirstThunk);
PIMAGE_THUNK_DATA FirstThunk = (PIMAGE_THUNK_DATA)((LPBYTE)LoaderParams->ImageBase + pIID->FirstThunk);
HMODULE hModule = LoaderParams->fnLoadLibraryA((LPCSTR)LoaderParams->ImageBase + pIID->Name);
if (!hModule)
return FALSE;
while (OrigFirstThunk->u1.AddressOfData)
{
if (OrigFirstThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG)
{
// Import by ordinal
DWORD Function = (DWORD)LoaderParams->fnGetProcAddress(hModule,
(LPCSTR)(OrigFirstThunk->u1.Ordinal & 0xFFFF));
if (!Function)
return FALSE;
FirstThunk->u1.Function = Function;
} else
{
// Import by name
PIMAGE_IMPORT_BY_NAME pIBN = (PIMAGE_IMPORT_BY_NAME)((LPBYTE)LoaderParams->ImageBase + OrigFirstThunk->u1.AddressOfData);
DWORD Function = (DWORD)LoaderParams->fnGetProcAddress(hModule, (LPCSTR)pIBN->Name);
if (!Function)
return FALSE;
FirstThunk->u1.Function = Function;
}
OrigFirstThunk++;
FirstThunk++;
}
pIID++;
}
// Call the entry point if it exists
if (LoaderParams->NtHeaders->OptionalHeader.AddressOfEntryPoint)
{
DLLMAIN EntryPoint = (DLLMAIN)((LPBYTE)LoaderParams->ImageBase + LoaderParams->NtHeaders->OptionalHeader.AddressOfEntryPoint);
// Call the entry point with exclusive parameters
return EntryPoint((HMODULE)LoaderParams->ImageBase, DLL_PROCESS_ATTACH | SIGNATURE, NULL);
}
return FALSE;
}
DWORD __stdcall Stub()
{
return 0;
}
BOOL APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdLine, int cmdShow)
{
// Find CS:GO
DWORD ProcessID = FindPID(L"csgo.exe");
if (!ProcessID)
{
MessageBoxA(NULL, "Falied to load NEPS.\nYou need to run CS:GO before running the loader.", "NEPS", MB_OK | MB_ICONERROR);
return FALSE;
}
LOADERDATA LoaderParams;
HMODULE hModule = GetModuleHandleA(NULL);
HRSRC hResource = FindResourceA(hModule, MAKEINTRESOURCEA(IDR_BIN1), "BIN");
HGLOBAL hResData = LoadResource(hModule, hResource);
PVOID Buffer = LockResource(hResData);
// Target DLL's DOS Header
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)Buffer;
// Target DLL's NT Headers
PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)Buffer + pDosHeader->e_lfanew);
// Opening target process.
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);
// Allocating memory for the DLL
PVOID ExecutableImage = VirtualAllocEx(hProcess, NULL, pNtHeaders->OptionalHeader.SizeOfImage,
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
// Copy the headers to target process
WriteProcessMemory(hProcess, ExecutableImage, Buffer,
pNtHeaders->OptionalHeader.SizeOfHeaders, NULL);
// Target DLL's Section Header
PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER)(pNtHeaders + 1);
// Copying sections of the dll to the target process
for (int i = 0; i < pNtHeaders->FileHeader.NumberOfSections; i++)
{
WriteProcessMemory(hProcess, (PVOID)((LPBYTE)ExecutableImage + pSectHeader[i].VirtualAddress),
(PVOID)((LPBYTE)Buffer + pSectHeader[i].PointerToRawData), pSectHeader[i].SizeOfRawData, NULL);
}
// Allocate memory for the loader code.
PVOID LoaderMemory = VirtualAllocEx(hProcess, NULL, 4096, MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
LoaderParams.ImageBase = ExecutableImage;
LoaderParams.NtHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)ExecutableImage + pDosHeader->e_lfanew);
LoaderParams.BaseReloc = (PIMAGE_BASE_RELOCATION)((LPBYTE)ExecutableImage
+ pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);
LoaderParams.ImportDirectory = (PIMAGE_IMPORT_DESCRIPTOR)((LPBYTE)ExecutableImage
+ pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
LoaderParams.fnLoadLibraryA = LoadLibraryA;
LoaderParams.fnGetProcAddress = GetProcAddress;
// Write the loader information to target process
WriteProcessMemory(hProcess, LoaderMemory, &LoaderParams, sizeof(LOADERDATA),
NULL);
// Write the loader code to target process
WriteProcessMemory(hProcess, (PVOID)((LOADERDATA *)LoaderMemory + 1), LibraryLoader,
(DWORD)Stub - (DWORD)LibraryLoader, NULL);
// Create a remote thread to execute the loader code
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)((LOADERDATA *)LoaderMemory + 1),
LoaderMemory, 0, NULL);
// Wait for the loader to finish executing
WaitForSingleObject(hThread, INFINITE);
// Get loader's return value to determine DllMain's return value
DWORD dwReturnValue = 0;
GetExitCodeThread(hThread, &dwReturnValue);
// Inform user about errors
if (!dwReturnValue) MessageBoxA(NULL, "Falied to load NEPS.\nTry running the loader with administrator privileges.", "NEPS", MB_OK | MB_ICONERROR);
else MessageBoxA(NULL, "Success! NEPS is now loaded.", "NEPS", MB_OK | MB_ICONINFORMATION);
// Free the allocated loader code
VirtualFreeEx(hProcess, LoaderMemory, 0, MEM_RELEASE);
FreeResource(hResData);
return TRUE;
}
| 30.623134
| 149
| 0.7256
|
NellaR1
|
2793ae74e55517111e854a55bf1617dc3554c5a7
| 1,383
|
cpp
|
C++
|
lib/socket_server.cpp
|
itsPG/asiod
|
29b56947ed1021f6d45a1275ef7b23fde7b94511
|
[
"MIT"
] | 2
|
2019-01-29T08:17:19.000Z
|
2019-01-29T08:52:20.000Z
|
lib/socket_server.cpp
|
itsPG/asiod
|
29b56947ed1021f6d45a1275ef7b23fde7b94511
|
[
"MIT"
] | null | null | null |
lib/socket_server.cpp
|
itsPG/asiod
|
29b56947ed1021f6d45a1275ef7b23fde7b94511
|
[
"MIT"
] | null | null | null |
// by PG, MIT license.
// this repo is for practicing boost::asio, not well tested, use it at your own risk.
#include "socket_server.h"
#include <cstdio>
#include "packet.h"
#include "session.h"
namespace PG {
socket_server::socket_server(asio::io_context::strand& strand, string path)
: strand_{strand}
, path_{std::move(path)}
{
std::remove(path_.c_str());
listen();
}
socket_server::~socket_server()
{
std::remove(path_.c_str());
}
void socket_server::listen()
{
cout << "socket_server::listen()" << endl;
asio::spawn(strand_, [&](asio::yield_context yield) {
asio::local::stream_protocol::acceptor acceptor{strand_.context(),
asio::local::stream_protocol::endpoint{path_}};
asio::local::stream_protocol::socket socket{strand_.context()};
while (true) {
boost::system::error_code error;
acceptor.async_accept(socket, yield[error]);
if (error) {
cout << "accept error" << endl;
} else {
cout << "accept one connection" << endl;
start_session(std::move(socket));
}
}
});
}
void socket_server::start_session(asio::local::stream_protocol::socket socket)
{
std::make_shared<session>(strand_, std::move(socket))->start();
}
} // namespace PG
| 25.611111
| 103
| 0.591468
|
itsPG
|
2793c2a77cf4a5ac7aee8652fb62a6f3c0de1315
| 512
|
cpp
|
C++
|
PD/PD_HW3_1.cpp
|
A2Zntu/DSPA
|
955202438ef2e0c963f98a0666cb6e7e30aa3e7a
|
[
"MIT"
] | null | null | null |
PD/PD_HW3_1.cpp
|
A2Zntu/DSPA
|
955202438ef2e0c963f98a0666cb6e7e30aa3e7a
|
[
"MIT"
] | null | null | null |
PD/PD_HW3_1.cpp
|
A2Zntu/DSPA
|
955202438ef2e0c963f98a0666cb6e7e30aa3e7a
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
int totalLen = 0, maxStop = 0, startStop = 0, endStop = 0;
cin >> totalLen >> maxStop >> startStop >> endStop;
int** array = new int*[totalLen-1];
for(int i = 0; i < totalLen-1; ++i)
array[i] = new int[totalLen-1];
for(int j = 0; j <= i; j++ ){
cin >> array[i][j];
}
}
cout << endl;
for(int i = 0; i < totalLen-1; i++){
for(int j = 0; j <= i; j++ ){
cout << array[i][j];
}
cout << endl;
}
cout << endl;
return 0;
}
| 21.333333
| 59
| 0.521484
|
A2Zntu
|
27968bd02dbc519b7804b0cfac104f9ae9e73ca1
| 438
|
hpp
|
C++
|
graphics-library/include/scene/scene_shape.hpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
graphics-library/include/scene/scene_shape.hpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
graphics-library/include/scene/scene_shape.hpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
#pragma once
#include "geometry/shape.hpp"
#include "scene/scene_object.hpp"
namespace gl::scene {
class SceneShape : public SceneObject {
public:
static std::shared_ptr<SceneShape> create(const std::shared_ptr<geometry::Shape> &shape);
void drawSelf() const;
private:
std::shared_ptr<geometry::Shape> m_shape;
SceneShape(const std::shared_ptr<geometry::Shape> &shape);
};
}
| 29.2
| 98
| 0.657534
|
thetorine
|
27970b29072df60fbd329ebebae747b073c353d1
| 102,344
|
cpp
|
C++
|
net/config/netoc/netoc.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
net/config/netoc/netoc.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
net/config/netoc/netoc.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1997.
//
// File: N E T O C . C P P
//
// Contents: Functions for handling installation and removal of optional
// networking components.
//
// Notes:
//
// Author: danielwe 28 Apr 1997
//
//----------------------------------------------------------------------------
#include "pch.h"
#pragma hdrstop
#include "lancmn.h"
#include "ncatlui.h"
#include "nccm.h"
#include "ncdhcps.h"
#include "ncias.h"
#include "ncmisc.h"
#include "ncmsz.h"
#include "ncnetcfg.h"
#include "ncnetcon.h"
#include "ncoc.h"
#include "ncperms.h"
#include "ncreg.h"
#include "ncsetup.h"
#include "ncsfm.h"
#include "ncstring.h"
#include "ncsvc.h"
#include "ncxbase.h"
#include "netcfgn.h"
#include "netcon.h"
#include "netoc.h"
#include "netocp.h"
#include "netocx.h"
#include "resource.h"
#include "netocmsg.h"
//
// External component install functions.
// Add an entry in this table for each component that requires additional,
// non-common installation support.
//
// NOTE: The component name should match the section name in the INF.
//
#pragma BEGIN_CONST_SECTION
static const OCEXTPROCS c_aocepMap[] =
{
{ L"MacSrv", HrOcExtSFM },
{ L"DHCPServer", HrOcExtDHCPServer },
{ L"NetCMAK", HrOcExtCMAK },
{ L"NetCPS", HrOcExtCPS },
{ L"WINS", HrOcExtWINS },
{ L"DNS", HrOcExtDNS },
{ L"SNMP", HrOcExtSNMP },
{ L"IAS", HrOcExtIAS },
};
#pragma END_CONST_SECTION
static const INT c_cocepMap = celems(c_aocepMap);
// generic strings
static const WCHAR c_szUninstall[] = L"Uninstall";
static const WCHAR c_szServices[] = L"StartServices";
static const WCHAR c_szDependOnComp[] = L"DependOnComponents";
static const WCHAR c_szVersionSection[] = L"Version";
static const WCHAR c_szProvider[] = L"Provider";
static const WCHAR c_szDefManu[] = L"Unknown";
static const WCHAR c_szInfRef[] = L"SubCompInf";
static const WCHAR c_szDesc[] = L"OptionDesc";
static const WCHAR c_szNoDepends[] = L"NoDepends";
// static-IP verification
static const WCHAR c_szTcpipInterfacesPath[] =
L"System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
static const WCHAR c_szEnableDHCP[] = L"EnableDHCP";
extern const WCHAR c_szOcMainSection[];
static const DWORD c_dwUpgradeMask = SETUPOP_WIN31UPGRADE |
SETUPOP_WIN95UPGRADE |
SETUPOP_NTUPGRADE;
OCM_DATA g_ocmData;
typedef list<NETOCDATA*> ListOcData;
ListOcData g_listOcData;
//+---------------------------------------------------------------------------
//
// Function: PnocdFindComponent
//
// Purpose: Looks for the given component name in the list of known
// components.
//
// Arguments:
// pszComponent [in] Name of component to lookup.
//
// Returns: Pointer to component's data.
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
NETOCDATA *PnocdFindComponent(PCWSTR pszComponent)
{
ListOcData::iterator iterList;
for (iterList = g_listOcData.begin();
iterList != g_listOcData.end();
iterList++)
{
NETOCDATA * pnocd;
pnocd = *iterList;
if (!lstrcmpiW(pnocd->pszComponentId, pszComponent))
{
return pnocd;
}
}
return NULL;
}
//+---------------------------------------------------------------------------
//
// Function: DeleteAllComponents
//
// Purpose: Removes all components from our list and frees all associated
// data.
//
// Arguments:
// (none)
//
// Returns: Nothing.
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
VOID DeleteAllComponents()
{
ListOcData::iterator iterList;
for (iterList = g_listOcData.begin();
iterList != g_listOcData.end();
iterList++)
{
NETOCDATA * pnocd;
pnocd = (*iterList);
if (pnocd->hinfFile)
{
SetupCloseInfFile(pnocd->hinfFile);
}
delete pnocd;
}
g_listOcData.erase(g_listOcData.begin(), g_listOcData.end());
}
//+---------------------------------------------------------------------------
//
// Function: AddComponent
//
// Purpose: Adds a component to our list.
//
// Arguments:
// pszComponent [in] Name of component to add.
// pnocd [in] Data to associate with component.
//
// Returns: S_OK if success, failure HRESULT otherwise
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
HRESULT AddComponent(PCWSTR pszComponent, NETOCDATA *pnocd)
{
HRESULT hr = S_OK;
Assert(pszComponent);
Assert(pnocd);
pnocd->pszComponentId = SzDupSz(pszComponent);
if (pnocd->pszComponentId)
{
try
{
g_listOcData.push_back(pnocd);
}
catch (bad_alloc)
{
MemFree(pnocd->pszComponentId);
hr = E_OUTOFMEMORY;
}
}
else
{
hr = E_OUTOFMEMORY;
}
TraceError("AddComponent", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: ParseAdditionalArguments
//
// Purpose: Parse additional commands following the /z option
// of sysocmgr.
//
// Arguments: Nothing.
//
// Returns: Nothing.
//
// Author: roelfc 19 Jul 2001
//
// Notes:
//
VOID ParseAdditionalArguments()
{
LPTSTR lpCmdLine = GetCommandLine();
TCHAR szTokens[] = TEXT("-/");
LPCTSTR lpszToken = NULL;
if (lpCmdLine)
{
// Search for additional parameters
lpszToken = wcspbrk(lpCmdLine, szTokens);
while (lpszToken != NULL)
{
// Check the correct option
switch (lpszToken[1])
{
case TEXT('z'):
case TEXT('Z'):
if ((lpszToken[2] == TEXT(':')) &&
(_wcsnicmp(&lpszToken[3],
SHOW_UNATTENDED_MESSAGES,
wcslen(SHOW_UNATTENDED_MESSAGES)) == 0) &&
(!iswgraph(lpszToken[3 + wcslen(SHOW_UNATTENDED_MESSAGES)])))
{
// Set the show unattended messages flag
g_ocmData.fShowUnattendedMessages = TRUE;
TraceTag(ttidNetOc, "Flag set to show messages in unattended mode");
}
break;
default:
break;
}
// Skip the last token found to find the next one
lpszToken = wcspbrk(&lpszToken[1], szTokens);
}
}
}
//+---------------------------------------------------------------------------
//
// Function: RegisterNetEventSource
//
// Purpose: Add netoc source name to the registry for
// event reporting.
//
// Arguments: Nothing.
//
// Returns: TRUE if success, FALSE otherwise
//
// Author: roelfc 21 May 2001
//
// Notes:
//
BOOL RegisterNetEventSource()
{
HKEY hk;
BOOL fSuccess = TRUE;
// Check if the key already exists
if (ERROR_SUCCESS != RegOpenKey(HKEY_LOCAL_MACHINE,
NETOC_REGISTRY_NAME NETOC_SERVICE_NAME,
&hk))
{
DWORD dwData;
WCHAR szBuf[80];
// Create the key as a subkey under the Application
// key in the EventLog registry key.
if (RegCreateKey(HKEY_LOCAL_MACHINE,
NETOC_REGISTRY_NAME NETOC_SERVICE_NAME,
&hk))
{
TraceTag(ttidNetOc, "RegisterEventSource: Could not create the registry key.");
return FALSE;
}
// Set the name of the message file.
lstrcpyW(szBuf, NETOC_DLL_NAME);
// Add the name to the EventMessageFile subkey.
if (RegSetValueEx(hk, // subkey handle
L"EventMessageFile", // value name
0, // must be zero
REG_EXPAND_SZ, // value type
(LPBYTE) szBuf, // pointer to value data
(2 * lstrlenW(szBuf)) + 1)) // length of value data
{
TraceTag(ttidNetOc, "RegisterEventSource: Could not set the event message file.");
fSuccess = FALSE;
goto RegisterExit;
}
// Set the supported event types in the TypesSupported subkey.
dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |
EVENTLOG_INFORMATION_TYPE;
if (RegSetValueEx(hk, // subkey handle
L"TypesSupported", // value name
0, // must be zero
REG_DWORD, // value type
(LPBYTE) &dwData, // pointer to value data
sizeof(DWORD))) // length of value data
{
TraceTag(ttidNetOc, "RegisterEventSource: Could not set the supported types.");
fSuccess = FALSE;
}
}
RegisterExit:
RegCloseKey(hk);
// Return result
return fSuccess;
}
//+---------------------------------------------------------------------------
//
// Function: NetOcSetupProcHelper
//
// Purpose: Main entry point for optional component installs
//
// Arguments:
// pvComponentId [in] Component Id (string)
// pvSubcomponentId [in] Sub component Id (string)
// uFunction [in] Function being performed
// uParam1 [in] First param to function
// pvParam2 [in, out] Second param to function
//
// Returns: Win32 error if failure
//
// Author: danielwe 17 Dec 1997
//
// Notes:
//
DWORD NetOcSetupProcHelper(LPCVOID pvComponentId, LPCVOID pvSubcomponentId,
UINT uFunction, UINT uParam1, LPVOID pvParam2)
{
TraceFileFunc(ttidNetOc);
HRESULT hr = S_OK;
UINT uiFlags;
switch (uFunction)
{
case OC_PREINITIALIZE:
return HrOnPreInitializeComponent(uParam1);
case OC_QUERY_CHANGE_SEL_STATE:
TraceTag(ttidNetOc, "OC_QUERY_CHANGE_SEL_STATE: %S, %ld, 0x%08X.",
pvSubcomponentId ? pvSubcomponentId : L"null", uParam1,
pvParam2);
if (FHasPermission(NCPERM_AddRemoveComponents))
{
uiFlags = PtrToUlong(pvParam2);
hr = HrOnQueryChangeSelState(reinterpret_cast<PCWSTR>(pvSubcomponentId),
uParam1, uiFlags);
if (S_OK == hr)
{
return TRUE;
}
}
else
{
ReportErrorHr(hr,
IDS_OC_NO_PERMS,
g_ocmData.hwnd,
SzLoadIds(IDS_OC_GENERIC_COMP));
}
return FALSE;
case OC_QUERY_SKIP_PAGE:
TraceTag(ttidNetOc, "OC_QUERY_SKIP_PAGE: %ld", uParam1);
return FOnQuerySkipPage(static_cast<OcManagerPage>(uParam1));
case OC_WIZARD_CREATED:
TraceTag(ttidNetOc, "OC_WIZARD_CREATED: 0x%08X", pvParam2);
OnWizardCreated(reinterpret_cast<HWND>(pvParam2));
break;
case OC_INIT_COMPONENT:
TraceTag(ttidNetOc, "OC_INIT_COMPONENT: %S", pvSubcomponentId ?
pvSubcomponentId : L"null");
hr = HrOnInitComponent(reinterpret_cast<PSETUP_INIT_COMPONENT>(pvParam2));
break;
case OC_ABOUT_TO_COMMIT_QUEUE:
TraceTag(ttidNetOc, "OC_ABOUT_TO_COMMIT_QUEUE: %S", pvSubcomponentId ?
pvSubcomponentId : L"null");
hr = HrOnPreCommitFileQueue(reinterpret_cast<PCWSTR>(pvSubcomponentId));
break;
case OC_CALC_DISK_SPACE:
// Ignore return value for now. This is not fatal anyway.
(VOID) HrOnCalcDiskSpace(reinterpret_cast<PCWSTR>(pvSubcomponentId),
uParam1, reinterpret_cast<HDSKSPC>(pvParam2));
break;
case OC_QUERY_STATE:
return DwOnQueryState(reinterpret_cast<PCWSTR>(pvSubcomponentId),
uParam1 == OCSELSTATETYPE_FINAL);
case OC_QUEUE_FILE_OPS:
TraceTag(ttidNetOc, "OC_QUEUE_FILE_OPS: %S, 0x%08X", pvSubcomponentId ?
pvSubcomponentId : L"null",
pvParam2);
hr = HrOnQueueFileOps(reinterpret_cast<PCWSTR>(pvSubcomponentId),
reinterpret_cast<HSPFILEQ>(pvParam2));
break;
case OC_COMPLETE_INSTALLATION:
TraceTag(ttidNetOc, "OC_COMPLETE_INSTALLATION: %S, %S", pvComponentId ?
pvComponentId : L"null",
pvSubcomponentId ? pvSubcomponentId : L"null");
hr = HrOnCompleteInstallation(reinterpret_cast<PCWSTR>(pvComponentId),
reinterpret_cast<PCWSTR>(pvSubcomponentId));
break;
case OC_QUERY_STEP_COUNT:
return DwOnQueryStepCount(reinterpret_cast<PCWSTR>(pvSubcomponentId));
case OC_CLEANUP:
OnCleanup();
break;
default:
break;
}
if (g_ocmData.sic.HelperRoutines.SetReboot && (NETCFG_S_REBOOT == hr))
{
// Request a reboot. Note we don't return the warning as the OCM call
// below handles it. Fall through and return NO_ERROR.
//
g_ocmData.sic.HelperRoutines.SetReboot(
g_ocmData.sic.HelperRoutines.OcManagerContext,
FALSE);
}
else if (FAILED(hr))
{
if (!g_ocmData.fErrorReported)
{
PCWSTR pszSubComponentId = reinterpret_cast<PCWSTR>(pvSubcomponentId);
TraceError("NetOcSetupProcHelper", hr);
if (pszSubComponentId)
{
NETOCDATA * pnocd;
pnocd = PnocdFindComponent(pszSubComponentId);
if (HRESULT_FROM_WIN32(ERROR_CANCELLED) != hr)
{
ReportErrorHr(hr,
UiOcErrorFromHr(hr),
g_ocmData.hwnd,
(pnocd)?(pnocd->strDesc.c_str()):
(SzLoadIds(IDS_OC_GENERIC_COMP)));
}
}
}
TraceError("NetOcSetupProcHelper", hr);
return DwWin32ErrorFromHr(hr);
}
return NO_ERROR;
}
//+---------------------------------------------------------------------------
//
// Function: HrOnPreInitializeComponent
//
// Purpose: Handles the OC_PREINITIALIZE function message.
//
// Arguments:
// uModesSupported [in] Modes supported by OCM (see OCManager spec)
//
// Returns: Flag indicating mode supported by netoc
//
// Author: roelfc 19 Jul 2001
//
// Notes:
//
DWORD HrOnPreInitializeComponent (UINT uModesSupported)
{
RegisterNetEventSource();
// Parse the additional command line arguments specific for netoc
ParseAdditionalArguments();
return OCFLAG_UNICODE;
}
//+---------------------------------------------------------------------------
//
// Function: HrOnInitComponent
//
// Purpose: Handles the OC_INIT_COMPONENT function message.
//
// Arguments:
// psic [in] Setup data. (see OCManager spec)
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
HRESULT HrOnInitComponent (PSETUP_INIT_COMPONENT psic)
{
HRESULT hr = S_OK;
if (OCMANAGER_VERSION <= psic->OCManagerVersion)
{
psic->ComponentVersion = OCMANAGER_VERSION;
CopyMemory(&g_ocmData.sic, (LPVOID)psic, sizeof(SETUP_INIT_COMPONENT));
}
else
{
hr = HRESULT_FROM_WIN32(ERROR_CALL_NOT_IMPLEMENTED);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: OnWizardCreated
//
// Purpose: Handles the OC_WIZARD_CREATED function message.
//
// Arguments:
// hwnd [in] HWND of wizard (may not be NULL)
//
// Returns: Nothing.
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
VOID OnWizardCreated(HWND hwnd)
{
g_ocmData.hwnd = hwnd;
AssertSz(g_ocmData.hwnd, "Parent HWND is NULL!");
}
//+---------------------------------------------------------------------------
//
// Function: HrOnCalcDiskSpace
//
// Purpose: Handles the OC_CALC_DISK_SPACE function message.
//
// Arguments:
// pszSubComponentId [in] Name of component.
// fAdd [in] TRUE if disk space should be added to total
// FALSE if removed from total.
// hdskspc [in] Handle to diskspace struct.
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
HRESULT HrOnCalcDiskSpace(PCWSTR pszSubComponentId, BOOL fAdd,
HDSKSPC hdskspc)
{
HRESULT hr = S_OK;
DWORD dwErr;
NETOCDATA * pnocd;
pnocd = PnocdFindComponent(pszSubComponentId);
if (!pnocd)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
if (SUCCEEDED(hr))
{
TraceTag(ttidNetOc, "Calculating disk space for %S...",
pszSubComponentId);
hr = HrEnsureInfFileIsOpen(pszSubComponentId, *pnocd);
if (SUCCEEDED(hr))
{
if (fAdd)
{
dwErr = SetupAddInstallSectionToDiskSpaceList(hdskspc,
pnocd->hinfFile,
NULL,
pszSubComponentId,
0, 0);
}
else
{
dwErr = SetupRemoveInstallSectionFromDiskSpaceList(hdskspc,
pnocd->hinfFile,
NULL,
pszSubComponentId,
0, 0);
}
if (!dwErr)
{
hr = HrFromLastWin32Error();
}
}
}
TraceError("HrOnCalcDiskSpace", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: DwOnQueryState
//
// Purpose: Handles the OC_QUERY_STATE function message.
//
// Arguments:
// pszSubComponentId [in] Name of component.
// fFinal [in] TRUE if this is the final state query, FALSE
// if not
//
// Returns: SubcompOn - component should be checked "on"
// SubcompUseOcManagerDefault - use whatever OCManage thinks is
// the default
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
DWORD DwOnQueryState(PCWSTR pszSubComponentId, BOOL fFinal)
{
HRESULT hr = S_OK;
if (pszSubComponentId)
{
NETOCDATA * pnocd;
EINSTALL_TYPE eit;
pnocd = PnocdFindComponent(pszSubComponentId);
if (!pnocd)
{
pnocd = new NETOCDATA;
if(pnocd)
{
hr = AddComponent(pszSubComponentId, pnocd);
if (FAILED(hr))
{
TraceTag(ttidNetOc, "OC_QUERY_STATE: Failed to add component %s.",
pszSubComponentId);
delete pnocd;
pnocd = NULL;
}
}
}
if(pnocd)
{
if (fFinal)
{
if (pnocd->fFailedToInstall)
{
TraceTag(ttidNetOc, "OC_QUERY_STATE: %S failed to install so "
"we are turning it off", pszSubComponentId);
return SubcompOff;
}
}
else
{
hr = HrGetInstallType(pszSubComponentId, *pnocd, &eit);
if (SUCCEEDED(hr))
{
pnocd->eit = eit;
if ((eit == IT_INSTALL) || (eit == IT_UPGRADE))
{
TraceTag(ttidNetOc, "OC_QUERY_STATE: %S is ON",
pszSubComponentId);
return SubcompOn;
}
else if (eit == IT_REMOVE)
{
TraceTag(ttidNetOc, "OC_QUERY_STATE: %S is OFF",
pszSubComponentId);
return SubcompOff;
}
}
}
}
}
TraceTag(ttidNetOc, "OC_QUERY_STATE: %S is using default",
pszSubComponentId);
return SubcompUseOcManagerDefault;
}
//+---------------------------------------------------------------------------
//
// Function: HrEnsureInfFileIsOpen
//
// Purpose: Ensures that the INF file for the given component is open.
//
// Arguments:
// pszSubComponentId [in] Name of component.
// nocd [in, ref] Data associated with component.
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
HRESULT HrEnsureInfFileIsOpen(PCWSTR pszSubComponentId, NETOCDATA &nocd)
{
HRESULT hr = S_OK;
tstring strInf;
if (!nocd.hinfFile)
{
// Get component INF file name
hr = HrSetupGetFirstString(g_ocmData.sic.ComponentInfHandle,
pszSubComponentId, c_szInfRef,
&strInf);
if (SUCCEEDED(hr))
{
TraceTag(ttidNetOc, "Opening INF file %S...", strInf.c_str());
hr = HrSetupOpenInfFile(strInf.c_str(), NULL,
INF_STYLE_WIN4, NULL, &nocd.hinfFile);
if (SUCCEEDED(hr))
{
// Append in the layout.inf file
(VOID) SetupOpenAppendInfFile(NULL, nocd.hinfFile, NULL);
}
}
// This is a good time to cache away the component description as
// well.
(VOID) HrSetupGetFirstString(g_ocmData.sic.ComponentInfHandle,
pszSubComponentId, c_szDesc,
&nocd.strDesc);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrOnPreCommitFileQueue
//
// Purpose: Handles the OC_ABOUT_TO_COMMIT_QUEUE function message.
//
// Arguments:
// pszSubComponentId [in] Name of component.
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 9 Dec 1998
//
// Notes:
//
HRESULT HrOnPreCommitFileQueue(PCWSTR pszSubComponentId)
{
HRESULT hr = S_OK;
NETOCDATA * pnocd;
if (pszSubComponentId)
{
EINSTALL_TYPE eit;
pnocd = PnocdFindComponent(pszSubComponentId);
if (!pnocd)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
if (SUCCEEDED(hr))
{
hr = HrGetInstallType(pszSubComponentId, *pnocd, &eit);
if (SUCCEEDED(hr))
{
pnocd->eit = eit;
if (pnocd->eit == IT_REMOVE)
{
// Always use main install section
hr = HrStartOrStopAnyServices(pnocd->hinfFile,
pszSubComponentId, FALSE);
if (FAILED(hr))
{
// Don't report errors for non-existent services
if (HRESULT_FROM_WIN32(ERROR_SERVICE_DOES_NOT_EXIST) != hr)
{
// Don't bail removal if services couldn't be stopped.
if (!g_ocmData.fErrorReported)
{
// Report an error and continue the removal.
ReportErrorHr(hr,
IDS_OC_STOP_SERVICE_FAILURE,
g_ocmData.hwnd,
pnocd->strDesc.c_str());
}
}
hr = S_OK;
}
// We need to unregister DLLs before they get commited to the
// queue, otherwise we try to unregister a non-existent DLL.
if (SUCCEEDED(hr))
{
tstring strUninstall;
// Get the name of the uninstall section first
hr = HrSetupGetFirstString(pnocd->hinfFile,
pszSubComponentId,
c_szUninstall, &strUninstall);
if (SUCCEEDED(hr))
{
PCWSTR pszInstallSection;
pszInstallSection = strUninstall.c_str();
// Run the INF but only call the unregister function
//
hr = HrSetupInstallFromInfSection(g_ocmData.hwnd,
pnocd->hinfFile,
pszInstallSection,
SPINST_UNREGSVR,
NULL, NULL, 0, NULL,
NULL, NULL, NULL);
}
else
{
// Uninstall may not be present
hr = S_OK;
}
}
}
}
}
}
TraceError("HrOnPreCommitFileQueue", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrOnQueueFileOps
//
// Purpose: Handles the OC_QUEUE_FILE_OPS function message.
//
// Arguments:
// pszSubComponentId [in] Name of component.
// hfq [in] Handle to file queue struct.
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
HRESULT HrOnQueueFileOps(PCWSTR pszSubComponentId, HSPFILEQ hfq)
{
HRESULT hr = S_OK;
NETOCDATA * pnocd;
if (pszSubComponentId)
{
EINSTALL_TYPE eit;
pnocd = PnocdFindComponent(pszSubComponentId);
if (!pnocd)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
if (SUCCEEDED(hr))
{
hr = HrGetInstallType(pszSubComponentId, *pnocd, &eit);
if (SUCCEEDED(hr))
{
pnocd->eit = eit;
if ((pnocd->eit == IT_INSTALL) || (pnocd->eit == IT_UPGRADE) ||
(pnocd->eit == IT_REMOVE))
{
BOOL fSuccess = TRUE;
PCWSTR pszInstallSection;
tstring strUninstall;
AssertSz(hfq, "No file queue?");
hr = HrEnsureInfFileIsOpen(pszSubComponentId, *pnocd);
if (SUCCEEDED(hr))
{
if (pnocd->eit == IT_REMOVE)
{
// Get the name of the uninstall section first
hr = HrSetupGetFirstString(pnocd->hinfFile,
pszSubComponentId,
c_szUninstall,
&strUninstall);
if (SUCCEEDED(hr))
{
pszInstallSection = strUninstall.c_str();
}
else
{
if (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND))
{
// Uninstall section is not required.
hr = S_OK;
fSuccess = FALSE;
}
}
}
else
{
pszInstallSection = pszSubComponentId;
}
}
if (SUCCEEDED(hr) && fSuccess)
{
hr = HrCallExternalProc(pnocd, NETOCM_QUEUE_FILES,
(WPARAM)hfq, 0);
}
if (SUCCEEDED(hr))
{
TraceTag(ttidNetOc, "Queueing files for %S...",
pszSubComponentId);
hr = HrSetupInstallFilesFromInfSection(pnocd->hinfFile,
NULL, hfq,
pszInstallSection,
NULL, 0);
}
}
}
}
}
TraceError("HrOnQueueFileOps", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrOnCompleteInstallation
//
// Purpose: Handles the OC_COMPLETE_INSTALLATION function message.
//
// Arguments:
// pszComponentId [in] Top-level component name (will always be
// "NetOC" or NULL.
// pszSubComponentId [in] Name of component.
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 23 Feb 1998
// omiller 28 March 2000 Added code to move the progress
// bar one tick for every component
// installed or removed.
//
// Notes:
//
HRESULT HrOnCompleteInstallation(PCWSTR pszComponentId,
PCWSTR pszSubComponentId)
{
HRESULT hr = S_OK;
// Make sure they're different. If not, it's the top level item and
// we don't want to do anything
if (pszSubComponentId && lstrcmpiW(pszSubComponentId, pszComponentId))
{
NETOCDATA * pnocd;
pnocd = PnocdFindComponent(pszSubComponentId);
if (!pnocd)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
if (SUCCEEDED(hr))
{
pnocd->fCleanup = FALSE;
if (pnocd->eit == IT_INSTALL || pnocd->eit == IT_REMOVE ||
pnocd->eit == IT_UPGRADE)
{
pnocd->pszSection = pszSubComponentId;
// Get component description
#if DBG
if (pnocd->eit == IT_INSTALL)
{
TraceTag(ttidNetOc, "Installing network OC %S...",
pszSubComponentId);
}
else if (pnocd->eit == IT_UPGRADE)
{
TraceTag(ttidNetOc, "Upgrading network OC %S...",
pszSubComponentId);
}
else if (pnocd->eit == IT_REMOVE)
{
TraceTag(ttidNetOc, "Removing network OC %S...",
pszSubComponentId);
}
#endif
hr = HrDoOCInstallOrUninstall(pnocd);
if (FAILED(hr) && pnocd->eit == IT_INSTALL)
{
// A failure during install means we have to clean up by doing
// an uninstall now. Report the appropriate error and do the
// remove. Note - Don't report the error if it's ERROR_CANCELLED,
// because they KNOW that they cancelled, and it's not really
// an error.
//
if (HRESULT_FROM_WIN32(ERROR_CANCELLED) != hr)
{
// Don't report the error a second time if the component
// has already put up error UI (and set this flag)
//
if (!g_ocmData.fErrorReported)
{
ReportErrorHr(hr,
UiOcErrorFromHr(hr),
g_ocmData.hwnd,
pnocd->strDesc.c_str());
}
}
g_ocmData.fErrorReported = TRUE;
// Now we're removing
pnocd->eit = IT_REMOVE;
pnocd->fCleanup = TRUE;
pnocd->fFailedToInstall = TRUE;
// eat the error. Haven't we troubled them enough? :(
(VOID) HrDoOCInstallOrUninstall(pnocd);
}
else
{
// Every time a component is installed,upgraded or removed, the progress
// bar is advanced by one tick. For every component that is being
// installed/removed/upgraded the OC manager asked netoc for how many ticks
// that component counts (OC_QUERY_STEP_COUNT). From this information
// the OC manger knows the relationship between tick and progress bar
// advancement.
g_ocmData.sic.HelperRoutines.TickGauge(g_ocmData.sic.HelperRoutines.OcManagerContext);
}
}
}
}
TraceError("HrOnCompleteInstallation", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: DwOnQueryStepCount
//
// Purpose: Handles the OC_QUERY_STEP_COUNT message.
// The OC manager is asking us how many ticks a component is worth.
// The number of ticks determines the distance the progress bar gets
// moved. For netoc all components installed/removed are one tick and
// all components that are unchanged are 0 ticks.
//
// Arguments:
// pszSubComponentId [in] Name of component.
//
// Returns: Number of ticks for progress bar to move
//
// Author: omiller 28 March 2000
//
//
DWORD DwOnQueryStepCount(PCWSTR pvSubcomponentId)
{
NETOCDATA * pnocd;
// Get the component
pnocd = PnocdFindComponent(reinterpret_cast<PCWSTR>(pvSubcomponentId));
if( pnocd )
{
// Check if the status of the component has changed.
if (pnocd->eit == IT_INSTALL || pnocd->eit == IT_REMOVE ||
pnocd->eit == IT_UPGRADE)
{
// Status of component has changed. For this component the OC manager
// will move the status bar by one tick.
return 1;
}
}
// The component has not changed. The progress bar will not move for this component.
return 0;
}
//+---------------------------------------------------------------------------
//
// Function: HrOnQueryChangeSelState
//
// Purpose: Handles the OC_QUERY_CHANGE_SEL_STATE function message.
// Enables and disables the next button. If no changes has
// been made to the selections the next button is disabled.
//
// Arguments:
// pszSubComponentId [in] Name of component.
// fSelected [in] TRUE if component was checked "on", FALSE if
// checked "off"
// uiFlags [in] Flags defined in ocmgr.doc
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
HRESULT HrOnQueryChangeSelState(PCWSTR pszSubComponentId, BOOL fSelected,
UINT uiFlags)
{
HRESULT hr = S_OK;
static int nItemsChanged=0;
NETOCDATA * pnocd;
if (fSelected && pszSubComponentId)
{
pnocd = PnocdFindComponent(pszSubComponentId);
if (pnocd)
{
// "NetOc" may be a subcomponent and we don't want to call this
// for it.
hr = HrCallExternalProc(pnocd, NETOCM_QUERY_CHANGE_SEL_STATE,
(WPARAM)(!!(uiFlags & OCQ_ACTUAL_SELECTION)),
0);
}
}
TraceError("HrOnQueryChangeSelState", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: FOnQuerySkipPage
//
// Purpose: Handles the OC_QUERY_SKIP_PAGE function message.
//
// Arguments:
// ocmPage [in] Which page we are asked to possibly skip.
//
// Returns: TRUE if component list page should be skipped, FALSE if not.
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
BOOL FOnQuerySkipPage(OcManagerPage ocmPage)
{
BOOL fUnattended;
BOOL fGuiSetup;
BOOL fWorkstation;
fUnattended = !!(g_ocmData.sic.SetupData.OperationFlags & SETUPOP_BATCH);
fGuiSetup = !(g_ocmData.sic.SetupData.OperationFlags & SETUPOP_STANDALONE);
fWorkstation = g_ocmData.sic.SetupData.ProductType == PRODUCT_WORKSTATION;
if ((fUnattended || fWorkstation) && fGuiSetup)
{
// We're in GUI mode setup and... we're unattended -OR- this is
// a workstation install
if (ocmPage == OcPageComponentHierarchy)
{
TraceTag(ttidNetOc, "NETOC: Skipping component list page "
"during GUI mode setup...");
TraceTag(ttidNetOc, "fUnattended = %s, fGuiSetup = %s, "
"fWorkstation = %s",
fUnattended ? "yes" : "no",
fGuiSetup ? "yes" : "no",
fWorkstation ? "yes" : "no");
// Make sure we never show the component list page during setup
return TRUE;
}
}
TraceTag(ttidNetOc, "Using component list page.");
TraceTag(ttidNetOc, "fUnattended = %s, fGuiSetup = %s, "
"fWorkstation = %s",
fUnattended ? "yes" : "no",
fGuiSetup ? "yes" : "no",
fWorkstation ? "yes" : "no");
return FALSE;
}
//+---------------------------------------------------------------------------
//
// Function: OnCleanup
//
// Purpose: Handles the OC_CLEANUP function message.
//
// Arguments:
// (none)
//
// Returns: Nothing
//
// Author: danielwe 23 Feb 1998
//
// Notes:
//
VOID OnCleanup()
{
TraceTag(ttidNetOc, "Cleaning up");
if (g_ocmData.hinfAnswerFile)
{
SetupCloseInfFile(g_ocmData.hinfAnswerFile);
TraceTag(ttidNetOc, "Closed answer file");
}
DeleteAllComponents();
}
//+---------------------------------------------------------------------------
//
// Function: HrGetSelectionState
//
// Purpose:
//
// Arguments:
// pszSubComponentId [in] Name of subcomponent
// uStateType [in] In OCManager doc.
//
// Returns: S_OK if component is selected, S_FALSE if not, or Win32 error
// otheriwse
//
// Author: danielwe 17 Dec 1997
//
// Notes:
//
HRESULT HrGetSelectionState(PCWSTR pszSubComponentId, UINT uStateType)
{
HRESULT hr = S_OK;
BOOL fInstall;
fInstall = g_ocmData.sic.HelperRoutines.
QuerySelectionState(g_ocmData.sic.HelperRoutines.OcManagerContext,
pszSubComponentId, uStateType);
if (!fInstall)
{
// Still not sure of the state
hr = HrFromLastWin32Error();
if (SUCCEEDED(hr))
{
// Ok now we know
hr = S_FALSE;
}
}
else
{
hr = S_OK;
}
TraceError("HrGetSelectionState", (S_FALSE == hr) ? S_OK : hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrGetInstallType
//
// Purpose: Determines whether the given component is being installed or
// removed and stores the result in the given structure.
//
// Arguments:
// pszSubComponentId [in] Component being queried
// nocd [in, ref] Net OC Data.
// peit [out] Returns the install type
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 16 Dec 1997
//
// Notes: If the function fails, the eit member is unreliable
//
HRESULT HrGetInstallType(PCWSTR pszSubComponentId, NETOCDATA &nocd,
EINSTALL_TYPE *peit)
{
HRESULT hr = S_OK;
Assert(peit);
Assert(pszSubComponentId);
*peit = IT_UNKNOWN;
if (g_ocmData.sic.SetupData.OperationFlags & SETUPOP_BATCH)
{
// In batch mode (upgrade or unattended install), install flag is
// determined from answer file not from selection state.
// assume no change
*peit = IT_NO_CHANGE;
if (!g_ocmData.hinfAnswerFile)
{
// Open the answer file
hr = HrSetupOpenInfFile(g_ocmData.sic.SetupData.UnattendFile, NULL,
INF_STYLE_OLDNT | INF_STYLE_WIN4, NULL,
&g_ocmData.hinfAnswerFile);
}
if (SUCCEEDED(hr))
{
DWORD dwValue = 0;
// First query for a special value called "NoDepends" which, if
// present, means that the DependOnComponents line will be IGNORED
// for ALL network optional components for this install. This is
// because NetCfg may invoke the OC Manager to install an optional
// component and if that component has DependOnComponents, it will
// turn around and try to instantiate another INetCfg and that
// will fail because one instance is already running. This case
// is rare, though.
//
hr = HrSetupGetFirstDword(g_ocmData.hinfAnswerFile,
c_szOcMainSection, c_szNoDepends,
&dwValue);
if (SUCCEEDED(hr) && dwValue)
{
TraceTag(ttidNetOc, "Found the special 'NoDepends'"
" keyword in the answer file. DependOnComponents "
"will be ignored from now on");
g_ocmData.fNoDepends = TRUE;
}
else
{
TraceTag(ttidNetOc, "Didn't find the special 'NoDepends'"
" keyword in the answer file");
hr = S_OK;
}
hr = HrSetupGetFirstDword(g_ocmData.hinfAnswerFile,
c_szOcMainSection, pszSubComponentId,
&dwValue);
if (SUCCEEDED(hr))
{
// This component was installed before, so we should
// return that this component should be checked on
if (dwValue)
{
TraceTag(ttidNetOc, "Optional component %S was "
"previously installed or is being added thru"
" unattended install.", pszSubComponentId);
if (g_ocmData.sic.SetupData.OperationFlags & SETUPOP_NTUPGRADE)
{
// If we're upgrading NT, then this optional component
// does exist but it needs to be upgraded
*peit = IT_UPGRADE;
}
else
{
// Otherwise (even if Win3.1 or Win95 upgrade) it's like
// we're fresh installing the optional component
*peit = IT_INSTALL;
}
}
else
{
// Answer file contains something like WINS=0
hr = HrGetSelectionState(pszSubComponentId,
OCSELSTATETYPE_ORIGINAL);
if (S_OK == hr)
{
// Only set state to remove if the component was
// previously installed.
//
*peit = IT_REMOVE;
}
}
}
}
hr = S_OK;
// If the answer file was opened successfully and if the
// a section was found for the pszSubComponentId, *peit
// will be either IT_INSTALL, IT_UPGRADE or IT_REMOVE.
// Nothing needs to be done for any of these *peit values.
// However, if the answerfile could not be opened or if
// no section existed in the answer file for the pszSubComponentId
// *peit will have the value IT_NO_CHANGE. For this scenario,
// if the corresponding subComponent is currently installed,
// we should upgrade it. The following if addresses this scenario.
if (*peit == IT_NO_CHANGE)
{
// Still not going to install, because this is an upgrade
hr = HrGetSelectionState(pszSubComponentId,
OCSELSTATETYPE_ORIGINAL);
if (S_OK == hr)
{
// If originally selected and not in answer file, this is an
// upgrade of this component
*peit = IT_UPGRADE;
}
}
}
else // This is standalone (post-setup) mode
{
hr = HrGetSelectionState(pszSubComponentId, OCSELSTATETYPE_ORIGINAL);
if (SUCCEEDED(hr))
{
HRESULT hrT;
hrT = HrGetSelectionState(pszSubComponentId,
OCSELSTATETYPE_CURRENT);
if (SUCCEEDED(hrT))
{
if (hrT != hr)
{
// wasn't originally installed so...
*peit = (hrT == S_OK) ? IT_INSTALL : IT_REMOVE;
}
else
{
// was originally checked
*peit = IT_NO_CHANGE;
}
}
else
{
hr = hrT;
}
}
}
AssertSz(FImplies(SUCCEEDED(hr), *peit != IT_UNKNOWN), "Succeeded "
"but we never found out the install type!");
if (SUCCEEDED(hr))
{
hr = S_OK;
#if DBG
const CHAR *szInstallType;
switch (*peit)
{
case IT_NO_CHANGE:
szInstallType = "no change";
break;
case IT_INSTALL:
szInstallType = "install";
break;
case IT_UPGRADE:
szInstallType = "upgrade";
break;
case IT_REMOVE:
szInstallType = "remove";
break;
default:
AssertSz(FALSE, "Unknown install type!");
break;
}
TraceTag(ttidNetOc, "Install type of %S is %s.", pszSubComponentId,
szInstallType);
#endif
}
TraceError("HrGetInstallType", hr);
return hr;
}
#if DBG
PCWSTR SzFromOcUmsg(UINT uMsg)
{
switch (uMsg)
{
case NETOCM_PRE_INF:
return L"NETOCM_PRE_INF";
case NETOCM_POST_INSTALL:
return L"NETOCM_POST_INSTALL";
case NETOCM_QUERY_CHANGE_SEL_STATE:
return L"NETOCM_QUERY_CHANGE_SEL_STATE";
case NETOCM_QUEUE_FILES:
return L"NETOCM_QUEUE_FILES";
default:
return L"**unknown**";
}
}
#else
#define SzFromOcUmsg(x) (VOID)0
#endif
//+---------------------------------------------------------------------------
//
// Function: HrCallExternalProc
//
// Purpose: Calls a component's external function as defined by
// the table at the top of this file. This enables a component
// to perform additional installation tasks that are not common
// to other components.
//
// Arguments:
// pnocd [in] Pointer to Net OC Data
//
// Returns: S_OK if successful, Win32 error code otherwise.
//
// Author: danielwe 5 May 1997
//
// Notes:
//
HRESULT HrCallExternalProc(PNETOCDATA pnocd, UINT uMsg, WPARAM wParam,
LPARAM lParam)
{
HRESULT hr = S_OK;
INT iaocep;
BOOL fFound = FALSE;
AssertSz(pnocd, "Bad pnocd in HrCallExternalProc");
for (iaocep = 0; iaocep < c_cocepMap; iaocep++)
{
if (!lstrcmpiW(c_aocepMap[iaocep].pszComponentName,
pnocd->pszComponentId))
{
TraceTag(ttidNetOc, "Calling external procedure for %S. uMsg = %S"
" wParam = %08X,"
" lParam = %08X", c_aocepMap[iaocep].pszComponentName,
SzFromOcUmsg(uMsg), wParam, lParam);
// This component has an external proc. Call it now.
hr = c_aocepMap[iaocep].pfnHrOcExtProc(pnocd, uMsg,
wParam, lParam);
fFound = TRUE;
// Don't try to call any other functions
break;
}
}
if (FALSE == fFound)
{
TraceTag(ttidNetOc, "HrCallExternalProc - did not find a matching Proc for %S",
pnocd->pszComponentId);
}
TraceError("HrCallExternalProc", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrInstallOrRemoveNetCfgComponent
//
// Purpose: Utility function for use by optional components that wish to
// install a NetCfg component from within their own install.
//
// Arguments:
// pnocd [in] Pointer to NETOC data
// pszComponentId [in] Component ID of NetCfg component to install.
// This can be found in the netinfid.cpp file.
// pszManufacturer [in] Manufacturer name of component doing the
// installing (*this* component). Should always
// be "Microsoft".
// pszProduct [in] Short name of product for this component.
// Should be something like "MacSrv".
// pszDisplayName [in] Display name of this product. Should be
// something like "Services For Macintosh".
// rguid [in] class GUID of the component being installed
//
// Returns: S_OK if successful, Win32 error code otherwise.
//
// Author: danielwe 6 May 1997
//
// Notes:
//
HRESULT HrInstallOrRemoveNetCfgComponent(PNETOCDATA pnocd,
PCWSTR pszComponentId,
PCWSTR pszManufacturer,
PCWSTR pszProduct,
PCWSTR pszDisplayName,
const GUID& rguid)
{
HRESULT hr = S_OK;
INetCfg * pnc;
NETWORK_INSTALL_PARAMS nip = {0};
BOOL fReboot = FALSE;
nip.dwSetupFlags = FInSystemSetup() ? NSF_PRIMARYINSTALL :
NSF_POSTSYSINSTALL;
hr = HrOcGetINetCfg(pnocd, TRUE, &pnc);
if (SUCCEEDED(hr))
{
if (pnocd->eit == IT_INSTALL || pnocd->eit == IT_UPGRADE)
{
if (*pszComponentId == L'*')
{
// Advance past the *
pszComponentId++;
// Install OBO user instead
TraceTag(ttidNetOc, "Installing %S on behalf of the user",
pszComponentId);
hr = HrInstallComponentOboUser(pnc, &nip, rguid,
pszComponentId, NULL);
}
else
{
TraceTag(ttidNetOc, "Installing %S on behalf of %S",
pszComponentId, pnocd->pszSection);
hr = HrInstallComponentOboSoftware(pnc, &nip,
rguid,
pszComponentId,
pszManufacturer,
pszProduct,
pszDisplayName,
NULL);
}
}
else
{
AssertSz(pnocd->eit == IT_REMOVE, "Invalid install action!");
TraceTag(ttidNetOc, "Removing %S on behalf of %S",
pszComponentId, pnocd->pszSection);
hr = HrRemoveComponentOboSoftware(pnc,
rguid,
pszComponentId,
pszManufacturer,
pszProduct,
pszDisplayName);
if (NETCFG_S_REBOOT == hr)
{
// Save off the fact that we need to reboot
fReboot = TRUE;
}
// Don't care about the return value here. If we can't remove a
// dependent component, we can't do anything about it so we should
// still continue the removal of the OC.
//
else if (FAILED(hr))
{
TraceTag(ttidError, "Failed to remove %S on behalf of %S!! "
"Error is 0x%08X",
pszComponentId, pnocd->pszSection, hr);
hr = S_OK;
}
}
if (SUCCEEDED(hr))
{
hr = pnc->Apply();
}
(VOID) HrUninitializeAndReleaseINetCfg(TRUE, pnc, TRUE);
}
if (SUCCEEDED(hr) && fReboot)
{
// If all went well and we needed to reboot, set hr back.
hr = NETCFG_S_REBOOT;
}
TraceError("HrInstallOrRemoveNetCfgComponent", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrInstallOrRemoveServices
//
// Purpose: Given an install section, installs (or removes) NT services
// from the section.
//
// Arguments:
// hinf [in] Handle to INF file.
// pszSectionName [in] Name of section to use.
//
// Returns: S_OK if successful, WIN32 HRESULT if not.
//
// Author: danielwe 23 Apr 1997
//
// Notes:
//
HRESULT HrInstallOrRemoveServices(HINF hinf, PCWSTR pszSectionName)
{
static const WCHAR c_szDotServices[] = L"."INFSTR_SUBKEY_SERVICES;
HRESULT hr = S_OK;
PWSTR pszServicesSection;
const DWORD c_cchServices = celems(c_szDotServices);
DWORD cchName;
// Look for <szSectionName>.Services to install any NT
// services if they exist.
cchName = c_cchServices + lstrlenW(pszSectionName);
pszServicesSection = new WCHAR [cchName];
if(pszServicesSection)
{
lstrcpyW(pszServicesSection, pszSectionName);
lstrcatW(pszServicesSection, c_szDotServices);
if (!SetupInstallServicesFromInfSection(hinf, pszServicesSection, 0))
{
hr = HrFromLastWin32Error();
if (hr == HRESULT_FROM_SETUPAPI(ERROR_SECTION_NOT_FOUND))
{
// No problem if section was not found
hr = S_OK;
}
}
delete [] pszServicesSection;
}
else
{
hr = E_OUTOFMEMORY;
}
TraceError("HrInstallOrRemoveServices", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrHandleOCExtensions
//
// Purpose: Handles support for all optional component extensions to the
// INF file format.
//
// Arguments:
// hinfFile [in] handle to INF to process
// pszInstallSection [in] Install section to process
//
// Returns: S_OK if success, setup API HRESULT otherwise
//
// Author: danielwe 28 Apr 1997
//
// Notes:
//
HRESULT HrHandleOCExtensions(HINF hinfFile, PCWSTR pszInstallSection)
{
HRESULT hr = S_OK;
// There's now common code to do this, so simply make a call to that code.
//
hr = HrProcessAllINFExtensions(hinfFile, pszInstallSection);
TraceError("HrHandleOCExtensions", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrInstallOrRemoveDependOnComponents
//
// Purpose: Handles installation or removal of any NetCfg components that
// the optional component being installed is dependent upon.
//
// Arguments:
// pnocd [in] Pointer to NETOC data
// hinf [in] Handle to INF file to process.
// pszInstallSection [in] Section name to install from.
// pszDisplayName [in] Display name of component being installed.
//
// Returns: S_OK if success, setup API HRESULT otherwise
//
// Author: danielwe 17 Jun 1997
//
// Notes:
//
HRESULT HrInstallOrRemoveDependOnComponents(PNETOCDATA pnocd,
HINF hinf,
PCWSTR pszInstallSection,
PCWSTR pszDisplayName)
{
HRESULT hr = S_OK;
PWSTR mszDepends;
tstring strManufacturer;
PCWSTR pszManufacturer;
Assert(pnocd);
hr = HrSetupGetFirstString(hinf, c_szVersionSection, c_szProvider,
&strManufacturer);
if (S_OK == hr)
{
pszManufacturer = strManufacturer.c_str();
}
else
{
// No provider found, use default
hr = S_OK;
pszManufacturer = c_szDefManu;
}
hr = HrSetupGetFirstMultiSzFieldWithAlloc(hinf, pszInstallSection,
c_szDependOnComp,
&mszDepends);
if (S_OK == hr)
{
PCWSTR pszComponent;
pszComponent = mszDepends;
while (SUCCEEDED(hr) && *pszComponent)
{
const GUID * pguidClass;
PCWSTR pszComponentActual = pszComponent;
if (*pszComponent == L'*')
{
pszComponentActual = pszComponent + 1;
}
if (FClassGuidFromComponentId(pszComponentActual, &pguidClass))
{
hr = HrInstallOrRemoveNetCfgComponent(pnocd,
pszComponent,
pszManufacturer,
pszInstallSection,
pszDisplayName,
*pguidClass);
}
#ifdef DBG
else
{
TraceTag(ttidNetOc, "Error in INF, Component %S not found!",
pszComponent);
}
#endif
pszComponent += lstrlenW(pszComponent) + 1;
}
delete mszDepends;
}
else if (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND))
{
// Section is not required.
hr = S_OK;
}
TraceError("HrInstallOrRemoveDependOnComponents", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrRunInfSection
//
// Purpose: Runs the given INF section, but doesn't copy files
//
// Arguments:
// hinf [in] Handle to INF to run
// pnocd [in] NetOC Data
// pszInstallSection [in] Install section to run
// dwFlags [in] Install flags (SPINST_*)
//
// Returns: S_OK if success, SetupAPI or Win32 error otherwise
//
// Author: danielwe 16 Dec 1997
//
// Notes:
//
HRESULT HrRunInfSection(HINF hinf, PNETOCDATA pnocd,
PCWSTR pszInstallSection, DWORD dwFlags)
{
HRESULT hr;
// Now we run all sections but CopyFiles and UnregisterDlls because we
// did that earlier
//
hr = HrSetupInstallFromInfSection(g_ocmData.hwnd, hinf,
pszInstallSection,
dwFlags & ~SPINST_FILES & ~SPINST_UNREGSVR,
NULL, NULL, 0, NULL,
NULL, NULL, NULL);
TraceError("HrRunInfSection", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrStartOrStopAnyServices
//
// Purpose: Starts or stops any services the INF has requested via the
// Services value in the main install section.
//
// Arguments:
// hinf [in] handle to INF to process
// pszSection [in] Install section to process
// fStart [in] TRUE to start, FALSE to stop.
//
// Returns: S_OK or Win32 error code.
//
// Author: danielwe 17 Jun 1997
//
// Notes: Services are stopped in the same order they are started.
//
HRESULT HrStartOrStopAnyServices(HINF hinf, PCWSTR pszSection, BOOL fStart)
{
HRESULT hr;
PWSTR mszServices;
hr = HrSetupGetFirstMultiSzFieldWithAlloc(hinf, pszSection,
c_szServices, &mszServices);
if (SUCCEEDED(hr))
{
// Build an array of pointers to strings that point at the
// strings of the multi-sz. This is needed because the API to
// stop and start services takes an array of pointers to strings.
//
UINT cServices;
PCWSTR* apszServices;
hr = HrCreateArrayOfStringPointersIntoMultiSz(
mszServices,
&cServices,
&apszServices);
if (SUCCEEDED(hr))
{
CServiceManager scm;
if (fStart)
{
hr = scm.HrStartServicesAndWait(cServices, apszServices);
}
else
{
hr = scm.HrStopServicesAndWait(cServices, apszServices);
}
MemFree (apszServices);
}
delete mszServices;
}
else if (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND))
{
// this is a totally optional thing
hr = S_OK;
}
TraceError("HrStartOrStopAnyServices", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrDoActualInstallOrUninstall
//
// Purpose: Handles main portion of install or uninstall for an optional
// network component.
//
// Arguments:
// hinf [in] handle to INF to process
// pnocd [in] Pointer to NETOC data (hwnd, poc)
// pszInstallSection [in] Install section to process
//
// Returns: S_OK if success, setup API HRESULT otherwise
//
// Author: danielwe 17 Jun 1997
//
// Notes:
//
HRESULT HrDoActualInstallOrUninstall(HINF hinf,
PNETOCDATA pnocd,
PCWSTR pszInstallSection)
{
HRESULT hr = S_OK;
BOOL fReboot = FALSE;
AssertSz(pszInstallSection, "Install section is NULL!");
AssertSz(pnocd, "Bad pnocd in HrDoActualInstallOrUninstall");
//AssertSz(g_ocmData.hwnd, "Bad g_ocmData.hwnd in HrDoActualInstallOrUninstall");
if (pnocd->eit == IT_REMOVE)
{
hr = HrCallExternalProc(pnocd, NETOCM_PRE_INF, 0, 0);
if (SUCCEEDED(hr))
{
// Now process the component's INF file
//
TraceTag(ttidNetOc, "Running INF section %S", pszInstallSection);
hr = HrRunInfSection(hinf, pnocd, pszInstallSection, SPINST_ALL);
}
}
else
{
hr = HrCallExternalProc(pnocd, NETOCM_PRE_INF, 0, 0);
if (SUCCEEDED(hr))
{
// Process the component's INF file
//
TraceTag(ttidNetOc, "Running INF section %S", pszInstallSection);
hr = HrRunInfSection(hinf, pnocd, pszInstallSection,
SPINST_ALL & ~SPINST_REGSVR);
}
}
if (SUCCEEDED(hr))
{
// Must install or remove services first
TraceTag(ttidNetOc, "Running HrInstallOrRemoveServices for %S",
pszInstallSection);
hr = HrInstallOrRemoveServices(hinf, pszInstallSection);
if (SUCCEEDED(hr))
{
// Bug #383239: Wait till services are installed before
// running the RegisterDlls section
//
hr = HrRunInfSection(hinf, pnocd, pszInstallSection,
SPINST_REGSVR);
}
if (SUCCEEDED(hr))
{
TraceTag(ttidNetOc, "Running HrHandleOCExtensions for %S",
pszInstallSection);
hr = HrHandleOCExtensions(hinf, pszInstallSection);
if (SUCCEEDED(hr))
{
if (!g_ocmData.fNoDepends)
{
// Now install or remove any NetCfg components that this
// component requires
TraceTag(ttidNetOc, "Running "
"HrInstallOrRemoveDependOnComponents for %S",
pnocd->pszSection);
hr = HrInstallOrRemoveDependOnComponents(pnocd,
hinf,
pnocd->pszSection,
pnocd->strDesc.c_str());
if (NETCFG_S_REBOOT == hr)
{
fReboot = TRUE;
}
}
else
{
AssertSz(g_ocmData.sic.SetupData.OperationFlags &
SETUPOP_BATCH, "How can NoDepends be set??");
TraceTag(ttidNetOc, "NOT Running "
"HrInstallOrRemoveDependOnComponents for %S "
"because NoDepends was set in the answer file.",
pnocd->pszSection);
}
if (SUCCEEDED(hr))
{
// Now call any external installation support...
hr = HrCallExternalProc(pnocd, NETOCM_POST_INSTALL,
0, 0);
if (SUCCEEDED(hr))
{
if (pnocd->eit == IT_INSTALL && !FInSystemSetup())
{
// ... and finally, start any services they've
// requested
hr = HrStartOrStopAnyServices(hinf,
pszInstallSection, TRUE);
{
if (FAILED(hr))
{
UINT ids = IDS_OC_START_SERVICE_FAILURE;
if (HRESULT_FROM_WIN32(ERROR_TIMEOUT) == hr)
{
ids = IDS_OC_START_TOOK_TOO_LONG;
}
// Don't bail installation if service
// couldn't be started. Report an error
// and continue the install.
ReportErrorHr(hr, ids, g_ocmData.hwnd,
pnocd->strDesc.c_str());
hr = S_OK;
}
}
}
}
}
}
}
}
if ((S_OK == hr) && (fReboot))
{
hr = NETCFG_S_REBOOT;
}
TraceError("HrDoActualInstallOrUninstall", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrOCInstallOrUninstallFromINF
//
// Purpose: Handles installation of an Optional Component from its INF
// file.
//
// Arguments:
// pnocd [in] Pointer to NETOC data.
//
// Returns: S_OK if success, setup API HRESULT otherwise
//
// Author: danielwe 6 May 1997
//
// Notes:
//
HRESULT HrOCInstallOrUninstallFromINF(PNETOCDATA pnocd)
{
HRESULT hr = S_OK;
tstring strUninstall;
PCWSTR pszInstallSection = NULL;
BOOL fSuccess = TRUE;
Assert(pnocd);
if (pnocd->eit == IT_REMOVE)
{
// Get the name of the uninstall section first
hr = HrSetupGetFirstString(pnocd->hinfFile, pnocd->pszSection,
c_szUninstall, &strUninstall);
if (SUCCEEDED(hr))
{
pszInstallSection = strUninstall.c_str();
}
else
{
if (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND))
{
// Uninstall section is not required.
hr = S_OK;
}
fSuccess = FALSE;
}
}
else
{
pszInstallSection = pnocd->pszSection;
}
if (fSuccess)
{
hr = HrDoActualInstallOrUninstall(pnocd->hinfFile,
pnocd,
pszInstallSection);
}
TraceError("HrOCInstallOrUninstallFromINF", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrDoOCInstallOrUninstall
//
// Purpose: Installs or removes an optional networking component.
//
// Arguments:
// pnocd [in] Pointer to NETOC data
//
// Returns: S_OK for success, SetupAPI HRESULT error code otherwise.
//
// Author: danielwe 6 May 1997
//
// Notes:
//
HRESULT HrDoOCInstallOrUninstall(PNETOCDATA pnocd)
{
HRESULT hr = S_OK;
hr = HrOCInstallOrUninstallFromINF(pnocd);
TraceError("HrDoOCInstallOrUninstall", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: UiOcErrorFromHr
//
// Purpose: Maps a Win32 error code into an understandable error string.
//
// Arguments:
// hr [in] HRESULT to convert
//
// Returns: The resource ID of the string.
//
// Author: danielwe 9 Feb 1998
//
// Notes:
//
UINT UiOcErrorFromHr(HRESULT hr)
{
UINT uid;
AssertSz(FAILED(hr), "Don't call UiOcErrorFromHr if Hr didn't fail!");
switch (hr)
{
case HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND):
case HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND):
uid = IDS_OC_REGISTER_PROBLEM;
break;
case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND):
uid = IDS_OC_FILE_PROBLEM;
break;
case NETCFG_E_NEED_REBOOT:
case HRESULT_FROM_WIN32(ERROR_SERVICE_MARKED_FOR_DELETE):
uid = IDS_OC_NEEDS_REBOOT;
break;
case HRESULT_FROM_WIN32(ERROR_CANCELLED):
uid = IDS_OC_USER_CANCELLED;
break;
case HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED):
uid = IDS_OC_NO_PERMISSION;
break;
default:
uid = IDS_OC_ERROR;
break;
}
return uid;
}
//+---------------------------------------------------------------------------
//
// Function: SzErrorToString
//
// Purpose: Converts an HRESULT into a displayable string.
//
// Arguments:
// hr [in] HRESULT value to convert.
//
// Returns: LPWSTR a dynamically allocated string to be freed with LocalFree
//
// Author: mbend 3 Apr 2000
//
// Notes: Attempts to use FormatMessage to convert the HRESULT to a string.
// If that fails, just convert the HRESULT to a hex string.
//
LPWSTR SzErrorToString(HRESULT hr)
{
LPWSTR pszErrorText = NULL;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
(WCHAR*)&pszErrorText, 0, NULL);
if (pszErrorText)
{
// Strip off newline characters.
//
LPWSTR pchText = pszErrorText;
while (*pchText && (*pchText != L'\r') && (*pchText != L'\n'))
{
pchText++;
}
*pchText = 0;
return pszErrorText;
}
// We did't find anything so format the hex value
WCHAR szBuf[128];
wsprintfW(szBuf, L"0x%08x", hr);
WCHAR * szRet = reinterpret_cast<WCHAR*>(LocalAlloc(LMEM_FIXED, (lstrlenW(szBuf) + 1) * sizeof(WCHAR)));
if(szRet)
{
lstrcpyW(szRet, szBuf);
}
return szRet;
}
//+---------------------------------------------------------------------------
//
// Function: NcMsgBoxMc
//
// Purpose: Displays a message box using resource strings from
// the message resource file and using replaceable
// parameters.
//
// Arguments:
// hwnd [in] parent window handle
// unIdCaption [in] resource id of caption string
// (from .RC file)
// unIdFormat [in] resource id of text string (with %1, %2, etc.)
// (from .MC file)
// unStyle [in] standard message box styles
// ... [in] replaceable parameters (optional)
// (these must be PCWSTRs as that is all
// FormatMessage handles.)
//
// Returns: The return value of MessageBox()
//
// Author: roelfc 7 June 2001
//
// Notes: FormatMessage is used to do the parameter substitution.
// The unIdFormat resource id MUST be specified in the
// .MC resource file with a severity of either informational,
// warning or error.
//
NOTHROW
int
WINAPIV
NcMsgBoxMc(HWND hwnd,
UINT unIdCaption,
UINT unIdFormat,
UINT unStyle,
...)
{
PCWSTR pszCaption = SzLoadIds(unIdCaption);
// We report only valid message resources to prevent event log failures
AssertSz(STATUS_SEVERITY_VALUE(unIdFormat) != STATUS_SEVERITY_SUCCESS,
"Either the severity code is not set (information, warning or error),"
" or you passed a .RC resource id instead of a .MC resource id.");
PWSTR pszText = NULL;
va_list val;
va_start (val, unStyle);
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
_Module.GetResourceInstance(), unIdFormat, 0, (PWSTR)&pszText, 0, &val);
va_end (val);
if(!pszText)
{
// This is what MessageBox returns if it fails.
return 0;
}
INT nRet = MessageBox (hwnd, pszText, pszCaption, unStyle);
LocalFree (pszText);
return nRet;
}
//+---------------------------------------------------------------------------
//
// Function: ReportEventHrString
//
// Purpose: Reports an error, warning or informative message
// to the event log from an error description string.
//
// Arguments:
// pszErr [in] Error description string.
// ids [in] Resource ID of string to display.
// pszDesc [in] Description of component involved.
//
// Returns: S_OK, or valid Win32 error code.
//
// Author: roelfc 18 May 2001
//
// Notes: This function works slow since it calls the open and close
// eventlog source everytime. This should not have an effect
// since it only happens during errors.
// The string resource in ids must contain a %1 and %2 where %1
// is the name of the component, and %2 is the error code.
// The resource ID of the string to display MUST be defined
// in the .MC file, with a severity of either informational,
// warning or error. The Assert below prevents the incorrect
// use of .RC strings which will fail during event logging.
//
HRESULT ReportEventHrString(PCWSTR pszErr, INT ids, PCWSTR pszDesc)
{
HANDLE hEventLog;
WORD elt;
HRESULT hr = S_OK;
PCWSTR plpszSubStrings[2];
plpszSubStrings[0] = pszDesc;
plpszSubStrings[1] = pszErr;
// We report only valid message resources to prevent event log failures
AssertSz(STATUS_SEVERITY_VALUE(ids) != STATUS_SEVERITY_SUCCESS,
"Either the severity code is not set (information, warning or error),"
" or you passed a .RC resource id instead of a .MC resource id.");
// Determine the event log type
switch (STATUS_SEVERITY_VALUE(ids))
{
case STATUS_SEVERITY_WARNING:
elt = EVENTLOG_WARNING_TYPE;
break;
case STATUS_SEVERITY_ERROR:
elt = EVENTLOG_ERROR_TYPE;
break;
default:
// Default to informational
elt = EVENTLOG_INFORMATION_TYPE;
break;
}
hEventLog = RegisterEventSource(NULL, NETOC_SERVICE_NAME);
Assert(hEventLog);
if (hEventLog)
{
if (!ReportEvent(hEventLog,
elt,
0, // Event category
ids, // Message file full id
NULL,
sizeof(plpszSubStrings) / sizeof(plpszSubStrings[0]),
0,
plpszSubStrings,
NULL))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
DeregisterEventSource(hEventLog);
}
else
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: ReportEventHrResult
//
// Purpose: Reports an error, warning or informative message
// to the event log from a result value.
//
// Arguments:
// hrv [in] HRESULT value to report.
// ids [in] Resource ID of string to display.
// pszDesc [in] Description of component involved.
//
// Returns: S_OK, or valid Win32 error code.
//
// Author: roelfc 18 May 2001
//
// Notes:
//
HRESULT ReportEventHrResult(HRESULT hrv, INT ids, PCWSTR pszDesc)
{
HRESULT hr = S_OK;
BOOL bCleanup = TRUE;
WCHAR * szText = SzErrorToString(hrv);
if(!szText)
{
szText = L"Out of memory!";
bCleanup = FALSE;
}
hr = ReportEventHrString(szText, ids, pszDesc);
if(bCleanup)
{
LocalFree(szText);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: ReportErrorHr
//
// Purpose: Reports an error, warning or informative message
// to the user or event log.
//
// Arguments:
// hrv [in] HRESULT value to report.
// ids [in] Resource ID of string to display.
// hwnd [in] HWND of parent window.
// pszDesc [in] Description of component involved.
//
// Returns: S_OK, or valid Win32 error code.
//
// Author: danielwe 28 Apr 1997
//
// Notes: The string resource in ids must contain a %1 and %2 where %1
// is the name of the component, and %2 is the error code.
// The resource ID of the string to display MUST be defined
// in the .MC file, with a severity of either informational,
// warning or error. The Assert below prevents the incorrect
// use of .RC strings which will fail during event logging.
//
HRESULT ReportErrorHr(HRESULT hrv, INT ids, HWND hwnd, PCWSTR pszDesc)
{
DWORD dwRt;
HRESULT hr = S_OK;
// We report only valid message resources to prevent event log failures
AssertSz(STATUS_SEVERITY_VALUE(ids) != STATUS_SEVERITY_SUCCESS,
"Either the severity code is not set (information, warning or error),"
" or you passed a .RC resource id instead of a .MC resource id.");
// We can only display a message box in "attended" setup mode
// or when the caller overide with the /z:netoc_show_unattended_messages option,
// else we log the problem to the event log.
if ((g_ocmData.sic.SetupData.OperationFlags & SETUPOP_BATCH) &&
(!g_ocmData.fShowUnattendedMessages))
{
// In batch mode ("unattended") we need to report the error in the event log
hr = ReportEventHrResult(hrv, ids, pszDesc);
}
else
{
BOOL bCleanup = TRUE;
WCHAR * szText = SzErrorToString(hrv);
if(!szText)
{
szText = L"Out of memory!";
bCleanup = FALSE;
}
// Get the right icon from the type of message
switch (STATUS_SEVERITY_VALUE(ids))
{
case STATUS_SEVERITY_WARNING:
dwRt = MB_ICONWARNING;
break;
case STATUS_SEVERITY_ERROR:
dwRt = MB_ICONERROR;
break;
default:
// Default to informational
dwRt = MB_ICONINFORMATION;
break;
}
// We can display the error to the user
NcMsgBoxMc(hwnd, IDS_OC_CAPTION, ids, dwRt | MB_OK, pszDesc, szText);
if(bCleanup)
{
LocalFree(szText);
}
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrVerifyStaticIPPresent
//
// Purpose: Verify that at least one adapter has a static IP address.
// Both DHCP Server and WINS need to know this, as they need
// to bring up UI if this isn't the case. This function is, of
// course, a complete hack until we can get a properties
// interface hanging off of the components.
//
// Arguments:
// pnc [in] INetCfg interface to use
//
// Returns: S_OK, or valid Win32 error code.
//
// Author: jeffspr 19 Jun 1997
//
// Notes:
//
HRESULT HrVerifyStaticIPPresent(INetCfg *pnc)
{
HRESULT hr = S_OK;
HKEY hkeyInterfaces = NULL;
HKEY hkeyEnum = NULL;
INetCfgComponent* pncc = NULL;
HKEY hkeyTcpipAdapter = NULL;
PWSTR pszBindName = NULL;
Assert(pnc);
// Iterate the adapters in the system looking for non-virtual adapters
//
CIterNetCfgComponent nccIter(pnc, &GUID_DEVCLASS_NET);
while (S_OK == (hr = nccIter.HrNext(&pncc)))
{
DWORD dwFlags = 0;
// Get the adapter characteristics
//
hr = pncc->GetCharacteristics(&dwFlags);
if (SUCCEEDED(hr))
{
DWORD dwEnableValue = 0;
// If we're NOT a virtual adapter, THEN test for
// tcp/ip static IP
if (!(dwFlags & NCF_VIRTUAL))
{
WCHAR szRegPath[MAX_PATH+1];
// Get the component bind name
//
hr = pncc->GetBindName(&pszBindName);
if (FAILED(hr))
{
TraceTag(ttidError,
"Error getting bind name from component "
"in HrVerifyStaticIPPresent()");
goto Exit;
}
// Build the path to the TCP/IP instance key for his adapter
//
wsprintfW(szRegPath, L"%s\\%s",
c_szTcpipInterfacesPath, pszBindName);
// Open the key for this adapter.
//
hr = HrRegOpenKeyEx(HKEY_LOCAL_MACHINE,
szRegPath,
KEY_READ, &hkeyTcpipAdapter);
if (SUCCEEDED(hr))
{
// Read the EnableDHCP value.
//
hr = HrRegQueryDword(hkeyTcpipAdapter, c_szEnableDHCP,
&dwEnableValue);
if (FAILED(hr))
{
TraceTag(ttidError,
"Error reading the EnableDHCP value from "
"the enumerated key in "
"HrVerifyStaticIPPresent()");
goto Exit;
}
// If we've found a non-DHCP-enabled adapter.
//
if (0 == dwEnableValue)
{
// We have our man. Take a hike, and return S_OK,
// meaning that we had at least one good adapter.
// The enumerated key will get cleaned up at exit.
hr = S_OK;
goto Exit;
}
RegSafeCloseKey(hkeyTcpipAdapter);
hkeyTcpipAdapter = NULL;
}
else
{
// If the key wasn't found, we just don't have a
// binding to TCP/IP. This is fine, but we don't need
// to continue plodding down this path.
//
if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
hr = S_OK;
}
else
{
TraceTag(ttidError,
"Error opening adapter key in "
"HrVerifyStaticIPPresent()");
goto Exit;
}
}
}
}
if (pszBindName)
{
CoTaskMemFree(pszBindName);
pszBindName = NULL;
}
ReleaseObj (pncc);
pncc = NULL;
}
// If we haven't found an adapter, we'll have an S_FALSE returned from
// the HrNext. This is fine, because if we haven't found an adapter
// with a static IP address, this is exactly what we want to return.
// If we'd found one, we'd have set hr = S_OK, and dropped out of the
// loop.
Exit:
RegSafeCloseKey(hkeyTcpipAdapter);
if (pszBindName)
{
CoTaskMemFree(pszBindName);
pszBindName = NULL;
}
ReleaseObj(pncc);
TraceError("HrVerifyStaticIPPresent()", (hr == S_FALSE) ? S_OK : hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrCountConnections
//
// Purpose: Determines the number of LAN connections present and returns
// a pointer to an INetConnection object if only one connection
// is present.
//
// Arguments:
// ppconn [out] If only one connection is present, this returns it
//
// Returns: S_OK if no errors were found and at least one connection
// exists, S_FALSE if no connections exist, or a Win32 or OLE
// error code otherwise
//
// Author: danielwe 28 Jul 1998
//
// Notes:
//
HRESULT HrCountConnections(INetConnection **ppconn)
{
HRESULT hr = S_OK;
INetConnectionManager * pconMan;
Assert(ppconn);
*ppconn = NULL;
// Iterate all LAN connections
//
hr = HrCreateInstance(
CLSID_LanConnectionManager,
CLSCTX_SERVER | CLSCTX_NO_CODE_DOWNLOAD,
&pconMan);
TraceHr(ttidError, FAL, hr, FALSE, "HrCreateInstance");
if (SUCCEEDED(hr))
{
CIterNetCon ncIter(pconMan, NCME_DEFAULT);
INetConnection * pconn = NULL;
INetConnection * pconnCur = NULL;
INT cconn = 0;
while (SUCCEEDED(hr) && (S_OK == (ncIter.HrNext(&pconn))))
{
ReleaseObj(pconnCur);
cconn++;
AddRefObj(pconnCur = pconn);
ReleaseObj(pconn);
}
if (cconn > 1)
{
// if more than one connection found, release last one we had
ReleaseObj(pconnCur);
hr = S_OK;
}
else if (cconn == 0)
{
ReleaseObj(pconnCur);
hr = S_FALSE;
}
else // conn == 1
{
*ppconn = pconnCur;
hr = S_OK;
}
ReleaseObj(pconMan);
}
TraceError("HrCountConnections", (hr == S_FALSE) ? S_OK : hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrHandleStaticIpDependency
//
// Purpose: Handles the need that some components have that requires
// at least one adapter using a static IP address before they
// can be installed properly.
//
// Arguments:
// pnocd [in] Pointer to NETOC data
//
// Returns: S_OK if success, Win32 HRESULT error code otherwise.
//
// Author: danielwe 19 Jun 1997
//
// Notes:
//
HRESULT HrHandleStaticIpDependency(PNETOCDATA pnocd)
{
HRESULT hr = S_OK;
static BOOL fFirstInvocation = TRUE;
// bug 25841. This function is called during installation of DNS, DHCP,
// and WINS. If all three are being installed togetther then this ends
// up showing the same error message thrice when one would suffice.
if( fFirstInvocation )
{
fFirstInvocation = FALSE;
}
else
{
return hr;
}
// We handle "attended" and "unattended" setup mode through ReportErrorHr
{
BOOL fChangesApplied = FALSE;
INetCfg * pnc = NULL;
Assert(pnocd);
//Assert(g_ocmData.hwnd);
hr = HrOcGetINetCfg(pnocd, FALSE, &pnc);
if (SUCCEEDED(hr))
{
hr = HrVerifyStaticIPPresent(pnc);
if (hr == S_FALSE)
{
INetConnectionCommonUi * pcommUi;
INetConnection * pconn = NULL;
hr = HrCountConnections(&pconn);
if (S_OK == hr)
{
// One or more connections found
// Report message to user indicating that she has to
// configure at least one adapter with a static IP address
// before we can continue.
ReportErrorHr(hr,
IDS_OC_NEED_STATIC_IP,
g_ocmData.hwnd,
pnocd->strDesc.c_str());
// Try to fix it if we are in "attended" mode or
// we have the /z:netoc_show_unattended_messages options flag set.
if ((!(g_ocmData.sic.SetupData.OperationFlags & SETUPOP_BATCH)) ||
(g_ocmData.fShowUnattendedMessages))
{
hr = CoCreateInstance(CLSID_ConnectionCommonUi, NULL,
CLSCTX_INPROC | CLSCTX_NO_CODE_DOWNLOAD,
IID_INetConnectionCommonUi,
reinterpret_cast<LPVOID *>(&pcommUi));
TraceHr(ttidError, FAL, hr, FALSE, "CoCreateInstance");
if (SUCCEEDED(hr))
{
if (pconn)
{
// Exactly one connection found
hr = pcommUi->ShowConnectionProperties(g_ocmData.hwnd,
pconn);
if (S_OK == hr)
{
fChangesApplied = TRUE;
}
else if (FAILED(hr))
{
// Eat the error since we can't do anything about it
// anyway.
TraceError("HrHandleStaticIpDependency - "
"ShowConnectionProperties", hr);
hr = S_OK;
}
}
else
{
// More than one connection found
if (SUCCEEDED(hr))
{
NETCON_CHOOSECONN chooseCon = {0};
chooseCon.lStructSize = sizeof(NETCON_CHOOSECONN);
chooseCon.hwndParent = g_ocmData.hwnd;
chooseCon.dwTypeMask = NCCHT_LAN;
chooseCon.dwFlags = NCCHF_DISABLENEW;
hr = pcommUi->ChooseConnection(&chooseCon, NULL);
if (SUCCEEDED(hr))
{
fChangesApplied = TRUE;
}
else
{
// Eat the error since we can't do anything about it
// anyway.
TraceError("HrHandleStaticIpDependency - "
"ChooseConnection", hr);
hr = S_OK;
}
}
}
ReleaseObj(pcommUi);
}
ReleaseObj(pconn);
if (SUCCEEDED(hr))
{
// Don't bother checking again if they never
// made any changes
if (!fChangesApplied ||
(S_FALSE == (hr = HrVerifyStaticIPPresent(pnc))))
{
// Geez, still no static IP address available.
// Report another message scolding the user for
// not following directions.
ReportErrorHr(hr,
IDS_OC_STILL_NO_STATIC_IP,
g_ocmData.hwnd,
pnocd->strDesc.c_str());
hr = S_OK;
}
}
}
else
{
// Just report the error as would have happened when the
// user did not correct it.
ReportErrorHr(hr,
IDS_OC_STILL_NO_STATIC_IP,
g_ocmData.hwnd,
pnocd->strDesc.c_str());
TraceTag(ttidNetOc, "Not handling static IP dependency for %S "
"because we're in unattended mode", pnocd->strDesc.c_str());
}
}
}
hr = HrUninitializeAndReleaseINetCfg(TRUE, pnc, FALSE);
}
}
TraceError("HrHandleStaticIpDependency", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrOcGetINetCfg
//
// Purpose: Obtains an INetCfg to work with
//
// Arguments:
// pnocd [in] OC Data
// fWriteLock [in] TRUE if write lock should be acquired, FALSE if
// not.
// ppnc [out] Returns INetCfg pointer
//
// Returns: S_OK if success, OLE or Win32 error if failed. ERROR_CANCELLED
// is returned if INetCfg is locked and the users cancels.
//
// Author: danielwe 18 Dec 1997
//
// Notes:
//
HRESULT HrOcGetINetCfg(PNETOCDATA pnocd, BOOL fWriteLock, INetCfg **ppnc)
{
HRESULT hr = S_OK;
PWSTR pszDesc;
BOOL fInitCom = TRUE;
Assert(ppnc);
*ppnc = NULL;
top:
AssertSz(!*ppnc, "Can't have valid INetCfg here!");
hr = HrCreateAndInitializeINetCfg(&fInitCom, ppnc, fWriteLock, 0,
SzLoadIds(IDS_OC_CAPTION), &pszDesc);
if ((hr == NETCFG_E_NO_WRITE_LOCK) && !pnocd->fCleanup)
{
// See if we are in "attended" mode or
// we have the /z:netoc_show_unattended_messages options flag set.
if ((g_ocmData.sic.SetupData.OperationFlags & SETUPOP_BATCH) &&
(!g_ocmData.fShowUnattendedMessages))
{
// "Unattended" mode, just report error
ReportEventHrString(pnocd->strDesc.c_str(),
IDS_OC_CANT_GET_LOCK,
pszDesc ? pszDesc : SzLoadIds(IDS_OC_GENERIC_COMP));
CoTaskMemFree(pszDesc);
hr = HRESULT_FROM_WIN32(ERROR_CANCELLED);
}
else
{
// "Attended mode", so interact with user
int nRet;
nRet = NcMsgBoxMc(g_ocmData.hwnd, IDS_OC_CAPTION, IDS_OC_CANT_GET_LOCK,
MB_RETRYCANCEL | MB_DEFBUTTON1 | MB_ICONWARNING,
pnocd->strDesc.c_str(),
pszDesc ? pszDesc : SzLoadIds(IDS_OC_GENERIC_COMP));
CoTaskMemFree(pszDesc);
if (IDRETRY == nRet)
{
goto top;
}
else
{
hr = HRESULT_FROM_WIN32(ERROR_CANCELLED);
}
}
}
TraceError("HrOcGetINetCfg", hr);
return hr;
}
| 32.844673
| 109
| 0.471791
|
npocmaka
|
279721dbb14936e37a675ff91a72024cb1022ce2
| 11,669
|
cpp
|
C++
|
source/Plugins/Generic/CastorGui/CtrlListBox.cpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 245
|
2015-10-29T14:31:45.000Z
|
2022-03-31T13:04:45.000Z
|
source/Plugins/Generic/CastorGui/CtrlListBox.cpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 64
|
2016-03-11T19:45:05.000Z
|
2022-03-31T23:58:33.000Z
|
source/Plugins/Generic/CastorGui/CtrlListBox.cpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 11
|
2018-05-24T09:07:43.000Z
|
2022-03-21T21:05:20.000Z
|
#include "CastorGui/CtrlListBox.hpp"
#include "CastorGui/ControlsManager.hpp"
#include "CastorGui/CtrlStatic.hpp"
#include <Castor3D/Engine.hpp>
#include <Castor3D/Cache/MaterialCache.hpp>
#include <Castor3D/Event/Frame/GpuFunctorEvent.hpp>
#include <Castor3D/Material/Material.hpp>
#include <Castor3D/Material/Pass/Pass.hpp>
#include <Castor3D/Material/Texture/TextureUnit.hpp>
#include <Castor3D/Overlay/BorderPanelOverlay.hpp>
#include <Castor3D/Overlay/Overlay.hpp>
#include <Castor3D/Overlay/PanelOverlay.hpp>
#include <Castor3D/Overlay/TextOverlay.hpp>
#include <CastorUtils/Graphics/Font.hpp>
using namespace castor;
using namespace castor3d;
namespace CastorGui
{
ListBoxCtrl::ListBoxCtrl( String const & p_name
, Engine & engine
, ControlRPtr p_parent
, uint32_t p_id )
: ListBoxCtrl( p_name
, engine
, p_parent
, p_id
, StringArray()
, -1
, Position()
, Size()
, 0
, true )
{
}
ListBoxCtrl::ListBoxCtrl( String const & p_name
, Engine & engine
, ControlRPtr p_parent
, uint32_t p_id
, StringArray const & p_values
, int p_selected
, Position const & p_position
, Size const & p_size
, uint32_t p_style
, bool p_visible )
: Control( ControlType::eListBox
, p_name
, engine
, p_parent
, p_id
, p_position
, p_size
, p_style
, p_visible )
, m_initialValues( p_values )
, m_values( p_values )
, m_selected( p_selected )
{
}
void ListBoxCtrl::setTextMaterial( MaterialRPtr p_material )
{
m_textMaterial = p_material;
}
void ListBoxCtrl::setSelectedItemBackgroundMaterial( MaterialRPtr p_value )
{
m_selectedItemBackgroundMaterial = p_value;
int i = 0;
for ( auto item : m_items )
{
if ( i++ == m_selected )
{
item->setBackgroundMaterial( p_value );
}
}
}
void ListBoxCtrl::setSelectedItemForegroundMaterial( MaterialRPtr p_value )
{
m_selectedItemForegroundMaterial = p_value;
int i = 0;
for ( auto item : m_items )
{
if ( i++ == m_selected )
{
item->setForegroundMaterial( p_value );
}
}
}
void ListBoxCtrl::appendItem( String const & p_value )
{
m_values.push_back( p_value );
if ( getControlsManager() )
{
StaticCtrlSPtr item = doCreateItemCtrl( p_value
, uint32_t( m_values.size() - 1u ) );
getEngine().postEvent( makeGpuFunctorEvent( EventType::ePreRender
, [this, item]( RenderDevice const & device
, QueueData const & queueData )
{
getControlsManager()->create( item );
} ) );
doUpdateItems();
}
else
{
m_initialValues.push_back( p_value );
}
}
void ListBoxCtrl::removeItem( int p_value )
{
if ( uint32_t( p_value ) < m_values.size() && p_value >= 0 )
{
m_values.erase( m_values.begin() + p_value );
if ( uint32_t( p_value ) < m_items.size() )
{
if ( p_value < m_selected )
{
setSelected( m_selected - 1 );
}
else if ( p_value == m_selected )
{
m_selectedItem.reset();
m_selected = -1;
}
auto it = m_items.begin() + p_value;
if ( getControlsManager() )
{
ControlSPtr control = *it;
getEngine().postEvent( makeGpuFunctorEvent( EventType::ePreRender
, [this, control]( RenderDevice const & device
, QueueData const & queueData )
{
getControlsManager()->destroy( control );
} ) );
}
m_items.erase( it );
doUpdateItems();
}
}
}
void ListBoxCtrl::setItemText( int p_index, String const & p_text )
{
auto index = uint32_t( p_index );
if ( index < m_values.size() && p_index >= 0 )
{
m_values[index] = p_text;
if ( index < m_items.size() )
{
StaticCtrlSPtr item = m_items[index];
if ( item )
{
item->setCaption( p_text );
}
}
}
}
String ListBoxCtrl::getItemText( int p_index )
{
auto index = uint32_t( p_index );
String result;
if ( index < m_values.size() )
{
result = m_values[index];
}
return result;
}
void ListBoxCtrl::clear()
{
m_values.clear();
m_items.clear();
m_selectedItem.reset();
m_selected = -1;
}
void ListBoxCtrl::setSelected( int p_value )
{
auto selected = uint32_t( m_selected );
if ( m_selected >= 0 && selected < m_items.size() )
{
StaticCtrlSPtr item = m_items[selected];
if ( item )
{
item->setBackgroundMaterial( getItemBackgroundMaterial() );
item->setForegroundMaterial( getForegroundMaterial() );
m_selectedItem.reset();
}
}
m_selected = p_value;
if ( m_selected >= 0 && selected < m_items.size() )
{
StaticCtrlSPtr item = m_items[selected];
if ( item )
{
item->setBackgroundMaterial( getSelectedItemBackgroundMaterial() );
item->setForegroundMaterial( getSelectedItemForegroundMaterial() );
m_selectedItem = item;
}
}
}
void ListBoxCtrl::setFont( castor::String const & p_font )
{
m_fontName = p_font;
for ( auto item : m_items )
{
item->setFont( m_fontName );
}
}
void ListBoxCtrl::doUpdateItems()
{
Position position;
for ( auto item : m_items )
{
item->setPosition( position );
item->setSize( Size( getSize().getWidth(), DEFAULT_HEIGHT ) );
position.y() += DEFAULT_HEIGHT;
}
BorderPanelOverlaySPtr background = getBackground();
if ( background )
{
background->setPixelSize( Size( getSize().getWidth(), uint32_t( m_items.size() * DEFAULT_HEIGHT ) ) );
}
}
StaticCtrlSPtr ListBoxCtrl::doCreateItemCtrl( String const & p_value
, uint32_t itemIndex )
{
StaticCtrlSPtr item = std::make_shared< StaticCtrl >( getName() + cuT( "_Item" ) + string::toString( itemIndex )
, getEngine()
, this
, p_value
, Position()
, Size( getSize().getWidth(), DEFAULT_HEIGHT ), uint32_t( StaticStyle::eVAlignCenter ) );
item->setCatchesMouseEvents( true );
item->connectNC( MouseEventType::eEnter, [this]( ControlSPtr p_control, MouseEvent const & p_event )
{
onItemMouseEnter( p_control, p_event );
} );
item->connectNC( MouseEventType::eLeave, [this]( ControlSPtr p_control, MouseEvent const & p_event )
{
onItemMouseLeave( p_control, p_event );
} );
item->connectNC( MouseEventType::eReleased, [this]( ControlSPtr p_control, MouseEvent const & p_event )
{
onItemMouseLButtonUp( p_control, p_event );
} );
item->connectNC( KeyboardEventType::ePushed, [this]( ControlSPtr p_control, KeyboardEvent const & p_event )
{
onItemKeyDown( p_control, p_event );
} );
if ( m_fontName.empty() )
{
item->setFont( getControlsManager()->getDefaultFont().lock()->getName() );
}
else
{
item->setFont( m_fontName );
}
m_items.push_back( item );
return item;
}
void ListBoxCtrl::doCreateItem( String const & p_value
, uint32_t itemIndex )
{
StaticCtrlSPtr item = doCreateItemCtrl( p_value, itemIndex );
getControlsManager()->create( item );
item->setBackgroundMaterial( getItemBackgroundMaterial() );
item->setForegroundMaterial( getForegroundMaterial() );
item->setTextMaterial( getTextMaterial() );
item->setVisible( doIsVisible() );
}
void ListBoxCtrl::doCreate()
{
auto material = getTextMaterial();
if ( !material )
{
m_textMaterial = getForegroundMaterial();
}
material = getSelectedItemBackgroundMaterial();
if ( !material )
{
setSelectedItemBackgroundMaterial( getEngine().getMaterialCache().find( cuT( "DarkBlue" ) ).lock().get() );
}
material = getSelectedItemForegroundMaterial();
if ( !material )
{
setSelectedItemForegroundMaterial( getEngine().getMaterialCache().find( cuT( "White" ) ).lock().get() );
}
material = getHighlightedItemBackgroundMaterial();
if ( !material )
{
RgbColour colour = getMaterialColour( *getBackgroundMaterial()->getPass( 0u ) );
colour.red() = std::min( 1.0f, float( colour.red() ) / 2.0f );
colour.green() = std::min( 1.0f, float( colour.green() ) / 2.0f );
colour.blue() = std::min( 1.0f, float( colour.blue() ) / 2.0f );
setHighlightedItemBackgroundMaterial( createMaterial( getEngine(), getBackgroundMaterial()->getName() + cuT( "_Highlight" ), colour ) );
}
setBackgroundBorders( castor::Rectangle( 1, 1, 1, 1 ) );
setSize( Size( getSize().getWidth(), uint32_t( m_values.size() * DEFAULT_HEIGHT ) ) );
EventHandler::connect( KeyboardEventType::ePushed, [this]( KeyboardEvent const & p_event )
{
onKeyDown( p_event );
} );
uint32_t index = 0u;
for ( auto value : m_initialValues )
{
doCreateItem( value, index );
++index;
}
m_initialValues.clear();
doUpdateItems();
setSelected( m_selected );
getControlsManager()->connectEvents( *this );
}
void ListBoxCtrl::doDestroy()
{
CU_Require( getControlsManager() );
auto & manager = *getControlsManager();
manager.disconnectEvents( *this );
for ( auto item : m_items )
{
manager.destroy( item );
}
m_items.clear();
m_selectedItem.reset();
}
void ListBoxCtrl::doSetPosition( Position const & p_value )
{
doUpdateItems();
}
void ListBoxCtrl::doSetSize( Size const & p_value )
{
doUpdateItems();
}
void ListBoxCtrl::doSetBackgroundMaterial( MaterialRPtr p_material )
{
int i = 0;
RgbColour colour = getMaterialColour( *p_material->getPass( 0u ) );
setItemBackgroundMaterial( p_material );
colour.red() = std::min( 1.0f, colour.red() / 2.0f );
colour.green() = std::min( 1.0f, colour.green() / 2.0f );
colour.blue() = std::min( 1.0f, colour.blue() / 2.0f );
setHighlightedItemBackgroundMaterial( createMaterial( getEngine(), getBackgroundMaterial()->getName() + cuT( "_Highlight" ), colour ) );
setMaterialColour( *p_material->getPass( 0u ), colour );
for ( auto item : m_items )
{
if ( i++ != m_selected )
{
item->setBackgroundMaterial( p_material );
}
}
}
void ListBoxCtrl::doSetForegroundMaterial( MaterialRPtr p_material )
{
int i = 0;
for ( auto item : m_items )
{
if ( i++ != m_selected )
{
item->setForegroundMaterial( p_material );
}
}
}
void ListBoxCtrl::doSetVisible( bool p_visible )
{
for ( auto item : m_items )
{
item->setVisible( p_visible );
}
}
void ListBoxCtrl::onItemMouseEnter( ControlSPtr p_control, MouseEvent const & p_event )
{
p_control->setBackgroundMaterial( getHighlightedItemBackgroundMaterial() );
}
void ListBoxCtrl::onItemMouseLeave( ControlSPtr p_control, MouseEvent const & p_event )
{
if ( m_selectedItem.lock() == p_control )
{
p_control->setBackgroundMaterial( getSelectedItemBackgroundMaterial() );
}
else
{
p_control->setBackgroundMaterial( getItemBackgroundMaterial() );
}
}
void ListBoxCtrl::onItemMouseLButtonUp( ControlSPtr p_control, MouseEvent const & p_event )
{
if ( p_event.getButton() == MouseButton::eLeft )
{
if ( m_selectedItem.lock() != p_control )
{
int index = -1;
auto it = m_items.begin();
int i = 0;
while ( index == -1 && it != m_items.end() )
{
if ( *it == p_control )
{
index = i;
}
++it;
++i;
}
setSelected( index );
m_signals[size_t( ListBoxEvent::eSelected )]( m_selected );
}
}
}
void ListBoxCtrl::onKeyDown( KeyboardEvent const & p_event )
{
if ( m_selected != -1 )
{
bool changed = false;
int index = m_selected;
if ( p_event.getKey() == KeyboardKey::eUp )
{
index--;
changed = true;
}
else if ( p_event.getKey() == KeyboardKey::edown )
{
index++;
changed = true;
}
if ( changed )
{
index = std::max( 0, std::min( index, int( m_items.size() - 1 ) ) );
setSelected( index );
m_signals[size_t( ListBoxEvent::eSelected )]( index );
}
}
}
void ListBoxCtrl::onItemKeyDown( ControlSPtr p_control, KeyboardEvent const & p_event )
{
onKeyDown( p_event );
}
}
| 22.880392
| 139
| 0.657554
|
Mu-L
|
2797ce9a09a948dafc437fab640be2fc0b982248
| 686
|
cpp
|
C++
|
src/main.cpp
|
pigatron-industries/arduino_eurorack_template
|
24cf48f14720ee03d5d652802421cb9dcf5fa6d0
|
[
"Unlicense"
] | null | null | null |
src/main.cpp
|
pigatron-industries/arduino_eurorack_template
|
24cf48f14720ee03d5d652802421cb9dcf5fa6d0
|
[
"Unlicense"
] | null | null | null |
src/main.cpp
|
pigatron-industries/arduino_eurorack_template
|
24cf48f14720ee03d5d652802421cb9dcf5fa6d0
|
[
"Unlicense"
] | null | null | null |
#include <Arduino.h>
#include "hwconfig.h"
#include "Config.h"
#include "Hardware.h"
#include "MainController.h"
#include "controllers/TestController.h"
TestController testController = TestController();
MainController mainController = MainController();
void setup() {
Serial.begin(SERIAL_BAUD);
delay(100);
Serial.println();
Serial.println("===============================");
Serial.println("* Pigatron Industries *");
Serial.println("===============================");
Serial.println();
Hardware::hw.init();
mainController.registerController(testController);
mainController.init();
}
void loop() {
mainController.process();
}
| 22.129032
| 54
| 0.625364
|
pigatron-industries
|
2799cac237d65f737878d98c615edc69f4bcb292
| 3,997
|
cpp
|
C++
|
benchmarks/allocator_benchmarks.cpp
|
nanzifan/Umpire-edit
|
990895b527bef0716aaa0fbb0c0f2017e8e15882
|
[
"MIT"
] | null | null | null |
benchmarks/allocator_benchmarks.cpp
|
nanzifan/Umpire-edit
|
990895b527bef0716aaa0fbb0c0f2017e8e15882
|
[
"MIT"
] | null | null | null |
benchmarks/allocator_benchmarks.cpp
|
nanzifan/Umpire-edit
|
990895b527bef0716aaa0fbb0c0f2017e8e15882
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory
//
// Created by David Beckingsale, david@llnl.gov
// LLNL-CODE-747640
//
// All rights reserved.
//
// This file is part of Umpire.
//
// For details, see https://github.com/LLNL/Umpire
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "benchmark/benchmark_api.h"
#include "umpire/config.hpp"
#include "umpire/ResourceManager.hpp"
#include "umpire/Allocator.hpp"
static const size_t max_allocations = 100000;
static void benchmark_allocate(benchmark::State& state, std::string name) {
auto allocator = umpire::ResourceManager::getInstance().getAllocator(name);
void** allocations = new void*[max_allocations];
auto size = state.range(0);
size_t i = 0;
while (state.KeepRunning()) {
if ( i == max_allocations ) {
state.PauseTiming();
for (size_t j = 0; j < max_allocations; j++)
allocator.deallocate(allocations[j]);
i = 0;
state.ResumeTiming();
}
allocations[i++] = allocator.allocate(size);
}
for (size_t j = 0; j < i; j++)
allocator.deallocate(allocations[j]);
delete[] allocations;
}
static void benchmark_deallocate(benchmark::State& state, std::string name) {
auto allocator = umpire::ResourceManager::getInstance().getAllocator(name);
void** allocations = new void*[max_allocations];
auto size = state.range(0);
size_t i = 0;
while (state.KeepRunning()) {
if ( i == 0 || i == max_allocations ) {
state.PauseTiming();
for (size_t j = 0; j < max_allocations; j++)
allocations[j] = allocator.allocate(size);
i = 0;
state.ResumeTiming();
}
allocator.deallocate(allocations[i++]);
}
for (size_t j = i; j < max_allocations; j++)
allocator.deallocate(allocations[j]);
delete[] allocations;
}
static void benchmark_malloc(benchmark::State& state, std::string name) {
auto allocator = umpire::ResourceManager::getInstance().getAllocator(name);
void** allocations = new void*[max_allocations];
auto size = state.range(0);
size_t i = 0;
while (state.KeepRunning()) {
if ( i == max_allocations ) {
state.PauseTiming();
for (size_t j = 0; j < max_allocations; j++)
free(allocations[j]);
i = 0;
state.ResumeTiming();
}
allocations[i++] = malloc(size);
}
for (size_t j = 0; j < i; j++)
free(allocations[j]);
delete[] allocations;
}
static void benchmark_free(benchmark::State& state, std::string name) {
auto allocator = umpire::ResourceManager::getInstance().getAllocator(name);
void** allocations = new void*[max_allocations];
auto size = state.range(0);
size_t i = 0;
while (state.KeepRunning()) {
if ( i == 0 || i == max_allocations ) {
state.PauseTiming();
for (size_t j = 0; j < max_allocations; j++)
allocations[j] = malloc(size);
i = 0;
state.ResumeTiming();
}
free(allocations[i++]);
}
for (size_t j = i; j < max_allocations; j++)
free(allocations[j]);
delete[] allocations;
}
BENCHMARK_CAPTURE(benchmark_allocate, host, std::string("HOST"))->Range(4, 1024);
BENCHMARK_CAPTURE(benchmark_malloc, host, std::string("HOST"))->Range(4, 1024);
BENCHMARK_CAPTURE(benchmark_deallocate, host, std::string("HOST"))->Range(4, 1024);
BENCHMARK_CAPTURE(benchmark_free, host, std::string("HOST"))->Range(4, 1024);
#if defined(UMPIRE_ENABLE_CUDA)
BENCHMARK_CAPTURE(benchmark_allocate, um, std::string("UM"))->Range(4, 1024);
BENCHMARK_CAPTURE(benchmark_deallocate, um, std::string("UM"))->Range(4, 1024);
BENCHMARK_CAPTURE(benchmark_allocate, device, std::string("DEVICE"))->Range(4, 1024);
BENCHMARK_CAPTURE(benchmark_deallocate, device, std::string("DEVICE"))->Range(4, 1024);
#endif
BENCHMARK_MAIN();
| 29.607407
| 87
| 0.641981
|
nanzifan
|
279b22e9f90e6a8cb81f16bf7bfb8a29ee781a25
| 763
|
cpp
|
C++
|
src/random-set/main.cpp
|
schien/practices
|
b248813e51314095c21cf9dc6193d0e1e48550d3
|
[
"MIT"
] | null | null | null |
src/random-set/main.cpp
|
schien/practices
|
b248813e51314095c21cf9dc6193d0e1e48550d3
|
[
"MIT"
] | null | null | null |
src/random-set/main.cpp
|
schien/practices
|
b248813e51314095c21cf9dc6193d0e1e48550d3
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "input_helper.h"
#include "solution.cpp"
int main() {
RandomizedSet rset;
while (std::cin.good()) {
char op;
std::cin >> op;
if (std::cin.eof()) {
break;
}
switch (op) {
case 'i':
{
std::cout << std::boolalpha << rset.insert(next<int>()) << '\n';
break;
}
case 'd':
{
std::cout << std::boolalpha << rset.remove(next<int>()) << '\n';
break;
}
case 'r':
{
try {
std::cout << rset.getRandom() << '\n';
} catch (runtime_error& ex) {
std::cerr << ex.what() << std::endl;
}
break;
}
default:
break;
}
}
return 0;
}
| 18.609756
| 74
| 0.415465
|
schien
|
279c9c7e74e622d478ea12804163ac171fa04981
| 207
|
hpp
|
C++
|
parser/spirit/BoostPrecompile.hpp
|
Vitaliy-Grigoriev/PDL
|
da528e34e91add4e11415e31e01535db04e7043f
|
[
"MIT"
] | 1
|
2019-09-23T08:27:31.000Z
|
2019-09-23T08:27:31.000Z
|
parser/spirit/BoostPrecompile.hpp
|
Vitaliy-Grigoriev/PDL
|
da528e34e91add4e11415e31e01535db04e7043f
|
[
"MIT"
] | null | null | null |
parser/spirit/BoostPrecompile.hpp
|
Vitaliy-Grigoriev/PDL
|
da528e34e91add4e11415e31e01535db04e7043f
|
[
"MIT"
] | null | null | null |
//#define BOOST_SPIRIT_X3_DEBUG
#define BOOST_SPIRIT_NO_STANDARD_WIDE // Disable wide characters for compilation speed.
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
| 34.5
| 88
| 0.816425
|
Vitaliy-Grigoriev
|
279e201b5087433e51391b8b41c1d569115758b8
| 22,572
|
cxx
|
C++
|
main/sw/source/core/text/txtio.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 679
|
2015-01-06T06:34:58.000Z
|
2022-03-30T01:06:03.000Z
|
main/sw/source/core/text/txtio.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 102
|
2017-11-07T08:51:31.000Z
|
2022-03-17T12:13:49.000Z
|
main/sw/source/core/text/txtio.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 331
|
2015-01-06T11:40:55.000Z
|
2022-03-14T04:07:51.000Z
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef DBG_UTIL
#include "viewsh.hxx" // IsDbg()
#include "viewopt.hxx" // IsDbg()
#include "txtatr.hxx"
#include "errhdl.hxx"
#include "txtcfg.hxx"
#include "txtfrm.hxx" // IsDbg()
#include "rootfrm.hxx"
#include "flyfrms.hxx"
#include "inftxt.hxx"
#include "porexp.hxx"
#include "porfld.hxx"
#include "porfly.hxx"
#include "porftn.hxx"
#include "porglue.hxx"
#include "porhyph.hxx"
#include "porlay.hxx"
#include "porlin.hxx"
#include "porref.hxx"
#include "porrst.hxx"
#include "portab.hxx"
#include "portox.hxx"
#include "portxt.hxx"
#include "pordrop.hxx"
#include "pormulti.hxx"
#include "ndhints.hxx"
// So kann man die Layoutstruktur ausgeben lassen
// #define AMA_LAYOUT
#ifdef AMA_LAYOUT
#include <stdio.h>
#include <stdlib.h> // getenv()
#include <flowfrm.hxx>
#include <pagefrm.hxx>
#include <svx/svdobj.hxx>
#include <dflyobj.hxx>
void lcl_OutFollow( XubString &rTmp, const SwFrm* pFrm )
{
if( pFrm->IsFlowFrm() )
{
const SwFlowFrm *pFlow = SwFlowFrm::CastFlowFrm( pFrm );
if( pFlow->IsFollow() || pFlow->GetFollow() )
{
rTmp += "(";
if( pFlow->IsFollow() )
rTmp += ".";
if( pFlow->GetFollow() )
{
MSHORT nFrmId = pFlow->GetFollow()->GetFrm()->GetFrmId();
rTmp += nFrmId;
}
rTmp += ")";
}
}
}
void lcl_OutFrame( SvFileStream& rStr, const SwFrm* pFrm, ByteString& rSp, sal_Bool bNxt )
{
if( !pFrm )
return;
KSHORT nSpc = 0;
MSHORT nFrmId = pFrm->GetFrmId();
ByteString aTmp;
if( pFrm->IsLayoutFrm() )
{
if( pFrm->IsRootFrm() )
aTmp = "R";
else if( pFrm->IsPageFrm() )
aTmp = "P";
else if( pFrm->IsBodyFrm() )
aTmp = "B";
else if( pFrm->IsColumnFrm() )
aTmp = "C";
else if( pFrm->IsTabFrm() )
aTmp = "Tb";
else if( pFrm->IsRowFrm() )
aTmp = "Rw";
else if( pFrm->IsCellFrm() )
aTmp = "Ce";
else if( pFrm->IsSctFrm() )
aTmp = "S";
else if( pFrm->IsFlyFrm() )
{
aTmp = "F";
const SwFlyFrm *pFly = (SwFlyFrm*)pFrm;
if( pFly->IsFlyInCntFrm() )
aTmp += "in";
else if( pFly->IsFlyAtCntFrm() )
{
aTmp += "a";
if( pFly->IsAutoPos() )
aTmp += "u";
else
aTmp += "t";
}
else
aTmp += "l";
}
else if( pFrm->IsHeaderFrm() )
aTmp = "H";
else if( pFrm->IsFooterFrm() )
aTmp = "Fz";
else if( pFrm->IsFtnContFrm() )
aTmp = "Fc";
else if( pFrm->IsFtnFrm() )
aTmp = "Fn";
else
aTmp = "?L?";
aTmp += nFrmId;
lcl_OutFollow( aTmp, pFrm );
aTmp += " ";
rStr << aTmp;
nSpc = aTmp.Len();
rSp.Expand( nSpc + rSp.Len() );
lcl_OutFrame( rStr, ((SwLayoutFrm*)pFrm)->Lower(), rSp, sal_True );
}
else
{
if( pFrm->IsTxtFrm() )
aTmp = "T";
else if( pFrm->IsNoTxtFrm() )
aTmp = "N";
else
aTmp = "?C?";
aTmp += nFrmId;
lcl_OutFollow( aTmp, pFrm );
aTmp += " ";
rStr << aTmp;
nSpc = aTmp.Len();
rSp.Expand( nSpc + rSp.Len() );
}
if( pFrm->IsPageFrm() )
{
const SwPageFrm* pPg = (SwPageFrm*)pFrm;
const SwSortedObjs *pSorted = pPg->GetSortedObjs();
const MSHORT nCnt = pSorted ? pSorted->Count() : 0;
if( nCnt )
{
for( MSHORT i=0; i < nCnt; ++i )
{
// --> OD 2004-07-07 #i28701# - consider changed type of
// <SwSortedObjs> entries
SwAnchoredObject* pAnchoredObj = (*pSorted)[ i ];
if( pAnchoredObj->ISA(SwFlyFrm) )
{
SwFlyFrm* pFly = static_cast<SwFlyFrm*>(pAnchoredObj);
lcl_OutFrame( rStr, pFly, rSp, sal_False );
}
else
{
aTmp = pAnchoredObj->GetDrawObj()->IsUnoObj() ? "UNO" : "Drw";
rStr << aTmp;
}
// <--
if( i < nCnt - 1 )
rStr << endl << rSp;
}
}
}
else if( pFrm->GetDrawObjs() )
{
MSHORT nCnt = pFrm->GetDrawObjs()->Count();
if( nCnt )
{
for( MSHORT i=0; i < nCnt; ++i )
{
// --> OD 2004-07-07 #i28701# - consider changed type of
// <SwSortedObjs> entries
SwAnchoredObject* pAnchoredObj = (*pFrm->GetDrawObjs())[ i ];
if( pAnchoredObj->ISA(SwFlyFrm) )
{
SwFlyFrm* pFly = static_cast<SwFlyFrm*>(pAnchoredObj);
lcl_OutFrame( rStr, pFly, rSp, sal_False );
}
else
{
aTmp = pAnchoredObj->GetDrawObj()->IsUnoObj() ? "UNO" : "Drw";
rStr << aTmp;
}
if( i < nCnt - 1 )
rStr << endl << rSp;
}
}
}
if( nSpc )
rSp.Erase( rSp.Len() - nSpc );
if( bNxt && pFrm->GetNext() )
{
do
{
pFrm = pFrm->GetNext();
rStr << endl << rSp;
lcl_OutFrame( rStr, pFrm, rSp, sal_False );
} while ( pFrm->GetNext() );
}
}
void LayOutPut( const SwFrm* pFrm )
{
static char* pOutName = 0;
const sal_Bool bFirstOpen = pOutName ? sal_False : sal_True;
if( bFirstOpen )
{
char *pPath = getenv( "TEMP" );
char *pName = "layout.txt";
if( !pPath )
pOutName = pName;
else
{
const int nLen = strlen(pPath);
// fuer dieses new wird es kein delete geben.
pOutName = new char[nLen + strlen(pName) + 3];
if(nLen && (pPath[nLen-1] == '\\') || (pPath[nLen-1] == '/'))
snprintf( pOutName, sizeof(pOutName), "%s%s", pPath, pName );
else
snprintf( pOutName, sizeof(pOutName), "%s/%s", pPath, pName );
}
}
SvFileStream aStream( pOutName, (bFirstOpen
? STREAM_WRITE | STREAM_TRUNC
: STREAM_WRITE ));
if( !aStream.GetError() )
{
if ( bFirstOpen )
aStream << "Layout-Struktur";
else
aStream.Seek( STREAM_SEEK_TO_END );
aStream << endl;
aStream << "---------------------------------------------" << endl;
XubString aSpace;
lcl_OutFrame( aStream, pFrm, aSpace, sal_False );
}
}
#endif
SvStream &operator<<( SvStream &rOs, const SwpHints & ) //$ ostream
{
rOs << " {HINTS:";
// REMOVED
rOs << '}';
return rOs;
}
/*************************************************************************
* IsDbg()
*************************************************************************/
sal_Bool IsDbg( const SwTxtFrm *pFrm )
{
if( pFrm && pFrm->getRootFrm()->GetCurrShell() )
return pFrm->getRootFrm()->GetCurrShell()->GetViewOptions()->IsTest4();
else
return sal_False;
}
#if OSL_DEBUG_LEVEL < 2
static void Error()
{
// wegen PM und BCC
sal_Bool bFalse = sal_False;
ASSERT( bFalse, "txtio: No debug version" );
}
#define IMPL_OUTOP(class) \
SvStream &class::operator<<( SvStream &rOs ) const /*$ostream*/\
{ \
Error(); \
return rOs; \
}
IMPL_OUTOP( SwTxtPortion )
IMPL_OUTOP( SwLinePortion )
IMPL_OUTOP( SwBreakPortion )
IMPL_OUTOP( SwGluePortion )
IMPL_OUTOP( SwFldPortion )
IMPL_OUTOP( SwHiddenPortion )
IMPL_OUTOP( SwHyphPortion )
IMPL_OUTOP( SwFixPortion )
IMPL_OUTOP( SwFlyPortion )
IMPL_OUTOP( SwFlyCntPortion )
IMPL_OUTOP( SwMarginPortion )
IMPL_OUTOP( SwNumberPortion )
IMPL_OUTOP( SwBulletPortion )
IMPL_OUTOP( SwGrfNumPortion )
IMPL_OUTOP( SwLineLayout )
IMPL_OUTOP( SwParaPortion )
IMPL_OUTOP( SwFtnPortion )
IMPL_OUTOP( SwFtnNumPortion )
IMPL_OUTOP( SwTmpEndPortion )
IMPL_OUTOP( SwHyphStrPortion )
IMPL_OUTOP( SwExpandPortion )
IMPL_OUTOP( SwBlankPortion )
IMPL_OUTOP( SwToxPortion )
IMPL_OUTOP( SwRefPortion )
IMPL_OUTOP( SwIsoToxPortion )
IMPL_OUTOP( SwIsoRefPortion )
IMPL_OUTOP( SwSoftHyphPortion )
IMPL_OUTOP( SwSoftHyphStrPortion )
IMPL_OUTOP( SwTabPortion )
IMPL_OUTOP( SwTabLeftPortion )
IMPL_OUTOP( SwTabRightPortion )
IMPL_OUTOP( SwTabCenterPortion )
IMPL_OUTOP( SwTabDecimalPortion )
IMPL_OUTOP( SwPostItsPortion )
IMPL_OUTOP( SwQuoVadisPortion )
IMPL_OUTOP( SwErgoSumPortion )
IMPL_OUTOP( SwHolePortion )
IMPL_OUTOP( SwDropPortion )
IMPL_OUTOP( SwKernPortion )
IMPL_OUTOP( SwArrowPortion )
IMPL_OUTOP( SwMultiPortion )
IMPL_OUTOP( SwCombinedPortion )
const char *GetPortionName( const MSHORT )
{
return 0;
}
const char *GetPrepName( const PrepareHint )
{
return 0;
}
void SwLineLayout::DebugPortions( SvStream &, const XubString &, //$ ostream
const xub_StrLen )
{
}
const char *GetLangName( const MSHORT )
{
return 0;
}
#else
# include <limits.h>
# include <stdlib.h>
# include "swtypes.hxx" // ZTCCONST
# include "swfont.hxx" // SwDropPortion
CONSTCHAR( pClose, "} " );
/*************************************************************************
* GetPortionName()
*************************************************************************/
CONSTCHAR( pPOR_LIN, "LIN" );
CONSTCHAR( pPOR_TXT, "TXT" );
CONSTCHAR( pPOR_SHADOW, "SHADOW" );
CONSTCHAR( pPOR_TAB, "TAB" );
CONSTCHAR( pPOR_TABLEFT, "TABLEFT" );
CONSTCHAR( pPOR_TABRIGHT, "TABRIGHT" );
CONSTCHAR( pPOR_TABCENTER, "TABCENTER" );
CONSTCHAR( pPOR_TABDECIMAL, "TABDECIMAL" );
CONSTCHAR( pPOR_EXP, "EXP" );
CONSTCHAR( pPOR_HYPH, "HYPH" );
CONSTCHAR( pPOR_HYPHSTR, "HYPHSTR" );
CONSTCHAR( pPOR_FLD, "FLD" );
CONSTCHAR( pPOR_FIX, "FIX" );
CONSTCHAR( pPOR_FLY, "FLY" );
CONSTCHAR( pPOR_FLYCNT, "FLYCNT" );
CONSTCHAR( pPOR_MARGIN, "MARGIN" );
CONSTCHAR( pPOR_GLUE, "GLUE" );
CONSTCHAR( pPOR_HOLE, "HOLE" );
CONSTCHAR( pPOR_END, "END" );
CONSTCHAR( pPOR_BRK, "BRK" );
CONSTCHAR( pPOR_LAY, "LAY" );
CONSTCHAR( pPOR_BLANK, "BLANK" );
CONSTCHAR( pPOR_FTN, "FTN" );
CONSTCHAR( pPOR_FTNNUM, "FTNNUM" );
CONSTCHAR( pPOR_POSTITS, "POSTITS" );
CONSTCHAR( pPOR_SOFTHYPH, "SOFTHYPH" );
CONSTCHAR( pPOR_SOFTHYPHSTR, "SOFTHYPHSTR" );
CONSTCHAR( pPOR_TOX, "TOX" );
CONSTCHAR( pPOR_REF, "REF" );
CONSTCHAR( pPOR_ISOTOX, "ISOTOX" );
CONSTCHAR( pPOR_ISOREF, "ISOREF" );
CONSTCHAR( pPOR_HIDDEN, "Hidden" );
CONSTCHAR( pPOR_QUOVADIS, "QuoVadis" );
CONSTCHAR( pPOR_ERGOSUM, "ErgoSum" );
CONSTCHAR( pPOR_NUMBER, "NUMBER" );
CONSTCHAR( pPOR_BULLET, "BULLET" );
CONSTCHAR( pPOR_UNKW, "UNKW" );
CONSTCHAR( pPOR_PAR, "PAR" );
const char *GetPortionName( const MSHORT /*nType*/ )
{
return 0;
}
CONSTCHAR( pPREP_CLEAR, "CLEAR" );
CONSTCHAR( pPREP_WIDOWS_ORPHANS, "WIDOWS_ORPHANS" );
CONSTCHAR( pPREP_FIXSIZE_CHG, "FIXSIZE_CHG" );
CONSTCHAR( pPREP_FOLLOW_FOLLOWS, "FOLLOW_FOLLOWS" );
CONSTCHAR( pPREP_ADJUST_FRM, "ADJUST_FRM" );
CONSTCHAR( pPREP_FREE_SPACE, "FREE_SPACE" );
CONSTCHAR( pPREP_FLY_CHGD, "FLY_CHGD" );
CONSTCHAR( pPREP_FLY_ATTR_CHG, "FLY_ATTR_CHG" );
CONSTCHAR( pPREP_FLY_ARRIVE, "FLY_ARRIVE" );
CONSTCHAR( pPREP_FLY_LEAVE, "FLY_LEAVE" );
CONSTCHAR( pPREP_VIEWOPT, "VIEWOPT" );
CONSTCHAR( pPREP_FTN, "FTN" );
CONSTCHAR( pPREP_POS_CHGD, "POS" );
CONSTCHAR( pPREP_UL_SPACE, "UL_SPACE" );
CONSTCHAR( pPREP_MUST_FIT, "MUST_FIT" );
CONSTCHAR( pPREP_WIDOWS, "ORPHANS" );
CONSTCHAR( pPREP_QUOVADIS, "QUOVADIS" );
CONSTCHAR( pPREP_PAGE, "PAGE" );
const char *GetPrepName( const PrepareHint ePrep )
{
// Kurz und schmerzlos:
const char *ppNameArr[PREP_END] =
{
pPREP_CLEAR, pPREP_WIDOWS_ORPHANS, pPREP_FIXSIZE_CHG,
pPREP_FOLLOW_FOLLOWS, pPREP_ADJUST_FRM, pPREP_FREE_SPACE,
pPREP_FLY_CHGD, pPREP_FLY_ATTR_CHG, pPREP_FLY_ARRIVE,
pPREP_FLY_LEAVE, pPREP_VIEWOPT, pPREP_FTN, pPREP_POS_CHGD,
pPREP_UL_SPACE, pPREP_MUST_FIT, pPREP_WIDOWS, pPREP_QUOVADIS,
pPREP_PAGE
};
ASSERT( ePrep < PREP_END, "GetPrepName: unknown PrepareHint" );
return( ppNameArr[ePrep] );
}
/*************************************************************************
* SwLineLayout::DebugPortions()
*
* DebugPortion() iteriert ueber alle Portions einer Zeile und deckt die
* internen Strukturen auf.
* Im Gegensatz zum Ausgabe-Operator werden auch die Textteile ausgegeben.
*************************************************************************/
void SwLineLayout::DebugPortions( SvStream &rOs, const XubString &/*rTxt*/, //$ ostream
const xub_StrLen /*nStart*/ )
{
SwLinePortion *pPortion2 = GetPortion();
xub_StrLen nPos = 0;
MSHORT nNr = 0;
KSHORT nPrtWidth, nLastPrt;
nPrtWidth = nLastPrt = 0;
SwLinePortion::operator<<( rOs );
rOs << '\"' << endl;
while( pPortion2 )
{
DBG_LOOP;
SwTxtPortion *pTxtPor = pPortion2->InTxtGrp() ?
(SwTxtPortion *)pPortion2 : NULL ;
(void)pTxtPor;
++nNr;
nLastPrt = nPrtWidth;
nPrtWidth = nPrtWidth + pPortion2->PrtWidth();
rOs << "\tNr:" << nNr
<< " Pos:" << nPos
<< " Org:" << nLastPrt
<< endl;
rOs << "\t";
pPortion2->operator<<( rOs );
rOs << endl;
nPos = nPos + pPortion2->GetLen();
pPortion2 = pPortion2->GetPortion();
}
}
const char *GetLangName( const MSHORT /*nLang*/ )
{
return "???";
}
SvStream &SwLinePortion::operator<<( SvStream &rOs ) const //$ ostream
{
rOs << " {";
rOs << "L:" << nLineLength;
rOs << " H:" << Height();
rOs << " W:" << PrtWidth();
rOs << " A:" << nAscent;
rOs << pClose;
return rOs;
}
SvStream &SwTxtPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TXT:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwTmpEndPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {END:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
if( PrtWidth() )
rOs << "(view)";
rOs << pClose;
return rOs;
}
SvStream &SwBreakPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {BREAK:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwKernPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {KERN:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwArrowPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {ARROW:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwMultiPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {MULTI:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwCombinedPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {COMBINED:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwLineLayout::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {LINE:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
SwLinePortion *pPos = GetPortion();
while( pPos )
{
DBG_LOOP;
rOs << "\t";
pPos->operator<<( rOs );
pPos = pPos->GetPortion();
}
rOs << pClose;
return rOs;
}
SvStream &SwGluePortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {GLUE:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << " F:" << GetFixWidth();
rOs << " G:" << GetPrtGlue();
rOs << pClose;
return rOs;
}
SvStream &SwFixPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {FIX:" );
rOs << pTxt;
SwGluePortion::operator<<( rOs );
rOs << " Fix:" << nFix;
rOs << pClose;
return rOs;
}
SvStream &SwFlyPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {FLY:" );
rOs << pTxt;
SwFixPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwMarginPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {MAR:" );
rOs << pTxt;
SwGluePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwFlyCntPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {FLYCNT:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
if( bDraw )
{
CONSTCHAR( pTxt2, " {DRAWINCNT" );
rOs << pTxt2;
rOs << pClose;
}
else
{
CONSTCHAR( pTxt2, " {FRM:" );
rOs << pTxt2;
rOs << " {FRM:" << GetFlyFrm()->Frm() << pClose;
rOs << " {PRT:" << GetFlyFrm()->Prt() << pClose;
rOs << pClose;
}
rOs << pClose;
return rOs;
}
SvStream &SwExpandPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {EXP:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwFtnPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {FTN:" );
rOs << pTxt;
SwExpandPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwFtnNumPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {FTNNUM:" );
rOs << pTxt;
SwNumberPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwNumberPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {NUMBER:" );
rOs << pTxt;
SwExpandPortion::operator<<( rOs );
rOs << " Exp:\"" << '\"';
rOs << pClose;
return rOs;
}
SvStream &SwBulletPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {BULLET:" );
rOs << pTxt;
SwNumberPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwGrfNumPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {GRFNUM:" );
rOs << pTxt;
SwNumberPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwHiddenPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {Hidden:" );
rOs << pTxt;
SwFldPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwToxPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TOX:" );
rOs << pTxt;
SwTxtPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwRefPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {Ref:" );
rOs << pTxt;
SwTxtPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwIsoToxPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {ISOTOX:" );
rOs << pTxt;
SwToxPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwIsoRefPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {ISOREF:" );
rOs << pTxt;
SwRefPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwHyphPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {HYPH:" );
rOs << pTxt;
SwExpandPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwHyphStrPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {HYPHSTR:" );
rOs << pTxt;
SwExpandPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwSoftHyphPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {SOFTHYPH:" );
rOs << pTxt;
SwHyphPortion::operator<<( rOs );
rOs << (IsExpand() ? " on" : " off");
rOs << pClose;
return rOs;
}
SvStream &SwSoftHyphStrPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {SOFTHYPHSTR:" );
rOs << pTxt;
SwHyphStrPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwBlankPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {BLANK:" );
rOs << pTxt;
SwExpandPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwFldPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {FLD:" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
if( IsFollow() )
rOs << " F!";
rOs << pClose;
return rOs;
}
SvStream &SwPostItsPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {POSTITS" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwTabPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TAB" );
rOs << pTxt;
SwFixPortion::operator<<( rOs );
rOs << " T:" << nTabPos;
if( IsFilled() )
rOs << " \"" << cFill << '\"';
rOs << pClose;
return rOs;
}
SvStream &SwTabLeftPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TABLEFT" );
rOs << pTxt;
SwTabPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwTabRightPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TABRIGHT" );
rOs << pTxt;
SwTabPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwTabCenterPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TABCENTER" );
rOs << pTxt;
SwTabPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwTabDecimalPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {TABDECIMAL" );
rOs << pTxt;
SwTabPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwParaPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {PAR" );
rOs << pTxt;
SwLineLayout::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwHolePortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {HOLE" );
rOs << pTxt;
SwLinePortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwQuoVadisPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {QUOVADIS" );
rOs << pTxt;
SwFldPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &SwErgoSumPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {ERGOSUM" );
rOs << pTxt;
SwFldPortion::operator<<( rOs );
rOs << pClose;
return rOs;
}
SvStream &operator<<( SvStream &rOs, const SwTxtSizeInfo &rInf ) //$ ostream
{
CONSTCHAR( pTxt, " {SIZEINFO:" );
rOs << pTxt;
rOs << ' ' << (rInf.OnWin() ? "WIN:" : "PRT:" );
rOs << " Idx:" << rInf.GetIdx();
rOs << " Len:" << rInf.GetLen();
rOs << pClose;
return rOs;
}
SvStream &SwDropPortion::operator<<( SvStream &rOs ) const //$ ostream
{
CONSTCHAR( pTxt, " {DROP:" );
rOs << pTxt;
SwTxtPortion::operator<<( rOs );
if( pPart && nDropHeight )
{
rOs << " H:" << nDropHeight;
rOs << " L:" << nLines;
rOs <<" Fnt:" << pPart->GetFont().GetHeight();
if( nX || nY )
rOs << " [" << nX << '/' << nY << ']';
}
rOs << pClose;
return rOs;
}
#endif /* OSL_DEBUG_LEVEL */
#endif // DBG_UTIL
| 23.885714
| 90
| 0.616073
|
Grosskopf
|
279ebb6034b6a93be79868b35fc5586368c57798
| 825
|
cpp
|
C++
|
src/error_handling_tk205.cpp
|
open205/libtk205
|
48b9c13623bd737e80cc9323d82a217afd927d04
|
[
"BSD-3-Clause"
] | 1
|
2021-12-09T00:04:43.000Z
|
2021-12-09T00:04:43.000Z
|
src/error_handling_tk205.cpp
|
open205/libtk205
|
48b9c13623bd737e80cc9323d82a217afd927d04
|
[
"BSD-3-Clause"
] | null | null | null |
src/error_handling_tk205.cpp
|
open205/libtk205
|
48b9c13623bd737e80cc9323d82a217afd927d04
|
[
"BSD-3-Clause"
] | null | null | null |
#include "error_handling_tk205.h"
#include <map>
#include <iostream>
#include <string_view>
namespace tk205 {
msg_handler _error_handler;
void Set_error_handler(msg_handler handler)
{
_error_handler = std::move(handler);
}
void Show_message(msg_severity severity, const std::string &message)
{
static std::map<msg_severity, std::string_view> severity_str {
{msg_severity::DEBUG_205, "DEBUG"},
{msg_severity::INFO_205, "INFO"},
{msg_severity::WARN_205, "WARN"},
{msg_severity::ERR_205, "ERR"}
};
if (!_error_handler)
{
//std::cout << severity_str[severity] << ": " << message << std::endl;
}
else
{
_error_handler(severity, message, nullptr);
}
}
}
| 24.264706
| 82
| 0.578182
|
open205
|
279fca8026a43de5182a515cb704965a388aa3a8
| 6,403
|
cpp
|
C++
|
src/lllarith.cpp
|
gligneul/Lua-LLVM
|
1579b46e28d9ca16b70b9e9f3c11b389734eca00
|
[
"MIT"
] | 12
|
2016-02-26T02:50:59.000Z
|
2021-05-27T00:56:16.000Z
|
src/lllarith.cpp
|
gligneul/Lua-LLVM
|
1579b46e28d9ca16b70b9e9f3c11b389734eca00
|
[
"MIT"
] | null | null | null |
src/lllarith.cpp
|
gligneul/Lua-LLVM
|
1579b46e28d9ca16b70b9e9f3c11b389734eca00
|
[
"MIT"
] | 1
|
2021-03-25T18:56:50.000Z
|
2021-03-25T18:56:50.000Z
|
/*
** LLL - Lua Low Level
** September, 2015
** Author: Gabriel de Quadros Ligneul
** Copyright Notice for LLL: see lllcore.h
**
** lllarith.cpp
** Compiles the arithmetics opcodes
*/
#include "lllarith.h"
#include "lllcompilerstate.h"
#include "lllvalue.h"
extern "C" {
#include "lprefix.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lvm.h"
}
namespace lll {
Arith::Arith(CompilerState& cs, Stack& stack) :
Opcode(cs, stack),
ra_(stack.GetR(GETARG_A(cs.instr_))),
rkb_(stack.GetRK(GETARG_B(cs.instr_))),
rkc_(stack.GetRK(GETARG_C(cs.instr_))),
x_(rkb_),
y_(rkc_),
check_y_(cs.CreateSubBlock("check_y")),
intop_(cs.CreateSubBlock("intop", check_y_)),
floatop_(cs.CreateSubBlock("floatop", intop_)),
tmop_(cs.CreateSubBlock("tmop", floatop_)),
x_int_(nullptr),
x_float_(nullptr) {
}
void Arith::Compile() {
CheckXTag();
CheckYTag();
ComputeInt();
ComputeFloat();
ComputeTaggedMethod();
}
void Arith::CheckXTag() {
auto check_y_int = cs_.CreateSubBlock("is_y_int");
auto check_x_float = cs_.CreateSubBlock("is_x_float", check_y_int);
auto tonumber_x = cs_.CreateSubBlock("tonumber_x", check_x_float);
cs_.B_.SetInsertPoint(entry_);
auto xtag = x_.GetTag();
auto is_x_int = cs_.B_.CreateICmpEQ(xtag, cs_.MakeInt(LUA_TNUMINT));
cs_.B_.CreateCondBr(is_x_int, check_y_int, check_x_float);
cs_.B_.SetInsertPoint(check_y_int);
x_int_ = x_.GetInteger();
auto floatt = cs_.rt_.GetType("lua_Number");
auto x_itof = cs_.B_.CreateSIToFP(x_int_, floatt, x_int_->getName() + "_flt");
x_float_inc_.push_back({x_itof, check_y_int});
auto is_y_int = y_.HasTag(LUA_TNUMINT);
cs_.B_.CreateCondBr(is_y_int, intop_, check_y_);
cs_.B_.SetInsertPoint(check_x_float);
x_float_inc_.push_back({x_.GetFloat(), check_x_float});
auto is_x_float = cs_.B_.CreateICmpEQ(xtag, cs_.MakeInt(LUA_TNUMFLT));
cs_.B_.CreateCondBr(is_x_float, check_y_, tonumber_x);
cs_.B_.SetInsertPoint(tonumber_x);
auto args = {x_.GetTValue(), cs_.values_.xnumber};
auto tonumberret = cs_.CreateCall("luaV_tonumber_", args);
auto x_converted = cs_.B_.CreateLoad(cs_.values_.xnumber);
x_float_inc_.push_back({x_converted, tonumber_x});
auto converted = cs_.ToBool(tonumberret);
cs_.B_.CreateCondBr(converted, check_y_, tmop_);
}
void Arith::CheckYTag() {
auto tonumber_y = cs_.CreateSubBlock("tonumber_y", check_y_);
cs_.B_.SetInsertPoint(check_y_);
auto floatt = cs_.rt_.GetType("lua_Number");
x_float_ = CreatePHI(floatt, x_float_inc_, "xfloat");
y_float_inc_.push_back({y_.GetFloat(), check_y_});
auto is_y_float = y_.HasTag(LUA_TNUMFLT);
cs_.B_.CreateCondBr(is_y_float, floatop_, tonumber_y);
cs_.B_.SetInsertPoint(tonumber_y);
auto args = {y_.GetTValue(), cs_.values_.ynumber};
auto tonumberret = cs_.CreateCall("luaV_tonumber_", args);
auto y_converted = cs_.B_.CreateLoad(cs_.values_.ynumber);
y_float_inc_.push_back({y_converted, tonumber_y});
auto converted = cs_.ToBool(tonumberret);
cs_.B_.CreateCondBr(converted, floatop_, tmop_);
}
void Arith::ComputeInt() {
cs_.B_.SetInsertPoint(intop_);
auto y_int = y_.GetInteger();
if (HasIntegerOp()) {
ra_.SetInteger(PerformIntOp(x_int_, y_int));
cs_.B_.CreateBr(exit_);
} else {
auto floatt = cs_.rt_.GetType("lua_Number");
auto x_float = cs_.B_.CreateSIToFP(x_int_, floatt);
auto y_float = cs_.B_.CreateSIToFP(y_int, floatt);
ra_.SetFloat(PerformFloatOp(x_float, y_float));
cs_.B_.CreateBr(exit_);
}
}
void Arith::ComputeFloat() {
cs_.B_.SetInsertPoint(floatop_);
auto floatt = cs_.rt_.GetType("lua_Number");
auto y_float = CreatePHI(floatt, y_float_inc_, "yfloat");
ra_.SetFloat(PerformFloatOp(x_float_, y_float));
cs_.B_.CreateBr(exit_);
}
void Arith::ComputeTaggedMethod() {
cs_.B_.SetInsertPoint(tmop_);
auto args = {
cs_.values_.state,
x_.GetTValue(),
y_.GetTValue(),
ra_.GetTValue(),
cs_.MakeInt(GetMethodTag())
};
cs_.CreateCall("luaT_trybinTM", args);
stack_.Update();
cs_.B_.CreateBr(exit_);
}
bool Arith::HasIntegerOp() {
switch (GET_OPCODE(cs_.instr_)) {
case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD: case OP_IDIV:
return true;
default:
break;
}
return false;
}
llvm::Value* Arith::PerformIntOp(llvm::Value* lhs, llvm::Value* rhs) {
auto name = "result";
switch (GET_OPCODE(cs_.instr_)) {
case OP_ADD:
return cs_.B_.CreateAdd(lhs, rhs, name);
case OP_SUB:
return cs_.B_.CreateSub(lhs, rhs, name);
case OP_MUL:
return cs_.B_.CreateMul(lhs, rhs, name);
case OP_MOD:
return cs_.CreateCall("luaV_mod", {cs_.values_.state, lhs, rhs},
name);
case OP_IDIV:
return cs_.CreateCall("luaV_div", {cs_.values_.state, lhs, rhs},
name);
default:
break;
}
assert(false);
return nullptr;
}
llvm::Value* Arith::PerformFloatOp(llvm::Value* lhs, llvm::Value* rhs) {
auto name = "result";
switch (GET_OPCODE(cs_.instr_)) {
case OP_ADD:
return cs_.B_.CreateFAdd(lhs, rhs, name);
case OP_SUB:
return cs_.B_.CreateFSub(lhs, rhs, name);
case OP_MUL:
return cs_.B_.CreateFMul(lhs, rhs, name);
case OP_MOD:
return cs_.CreateCall("LLLNumMod", {lhs, rhs}, name);
case OP_POW:
return cs_.CreateCall(STRINGFY2(l_mathop(pow)), {lhs, rhs}, name);
case OP_DIV:
return cs_.B_.CreateFDiv(lhs, rhs, name);
case OP_IDIV:
return cs_.CreateCall(STRINGFY2(l_mathop(floor)),
{cs_.B_.CreateFDiv(lhs, rhs, name)}, "floor");
default:
break;
}
assert(false);
return nullptr;
}
int Arith::GetMethodTag() {
switch (GET_OPCODE(cs_.instr_)) {
case OP_ADD: return TM_ADD;
case OP_SUB: return TM_SUB;
case OP_MUL: return TM_MUL;
case OP_MOD: return TM_MOD;
case OP_POW: return TM_POW;
case OP_DIV: return TM_DIV;
case OP_IDIV: return TM_IDIV;
default: break;
}
assert(false);
return -1;
}
}
| 30.636364
| 82
| 0.640325
|
gligneul
|
27a1ee71243b7276ca7d333f8a7d3dde4bc3800b
| 785
|
cpp
|
C++
|
Codeforces/1108A-Two_distinct_points.cpp
|
Pankajcoder1/Competitive_programming
|
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
|
[
"MIT"
] | null | null | null |
Codeforces/1108A-Two_distinct_points.cpp
|
Pankajcoder1/Competitive_programming
|
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
|
[
"MIT"
] | null | null | null |
Codeforces/1108A-Two_distinct_points.cpp
|
Pankajcoder1/Competitive_programming
|
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
|
[
"MIT"
] | 1
|
2020-10-02T04:51:22.000Z
|
2020-10-02T04:51:22.000Z
|
/*
written by Pankaj Kumar.
country:-INDIA
Institute: National Institute of Technology, Uttarakhand
*/
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<string.h>
#define pan cin.tie(0);cout.tie(0);ios_base::sync_with_stdio(0);
#define mod 1000000007;
using namespace std;
typedef long long ll ;
#define line cout<<endl;
int main()
{
pan;
ll t;
cin>>t;
while(t--)
{
ll l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
if(l2!=l1)
cout<<l1<<" "<<l2<<endl;
else
cout<<l1<<" "<<l2+1<<endl;
}
}
// * -----------------END OF PROGRAM --------------------*/
/*
* stuff you should look before submission
* constraint and time limit
* int overflow
* special test case (n=0||n=1||n=2)
* don't get stuck on one approach if you get wrong answer
*/
| 19.625
| 64
| 0.628025
|
Pankajcoder1
|
27a1f8f0e9171053961ab73f49b30d853cdbf9d1
| 25,258
|
cpp
|
C++
|
test/code/myauth/myauth_test.cpp
|
Bhaskers-Blu-Org2/MySQL-Provider
|
211f79e98e7f34a13c4fb7c01f3aaaefc0dada63
|
[
"MIT"
] | 5
|
2016-06-18T14:41:36.000Z
|
2019-01-10T09:46:20.000Z
|
test/code/myauth/myauth_test.cpp
|
microsoft/MySQL-Provider
|
211f79e98e7f34a13c4fb7c01f3aaaefc0dada63
|
[
"MIT"
] | 5
|
2016-04-12T23:00:45.000Z
|
2019-03-28T23:04:57.000Z
|
test/code/myauth/myauth_test.cpp
|
microsoft/MySQL-Provider
|
211f79e98e7f34a13c4fb7c01f3aaaefc0dada63
|
[
"MIT"
] | 6
|
2019-09-18T00:11:36.000Z
|
2021-11-10T10:07:03.000Z
|
/*
* --------------------------------- START OF LICENSE ----------------------------
*
* MySQL cimprov ver. 1.0
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* MIT 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.
*
* ---------------------------------- END OF LICENSE -----------------------------
*/
/*--------------------------------------------------------------------------------
Created date 2015-01-23 08:45:00
MySQL Authentication Tool unit tests.
*/
/*----------------------------------------------------------------------------*/
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxfile.h>
#include <scxcorelib/scxprocess.h>
#include <scxcorelib/stringaid.h>
#include <testutils/scxunit.h>
#include <testutils/providertestutils.h>
#include <iostream> // for cout
#include "sqlauth.h"
#include "sqlcredentials.h"
static const std::wstring s_authProgram = L"./mycimprovauth";
static const wchar_t* s_authFilePath = L"./mysql-auth";
static const int s_timeout = 0;
using namespace SCXCoreLib;
class MyCimprovAuth_Test : public CPPUNIT_NS::TestFixture
{
CPPUNIT_TEST_SUITE( MyCimprovAuth_Test );
CPPUNIT_TEST( test_NoCommandOptions );
CPPUNIT_TEST( test_BasicHelp );
CPPUNIT_TEST( test_CommandHelp );
CPPUNIT_TEST( test_OptionTest_Valid );
CPPUNIT_TEST( test_CommandPrint_Empty );
CPPUNIT_TEST( test_CommandQuit_DoesntUpdate );
CPPUNIT_TEST( test_AutoUpdate_Interactive );
CPPUNIT_TEST( test_AutoUpdate_CommandLine );
CPPUNIT_TEST( test_Default_Interactive );
CPPUNIT_TEST( test_Default_CommandLine );
CPPUNIT_TEST( test_Update_Interactive );
CPPUNIT_TEST( test_Update_CommandLine );
CPPUNIT_TEST( test_Delete_Interactive );
CPPUNIT_TEST( test_Delete_CommandLine );
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp(void)
{
}
void tearDown(void)
{
// Delete the authentication file
SCXCoreLib::SCXFile::Delete( s_authFilePath );
}
void test_NoCommandOptions()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( "", processOutput.str() );
CPPUNIT_ASSERT_EQUAL( "./mycimprovauth: Try './mycimprovauth -h' for more information.\n", processErr.str() );
CPPUNIT_ASSERT_EQUAL( 1, status );
}
void test_BasicHelp()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -h", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "Usage: ./mycimprovauth[options] [operations]" << std::endl
<< std::endl
<< "Options:" << std::endl
<< " -h:\tDisplay detailed help information" << std::endl
<< " -i:\tInteractive use" << std::endl
<< " -v:\tDisplay version information" << std::endl << std::endl
<< "Operations:" << std::endl
<< " autoupdate true|false" << std::endl
<< " default [bind-address] [username] [password]" << std::endl
<< " delete default|<port#>" << std::endl
<< " help" << std::endl
<< " print" << std::endl
<< " update <port#> [bind-address] [username] [password]" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
}
void test_CommandHelp()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" help", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "Help for commands to maintain MySQL Provider Authentication File:" << std::endl << std::endl
<< " autoupdate [true|false]" << std::endl
<< " Allow/disallow automatic updates to authentication file." << std::endl << std::endl
<< " default [bind-address] [username] [password] [in-base64]:" << std::endl
<< " Add or update default record to provide default information for" << std::endl
<< " port records (set via update command)." << std::endl
<< " [bind-address] is default bind address for MySQL Server" << std::endl
<< " [username] is default username for login to MySQL Server" << std::endl
<< " [password] is default password for login to MySQL Server" << std::endl
<< " [in-base64] is \"true\" or \"false\" if record pw in Base64 format" << std::endl
<< " Default record is entirely optional, and need not exist. Specify" << std::endl
<< " an empty field as \"\"." << std::endl << std::endl
<< " delete [default|port#]:" << std::endl
<< " Delete default record or a port record in authentication file." << std::endl << std::endl
<< " exit:" << std::endl
<< " Saves changes and exits (only useful for interactive mode)." << std::endl << std::endl
<< " help:" << std::endl
<< " Display this help text." << std::endl << std::endl
<< " print:" << std::endl
<< " Print the contents of the MySQL provider authenticaiton file." << std::endl << std::endl
<< " quit:" << std::endl
<< " Quits interactive mode without saving changes." << std::endl << std::endl
<< " save:" << std::endl
<< " Save changes to disk. This is automatic for non-interactive mode." << std::endl << std::endl
<< " update [port#] [bind-address] [username] [password] [in-base64]:" << std::endl
<< " Add or update a port record to identify a MySQL Server instance in the" << std::endl
<< " authentication file." << std::endl
<< " [port#] is the port number for the MySQL Server instance" << std::endl
<< " [bind-address] is default bind address for MySQL Server" << std::endl
<< " [username] is default username for login to MySQL Server" << std::endl
<< " [password] is default password for login to MySQL Server" << std::endl
<< " [in-base64] is \"true\" or \"false\" if record pw in Base64 format" << std::endl
<< " Note that all information is validated by connecting to MySQL Server." << std::endl
<< " Specify an empty field as \"\"." << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
}
void test_OptionTest_Valid()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t", processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string("Error - No command specified or command keyword empty\n"), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 3, status );
}
void test_CommandPrint_Empty()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t print", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "[Automatic Updates: Enabled]" << std::endl
<< "[No default entry defined]" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
}
void test_CommandQuit_DoesntUpdate()
{
std::istringstream processInput( std::string("autoupdate false\nprint\nquit\n") );
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "auth> autoupdate false" << std::endl
<< "auth> print" << std::endl
<< "[Automatic Updates: DISABLED]" << std::endl
<< "[No default entry defined]" << std::endl
<< "auth> quit" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[0] );
}
void test_AutoUpdate_Interactive()
{
std::istringstream processInput( std::string("autoupdate false\nprint\nexit\n") );
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "auth> autoupdate false" << std::endl
<< "auth> print" << std::endl
<< "[Automatic Updates: DISABLED]" << std::endl
<< "[No default entry defined]" << std::endl
<< "auth> exit" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=false"), lines[0] );
}
void test_AutoUpdate_CommandLine()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t autoupdate false", processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=false"), lines[0] );
}
void test_Default_Interactive()
{
std::istringstream processInput( std::string("default " + sqlHostname + " " + sqlUsername + " " + sqlPassword + "\nprint\nexit\n") );
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "auth> default "<< sqlHostname << " " << sqlUsername << " " << sqlPassword << std::endl
<< "auth> print" << std::endl
<< "[Automatic Updates: Enabled]" << std::endl
<< std::endl
<< "Default Entry: " << std::endl
<< " Binding: " << sqlHostname << std::endl
<< " Username: root" << std::endl
<< " Password: root" << std::endl
<< "auth> exit" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] );
}
void test_Default_CommandLine()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
std::wstring commandLine(s_authProgram);
commandLine += L" -t default " + StrFromUTF8(sqlHostname) + L" " + StrFromUTF8(sqlUsername) + L" " + StrFromUTF8(sqlPassword);
int status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] );
}
void test_Update_Interactive()
{
std::istringstream processInput( std::string(
"default " + sqlHostname + " " + sqlUsername + " " + sqlPassword + "\n"
"update 3306 \"\"\n"
"print\n"
"exit\n") );
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "auth> default " << sqlHostname << " " << sqlUsername << " " << sqlPassword << std::endl
<< "auth> update 3306 \"\"" << std::endl
<< "auth> print" << std::endl
<< "[Automatic Updates: Enabled]" << std::endl
<< std::endl
<< "Default Entry: " << std::endl
<< " Binding: " << sqlHostname << std::endl
<< " Username: " << sqlUsername << std::endl
<< " Password: " << sqlPassword << std::endl
<< std::endl
<< "Port 3306:" << std::endl
<< " Binding: <From Default>" << std::endl
<< " Username: <From Default>" << std::endl
<< " Password: <From Default>" << std::endl
<< "auth> exit" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"3306=, ,"), lines[1] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[2] );
}
void test_Update_CommandLine()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
std::wstring commandLine(s_authProgram);
commandLine += L" -t default " + StrFromUTF8(sqlHostname) + L" " + StrFromUTF8(sqlUsername) + L" " + StrFromUTF8(sqlPassword);
int status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
commandLine = s_authProgram + L" -t update 3306 " + StrFromUTF8(sqlHostname);
status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"3306=127.0.0.1, ,"), lines[1] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[2] );
}
void test_Delete_Interactive()
{
std::istringstream processInput( std::string(
"default " + sqlHostname + " " + sqlUsername + " " + sqlPassword + "\n"
"update 3306 \"\"\n"
"delete 3306\n"
"delete default\n"
"print\n"
"exit\n") );
std::ostringstream processOutput;
std::ostringstream processErr;
int status = SCXProcess::Run(s_authProgram + L" -t -i", processInput, processOutput, processErr, s_timeout);
std::stringstream expectedOutput;
expectedOutput << "auth> default " << sqlHostname << " " << sqlUsername << " " << sqlPassword << std::endl
<< "auth> update 3306 \"\"" << std::endl
<< "auth> delete 3306" << std::endl
<< "auth> delete default" << std::endl
<< "auth> print" << std::endl
<< "[Automatic Updates: Enabled]" << std::endl
<< "[No default entry defined]" << std::endl
<< "auth> exit" << std::endl;
CPPUNIT_ASSERT_EQUAL( expectedOutput.str(), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[0] );
}
void test_Delete_CommandLine()
{
std::istringstream processInput;
std::ostringstream processOutput;
std::ostringstream processErr;
// Create default record
std::wstring commandLine(s_authProgram);
commandLine += L" -t default " + StrFromUTF8(sqlHostname) + L" " + StrFromUTF8(sqlUsername) + L" " + StrFromUTF8(sqlPassword);
int status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
std::vector<std::wstring> lines;
SCXStream::NLFs nlfs;
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] );
// Create port 3306 record
commandLine = s_authProgram + L" -t update 3306 " + StrFromUTF8(sqlHostname);
status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"3306=127.0.0.1, ,"), lines[1] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[2] );
// Delete port 3306 record
commandLine = s_authProgram + L" -t delete 3306";
status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"0=127.0.0.1, root, cm9vdA=="), lines[0] );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[1] );
// Delete default record
commandLine = s_authProgram + L" -t delete default";
status = SCXProcess::Run(commandLine, processInput, processOutput, processErr, s_timeout);
CPPUNIT_ASSERT_EQUAL( std::string(""), processOutput.str() );
CPPUNIT_ASSERT_EQUAL( std::string(""), processErr.str() );
CPPUNIT_ASSERT_EQUAL( 0, status );
// Validate that the authentication file was written properly
CPPUNIT_ASSERT( SCXFile::Exists( s_authFilePath ) );
SCXFile::ReadAllLines( s_authFilePath, lines, nlfs );
CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), lines.size() );
CPPUNIT_ASSERT_EQUAL( std::wstring(L"AutoUpdate=true"), lines[0] );
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MyCimprovAuth_Test );
| 45.428058
| 141
| 0.598305
|
Bhaskers-Blu-Org2
|
27a228655f5fe4c49b886949898cbc561d65c722
| 2,891
|
hpp
|
C++
|
include/Graphy/Graphables/Styles/LabelStyle.hpp
|
dominicprice/Graphy
|
4553adf06e9c63365ed2ef994fa76c460f8673f4
|
[
"MIT"
] | null | null | null |
include/Graphy/Graphables/Styles/LabelStyle.hpp
|
dominicprice/Graphy
|
4553adf06e9c63365ed2ef994fa76c460f8673f4
|
[
"MIT"
] | null | null | null |
include/Graphy/Graphables/Styles/LabelStyle.hpp
|
dominicprice/Graphy
|
4553adf06e9c63365ed2ef994fa76c460f8673f4
|
[
"MIT"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////////
//MIT License
//
//Copyright(c) 2017 Dominic Price
//
//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 GRAPHY_LABELSTYLE_H
#define GRAPHY_LABELSTYLE_H
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <string>
#include <SFML/Graphics/Color.hpp>
namespace graphy
{
struct LabelStyle
{
////////////////////////////////////////////////////////////
/// \brief Enumeration defining where the label should float relative to its position
///
////////////////////////////////////////////////////////////
enum Float : signed char
{
above_right = 0, ///< Above and to the right of a point
below_right = 1, ///< Below and to the right of a point
above_left = 2, ///< Above and to the left of a point
below_left = 3, ///< Below and to the left of a point
_unset = -1 ///< Ambiguous, may be drawn anywhere
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs a default style.
///
////////////////////////////////////////////////////////////
LabelStyle() :
enabled(true),
text(),
color(sf::Color::Black),
size(15),
pos(Float::below_left),
x(0),
offset(0)
{}
bool enabled; ///< Labels will only display if this is set to true
std::string text; ///< Label text
sf::Color color; ///< Colour of label
unsigned int size; ///< Height of label in pixels
Float pos; ///< Placement of label relative to position
double x; ///< x-coordinate of label for objects with extended length
float offset; ///< offset of label from its position
};
} // namespace graphy
#endif //GRAPHY_LABELSTYLE_H
| 36.1375
| 87
| 0.583189
|
dominicprice
|
27a6b11730fa13345cf43b0a3ed5ce356008fcee
| 1,848
|
hpp
|
C++
|
ParticleSystem/src/ParticleUpdater.hpp
|
Azatsu/ParticleSystem
|
8d8a5f41200c1865089b3b2dff8c41cc63dc3b13
|
[
"MIT"
] | 1
|
2021-05-05T06:42:19.000Z
|
2021-05-05T06:42:19.000Z
|
ParticleSystem/src/ParticleUpdater.hpp
|
Azatsu/ParticleSystem
|
8d8a5f41200c1865089b3b2dff8c41cc63dc3b13
|
[
"MIT"
] | 5
|
2021-05-04T10:05:11.000Z
|
2021-05-05T08:28:02.000Z
|
ParticleSystem/src/ParticleUpdater.hpp
|
Azatsu/ParticleSystem
|
8d8a5f41200c1865089b3b2dff8c41cc63dc3b13
|
[
"MIT"
] | null | null | null |
#ifndef __PRTCL_UPDT_HPP__
#define __PRTCL_UPDT_HPP__
#include <vector>
#include <algorithm>
#include "particleGenerator.hpp"
class ParticleUpdater
{
public:
ParticleUpdater() { }
virtual ~ParticleUpdater() { }
virtual void Update(float dt, ParticleData* p) = 0;
};
class EulerUpdater : public ParticleUpdater
{
public:
float4 globalAcceleration;
public:
EulerUpdater() : globalAcceleration(0.f, 0.f, 0.f, 0.f) { }
virtual void Update(float dt, ParticleData* p) override;
};
// collision with the floor :) todo: implement a collision model
class FloorUpdater : public ParticleUpdater
{
public:
float floorY;
float bounceFactor;
public:
FloorUpdater() :floorY(0.0), bounceFactor(0.5f) { }
virtual void Update(float dt, ParticleData* p) override;
};
class AttractorUpdater : public ParticleUpdater
{
protected:
std::vector<float4> attractors; // .w is force
public:
virtual void Update(float dt, ParticleData* p) override;
size_t CollectionSize() const { return attractors.size(); }
void Add(const float4& attr) { attractors.push_back(attr); }
float4& Get(size_t id) { return attractors[id]; }
};
class BasicColorUpdater : public ParticleUpdater
{
public:
virtual void Update(float dt, ParticleData* p) override;
};
class PosColorUpdater : public ParticleUpdater
{
public:
float4 minPos;
float4 maxPos;
public:
PosColorUpdater() : minPos(0.f, 0.f, 0.f, 0.f), maxPos(1.f, 1.f, 1.f, 1.f) { }
virtual void Update(float dt, ParticleData* p) override;
};
class VelColorUpdater : public ParticleUpdater
{
public:
float4 minVel;
float4 maxVel;
public:
VelColorUpdater() : minVel(0.f, 0.f, 0.f, 0.f), maxVel(1.f, 1.f, 1.f, 1.f) { }
virtual void Update(float dt, ParticleData* p) override;
};
class BasicTimeUpdater : public ParticleUpdater
{
public:
virtual void Update(float dt, ParticleData* p) override;
};
#endif
| 21.488372
| 79
| 0.731061
|
Azatsu
|
27a79a997fe218c175ba9a076c86934794aa53d3
| 96
|
hh
|
C++
|
vm/vm/main/cached/Unit-implem-decl.hh
|
Ahzed11/mozart2
|
4806504b103e11be723e7813be8f69e4d85875cf
|
[
"BSD-2-Clause"
] | 379
|
2015-01-02T20:27:33.000Z
|
2022-03-26T23:18:17.000Z
|
vm/vm/main/cached/Unit-implem-decl.hh
|
Ahzed11/mozart2
|
4806504b103e11be723e7813be8f69e4d85875cf
|
[
"BSD-2-Clause"
] | 81
|
2015-01-08T13:18:52.000Z
|
2021-12-21T14:02:21.000Z
|
vm/vm/main/cached/Unit-implem-decl.hh
|
Ahzed11/mozart2
|
4806504b103e11be723e7813be8f69e4d85875cf
|
[
"BSD-2-Clause"
] | 75
|
2015-01-06T09:08:20.000Z
|
2021-12-17T09:40:18.000Z
|
class Unit;
template <>
class Storage<Unit> {
public:
typedef struct mozart::unit_t Type;
};
| 12
| 37
| 0.708333
|
Ahzed11
|
27a7c014c2902b7a8d7ab0d4b44e8fa5b6538169
| 1,632
|
cpp
|
C++
|
Gym/0719/c.cpp
|
tusikalanse/acm-icpc
|
20150f42752b85e286d812e716bb32ae1fa3db70
|
[
"MIT"
] | 2
|
2021-06-09T12:27:07.000Z
|
2021-06-11T12:02:03.000Z
|
Gym/0719/c.cpp
|
tusikalanse/acm-icpc
|
20150f42752b85e286d812e716bb32ae1fa3db70
|
[
"MIT"
] | 1
|
2021-09-08T12:00:05.000Z
|
2021-09-08T14:52:30.000Z
|
Gym/0719/c.cpp
|
tusikalanse/acm-icpc
|
20150f42752b85e286d812e716bb32ae1fa3db70
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 405;
int val[MAXN][MAXN], dis[MAXN], vis[MAXN];
int T, n, m, k, W, w, s, t, op;
struct node {
int id, d;
bool operator<(const node &rhs) const {
return id > rhs.id;
}
};
vector<pair<int,int>> toerase;
bool hd;
void dfs(int id, int des) {
if(hd) return;
if(id == des) {
hd = 1;
return;
}
for(int i = des; hd == 0 && i > id; --i) {
if(dis[i] - dis[id] == val[id][i]) {
toerase.push_back(make_pair(id, i));
dfs(i, des);
if(!hd)
toerase.pop_back();
}
}
}
int dijk() {
memset(dis, -1, sizeof(dis));
memset(vis, 0, sizeof(vis));
priority_queue<node> q;
q.push({0, 0});
dis[0] = 0;
vis[0] = 1;
while(!q.empty()) {
node u = q.top();
q.pop();
vis[u.id] = 1;
if(dis[u.id] > u.d) continue;
for(int i = u.id + 1; i <= 2 * n; ++i) if(vis[i] == 0) {
if(dis[i] < dis[u.id] + val[u.id][i]) {
dis[i] = dis[u.id] + val[u.id][i];
q.push({i, dis[i]});
}
}
}
int mmax = dis[2 * n], id = 2 * n;
if(mmax < dis[2 * n - 1]) {
mmax = dis[2 * n - 1];
id = 2 * n - 1;
}
toerase.resize(0);
hd = 0;
dfs(0, id);
for(auto it : toerase) {
val[it.first][it.second] = 0;
}
return mmax;
}
int main() {
scanf("%d", &T);
while(T--) {
memset(val, 0, sizeof(val));
scanf("%d%d%d%d", &n, &m, &k, &W);
while(m--) {
scanf("%d%d%d%d", &s, &t, &w, &op);
if(op == 0) {
val[2 * s][2 * t] = w - W;
val[2 * s - 1][2 * t] = w;
}
else {
val[2 * s - 1][2 * t - 1] = w - W;
val[2 * s][2 * t - 1] = w;
}
}
int ans = 0;
while(k--) {
ans += dijk();
}
printf("%d\n", ans);
}
return 0;
}
| 18.133333
| 58
| 0.474265
|
tusikalanse
|
27a836943d08f7a9b12542c16ca7586f2d6c4e34
| 1,689
|
cpp
|
C++
|
BRAC University Competitive Programming training/Prefix sum/chechinkg range for a particular summation.cpp
|
Mit382/Mitul-s-Competitive-Programming-March-August
|
3b0d9b3d018444584020e37b892021f7e9ec984d
|
[
"MIT"
] | 1
|
2021-04-23T16:53:35.000Z
|
2021-04-23T16:53:35.000Z
|
BRAC University Competitive Programming training/Prefix sum/chechinkg range for a particular summation.cpp
|
Mit382/Mitul-s-Competitive-Programming-March-August
|
3b0d9b3d018444584020e37b892021f7e9ec984d
|
[
"MIT"
] | null | null | null |
BRAC University Competitive Programming training/Prefix sum/chechinkg range for a particular summation.cpp
|
Mit382/Mitul-s-Competitive-Programming-March-August
|
3b0d9b3d018444584020e37b892021f7e9ec984d
|
[
"MIT"
] | 1
|
2021-03-27T19:56:19.000Z
|
2021-03-27T19:56:19.000Z
|
//Question in array 1 , -1, 0,2 there is how many ranges, that can make the summation 2?
//Input:
//4 2
//1 -1 0 2
//Output:
//3
//solve:
//index: 0 1 2 3 4
//array 1 -1 0 2
//prefix: 0 1 0 0 2
// check that there is 2 , (0,2 ), (1,-1,0,2) can make summation 2. thus answer is 3
//now check the prefix array and relate: prefix[4]-2=0 . here 0 is there 3 times beacuse in the prefix we assume index 0 has default value =0 and such 0 is there 3 times and that is the answer. Note: prefix[4]=2
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n,s;
cin>>n>>s;
//n+1 beacuse in for loop we took i=1 to i<=n and thus
vector<long long int > input(n+1);//creating input vecor (dynamic array). Note:1≤xi≤10^9 in problem and thus you may need to add a lot of this and it may exceed the integer range and thus long long integer is suggested
vector<long long int>pref(n+1);// creating prefix vecor . Note:1≤xi≤10^9 in problem and thus you may need to add a lot of this and it may exceed the integer range and thus long long integer is suggested
for(int i=1; i<=n;i++){
cin>>input[i];
}
//Prefix sum building
pref[0]=0; //prefix[0]=0
for(int i=1; i<=n;i++){
pref[i]=pref[i-1]+input[i];
}
map<long long int, int> mp;
long long int ans=0;// defining from the map;
mp[0]=1;//defining from the map
for( int i=1; i<=n;i++){
long long int key=pref[i]-s;
ans+=mp[key];
mp[pref[i]]++;// adding value to map's 2nd parameter
}
cout<<ans<<endl;
return 0;
}
| 31.867925
| 222
| 0.606868
|
Mit382
|
27ad1a1f8e279742a161e298429f27e55e93c7b6
| 1,481
|
cc
|
C++
|
src/Parser/AST/MatchStatementNode.cc
|
stenbror/PythonCoreNative
|
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
|
[
"BSL-1.0"
] | null | null | null |
src/Parser/AST/MatchStatementNode.cc
|
stenbror/PythonCoreNative
|
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
|
[
"BSL-1.0"
] | null | null | null |
src/Parser/AST/MatchStatementNode.cc
|
stenbror/PythonCoreNative
|
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
|
[
"BSL-1.0"
] | 1
|
2021-05-24T11:18:32.000Z
|
2021-05-24T11:18:32.000Z
|
#include <ast/MatchStatementNode.h>
using namespace PythonCoreNative::RunTime::Parser::AST;
using namespace PythonCoreNative::RunTime::Parser;
MatchStatementNode::MatchStatementNode(
unsigned int start, unsigned int end,
std::shared_ptr<Token> op1,
std::shared_ptr<AST::StatementNode> left,
std::shared_ptr<Token> op2,
std::shared_ptr<Token> op3,
std::shared_ptr<Token> op4,
std::shared_ptr<std::vector<std::shared_ptr<StatementNode>>> nodes,
std::shared_ptr<Token> op5
) : StatementNode(start, end)
{
mOp1 = op1;
mLeft = left;
mOp2 = op2;
mOp3 = op3;
mOp4 = op4;
mNodes = nodes;
mOp3 = op5;
}
std::shared_ptr<Token> MatchStatementNode::GetOperator1()
{
return mOp1;
}
std::shared_ptr<Token> MatchStatementNode::GetOperator2()
{
return mOp2;
}
std::shared_ptr<Token> MatchStatementNode::GetOperator3()
{
return mOp3;
}
std::shared_ptr<Token> MatchStatementNode::GetOperator4()
{
return mOp4;
}
std::shared_ptr<Token> MatchStatementNode::GetOperator5()
{
return mOp5;
}
std::shared_ptr<AST::StatementNode> MatchStatementNode::GetLeft()
{
return mLeft;
}
std::shared_ptr<std::vector<std::shared_ptr<StatementNode>>> MatchStatementNode::GetNodes()
{
return mNodes;
}
| 24.278689
| 95
| 0.602296
|
stenbror
|
27ad2135e457a7db745ea1d84b8fd2e9f8eb59b5
| 1,239
|
cpp
|
C++
|
arm9/source/menuDemo.cpp
|
henke37/hblankmegademo
|
638d6200c930e305acb6aea341211cff99dc5893
|
[
"BSD-2-Clause"
] | 2
|
2019-09-01T14:31:51.000Z
|
2019-09-10T11:00:20.000Z
|
arm9/source/menuDemo.cpp
|
henke37/hblankmegademo
|
638d6200c930e305acb6aea341211cff99dc5893
|
[
"BSD-2-Clause"
] | 8
|
2017-09-24T20:21:15.000Z
|
2022-03-04T15:29:05.000Z
|
arm9/source/menuDemo.cpp
|
henke37/hblankmegademo
|
638d6200c930e305acb6aea341211cff99dc5893
|
[
"BSD-2-Clause"
] | 2
|
2019-02-04T02:59:42.000Z
|
2019-02-05T06:16:07.000Z
|
#include "menuDemo.h"
#include "sinScrollDemo.h"
#include "peepHoleWindowDemo.h"
#include "spotlightDemo.h"
#include "demoRunner.h"
#include "scanInDemo.h"
#include "rasterbarDemo.h"
#include "flutterDemo.h"
#include <nds/arm9/console.h>
#include <cassert>
#include <nds/arm9/input.h>
MenuDemo::MenuDemo() : selection(0) {}
MenuDemo::~MenuDemo() {}
void MenuDemo::Load() {
setupDefaultBG();
consoleClear();
}
void MenuDemo::Unload() {}
void MenuDemo::PrepareFrame(VramBatcher &) {}
void MenuDemo::AcceptInput() {
auto keys = keysDown();
if(keys & KEY_UP && selection > 0) {
selection--;
} else if(keys & KEY_DOWN && selection+1 < demoCount) {
selection++;
}
if(keys & KEY_START) {
runner.RunDemo(makeDemo());
}
}
std::shared_ptr<Demo> MenuDemo::makeDemo() {
switch(selection) {
case 0:
return std::make_shared<SinXScrollDemo>();
case 1:
return std::make_shared<SinYScrollDemo>();
case 2:
return std::make_shared<ScanInDemo>();
case 3:
return std::make_shared<PeepHoleWindowDemo>();
case 4:
return std::make_shared<SpotLightDemo>();
case 5:
return std::make_shared<RasterBarDemo>();
case 6:
return std::make_shared<FlutterDemo>();
}
sassert(0,"Bad menu selection instatiated");
assert(0);
}
| 21
| 56
| 0.696529
|
henke37
|
27b1c2cd6ce82237c2f7d858ce0e4ac2557e9295
| 487
|
hpp
|
C++
|
src/util.hpp
|
Cynnexis/dna-not-ascii
|
9df62c48f530297a12c9c0328a8d3e115c5c18cf
|
[
"MIT"
] | null | null | null |
src/util.hpp
|
Cynnexis/dna-not-ascii
|
9df62c48f530297a12c9c0328a8d3e115c5c18cf
|
[
"MIT"
] | 1
|
2021-03-03T08:51:30.000Z
|
2021-03-03T08:51:30.000Z
|
src/util.hpp
|
Cynnexis/dna-not-ascii
|
9df62c48f530297a12c9c0328a8d3e115c5c18cf
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream>
#include <functional>
#include <cstdlib>
#include <string>
#include <sstream>
#include <cassert>
using std::cout, std::cerr, std::cin, std::endl, std::string;
/**
* @brief Get the current epoch in milliseconds.
* @details Source code inspired from https://stackoverflow.com/a/17371925/7347145
* by Dan Moulding and Raedwald.
*
* @return unsigned long The time in milliseconds starting from January the 1st,
* 1970.
*/
unsigned long epochMs();
| 23.190476
| 82
| 0.722793
|
Cynnexis
|
27b7166908d70e2f3a7588a7d6f426a25888dffc
| 1,287
|
cpp
|
C++
|
VeronixApp.cpp
|
LNAV/Sudoku_Solver_Cpp
|
431a5d0e370d3d5f7da33674601f3a57efd7032a
|
[
"Apache-2.0"
] | 1
|
2020-05-17T11:46:46.000Z
|
2020-05-17T11:46:46.000Z
|
VeronixApp.cpp
|
LNAV/VeronixApp-Sudoku_Solver
|
431a5d0e370d3d5f7da33674601f3a57efd7032a
|
[
"Apache-2.0"
] | null | null | null |
VeronixApp.cpp
|
LNAV/VeronixApp-Sudoku_Solver
|
431a5d0e370d3d5f7da33674601f3a57efd7032a
|
[
"Apache-2.0"
] | null | null | null |
/*
* VeronixApp.cpp
*
* Created on: May 18, 2019
* Author: LavishK1
*/
#include <SudokuConsoleViewController.h>
#include "VeronixApp.h"
#include "AppDefines.h"
#include "APP/GridSolver.h"
#include "APP/Helper/InputHelper.h"
namespace Veronix
{
namespace App
{
VeronixApp::VeronixApp()
{
DEF_COUT( "VeronixApp::VeronixApp" );
}
VeronixApp::~VeronixApp()
{
DEF_COUT( "VeronixApp::~VeronixApp" );
}
void VeronixApp::start()
{
DEF_COUT( "This is a Start" );
try
{
helper::InputHelper inputProcessor;
const Array::TabularArray<int> & gridValues = inputProcessor.getSudokuGridData(/*helper::console_read*/);
sudosolver::container::GridContainer gridContainer(gridValues);
viewcontroller::SudokuViewController sudokuView(gridContainer);
DEF_COUT( "Before Solving Sudoku: " );
sudokuView.displaySudoku();
sudosolver::GridSolver gridSolver(gridContainer);
gridSolver.solveGrid();
DEF_COUT( "After Solving Sudoku: " );
sudokuView.displaySudoku();
}
catch (const std::string e)
{
DEF_COUT( "Exception Thrown" << e );
}
catch (const char * e)
{
DEF_COUT( "Exception Thrown int *: " << e );
}
catch (...)
{
DEF_COUT("Exception is thrown somewhere");
}
DEF_COUT( "Start Ended Here" );
}
} /* namespace App */
} /* namespace Veronix */
| 18.652174
| 107
| 0.694639
|
LNAV
|
27ba6a4992b0b98dd27c85182d91b4b2eb479c1f
| 1,729
|
cc
|
C++
|
components/shared_highlighting/core/common/disabled_sites.cc
|
Ron423c/chromium
|
2edf7b980065b648f8b2a6e52193d83832fe36b7
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575
|
2015-06-18T23:58:20.000Z
|
2022-03-23T09:32:39.000Z
|
components/shared_highlighting/core/common/disabled_sites.cc
|
Ron423c/chromium
|
2edf7b980065b648f8b2a6e52193d83832fe36b7
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113
|
2015-05-04T09:58:14.000Z
|
2022-01-31T19:35:03.000Z
|
components/shared_highlighting/core/common/disabled_sites.cc
|
DamieFC/chromium
|
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52
|
2015-07-14T10:40:50.000Z
|
2022-03-15T01:11:49.000Z
|
// Copyright 2020 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 "components/shared_highlighting/core/common/disabled_sites.h"
#include "base/feature_list.h"
#include "components/shared_highlighting/core/common/shared_highlighting_features.h"
#include "third_party/re2/src/re2/re2.h"
#include <map>
#include <utility>
namespace shared_highlighting {
bool ShouldOfferLinkToText(const GURL& url) {
if (base::FeatureList::IsEnabled(kSharedHighlightingUseBlocklist)) {
// If a URL's host matches a key in this map, then the path will be tested
// against the RE stored in the value. For example, {"foo.com", ".*"} means
// any page on the foo.com domain.
const static std::map<std::string, std::string> kBlocklist = {
{"facebook.com", ".*"},
// TODO(crbug.com/1157981): special case this to cover other Google TLDs
{"google.com", "^\\/amp\\/.*"},
{"instagram.com", ".*"},
{"mail.google.com", ".*"},
{"outlook.live.com", ".*"},
{"reddit.com", ".*"},
{"twitter.com", ".*"},
{"web.whatsapp.com", ".*"},
{"youtube.com", ".*"},
};
std::string domain = url.host();
if (domain.compare(0, 4, "www.") == 0) {
domain = domain.substr(4);
} else if (domain.compare(0, 2, "m.") == 0) {
domain = domain.substr(2);
} else if (domain.compare(0, 7, "mobile.") == 0) {
domain = domain.substr(7);
}
auto it = kBlocklist.find(domain);
if (it != kBlocklist.end()) {
return !re2::RE2::FullMatch(url.path(), it->second);
}
}
return true;
}
} // namespace shared_highlighting
| 32.622642
| 84
| 0.614806
|
Ron423c
|
27bf7731c49ad3e4ee83bc3d6c5443f9e1de0774
| 1,980
|
hpp
|
C++
|
include/Animation.hpp
|
prfcto2/noName
|
e179d49282755039f2acb267931ef445aff5000b
|
[
"MIT"
] | 3
|
2019-08-05T13:33:01.000Z
|
2022-02-14T12:55:18.000Z
|
include/Animation.hpp
|
prfcto2/noName
|
e179d49282755039f2acb267931ef445aff5000b
|
[
"MIT"
] | null | null | null |
include/Animation.hpp
|
prfcto2/noName
|
e179d49282755039f2acb267931ef445aff5000b
|
[
"MIT"
] | null | null | null |
# define ANIMATION_HPP
# ifndef HELPERS_HPP
# include <Helpers.hpp>
# endif
# include <vector>
//Animation has the animation's frames, it's duration and it's loop conditional.
// if the animation is looping, it means that the animation is going to repite itself
// in the pass of time but, if it is not looping, it is going to show it last frame after the
// total duration has been reached
class Animation
{
public:
// constructor takes as parameters the total time to get to the last frame
// and if it is going to loop
Animation(const sf::Time &, bool = false);
Animation(const Animation &);
~Animation();
//sets animation time elapsed to zero
void reset();
// methods identifiers are pretty clear I believe
void setDuraton(const sf::Time &);
void setLooping(bool);
sf::Texture & getFrame() const;
const sf::Time & getDuration() const;
const sf::Time & getElapsed() const;
bool getLooping() const;
size_t size() const;
// it's mean to work as a manual setter of frames getting as parameter
// the complete path of it's texture on assets folder
void addFrame(const std::string &);
// parameter 1 is the path to a folder of animation,
// for simplicity, our animations using this method are going to have a name
// "frame" and what our function does is to take all frames starting from 1.
// it takes all frames placed on the prefix path
// parameter 2 is the postfx of the frame,s by default they are ".png"
void addFrames(const std::string &,
const std::string & = ".png", bool = false);
void addFrames(const std::string &, bool);
// @note: This method is setted virtual so we can define different types of interactions
// from derived classes, with aims of class Enemies having a global Animator.
virtual void update(const sf::Time &);
private:
std::vector<sf::Texture *> m_frames;
sf::Time m_duration;
bool m_looping;
sf::Time m_elapsed;
uint m_pos;
};
| 33
| 93
| 0.697475
|
prfcto2
|
27c63cfb63003f012076586134080800fb72ffc3
| 46
|
cpp
|
C++
|
libs/vis_utils/summedareatable.cpp
|
danniesim/cpp_volume_rendering
|
242c8917aea0a58c9851c2ae3e6c1555db51912e
|
[
"MIT"
] | 10
|
2020-05-15T23:50:19.000Z
|
2022-02-17T09:54:44.000Z
|
libs/vis_utils/summedareatable.cpp
|
danniesim/cpp_volume_rendering
|
242c8917aea0a58c9851c2ae3e6c1555db51912e
|
[
"MIT"
] | 1
|
2022-01-25T02:36:59.000Z
|
2022-01-26T11:41:38.000Z
|
libs/vis_utils/summedareatable.cpp
|
danniesim/cpp_volume_rendering
|
242c8917aea0a58c9851c2ae3e6c1555db51912e
|
[
"MIT"
] | 3
|
2021-11-01T10:32:46.000Z
|
2021-12-28T16:40:10.000Z
|
#include "summedareatable.h"
namespace vis
{}
| 11.5
| 28
| 0.76087
|
danniesim
|
27cbf90cb2a6126f4154915a781b815cccc234b3
| 4,422
|
cpp
|
C++
|
TestApps/bnn/bin_dense_tb.cpp
|
HansGiesen/hls_tuner
|
9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19
|
[
"MIT"
] | 1
|
2021-02-21T12:13:09.000Z
|
2021-02-21T12:13:09.000Z
|
TestApps/bnn/bin_dense_tb.cpp
|
HansGiesen/hls_tuner
|
9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19
|
[
"MIT"
] | null | null | null |
TestApps/bnn/bin_dense_tb.cpp
|
HansGiesen/hls_tuner
|
9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19
|
[
"MIT"
] | 1
|
2019-09-10T16:45:27.000Z
|
2019-09-10T16:45:27.000Z
|
#include <random>
#include <ap_int.h>
const unsigned WORD_SIZE = 64;
const unsigned CONVOLVERS = 2;
const unsigned CONV_W_PER_WORD = 7;
const unsigned WT_L = 16*4*512*64; // parameter to control wt mem size
const unsigned C_WT_WORDS = ((WT_L+CONV_W_PER_WORD-1)/CONV_W_PER_WORD + CONVOLVERS-1) / CONVOLVERS; // wt words per convolver
const unsigned KH_WORDS = WT_L/128*16 / WORD_SIZE;
const unsigned DMEM_WORDS = 128*32*32 / WORD_SIZE;
const unsigned C_DMEM_WORDS = DMEM_WORDS / CONVOLVERS;
typedef ap_int<WORD_SIZE> Word;
typedef ap_uint<22> Address;
enum LayerTypeEnum {LAYER_CONV1, LAYER_CONV, LAYER_DENSE, LAYER_LAST};
void bin_dense_orig(
const Word wt_mem[CONVOLVERS][C_WT_WORDS],
const Word kh_mem[KH_WORDS],
Word dmem[2][CONVOLVERS][C_DMEM_WORDS],
ap_uint<2> layer_type,
ap_uint<1> d_i_idx,
ap_uint<1> d_o_idx,
const Address o_index,
const unsigned n_inputs,
const unsigned n_outputs
);
typedef ap_uint<1> Input;
typedef ap_uint<1> Output;
typedef ap_int<16> Sum;
typedef ap_uint<1> Weight;
typedef ap_int<16> Norm_coef;
typedef ap_uint<4> Pred;
typedef ap_fixed<16, 2> Scale;
typedef ap_fixed<16, 4> Offset;
void bin_dense_0(Input input[8192], Output output[1024], Weight weights[8192 * 1024], Norm_coef norm_coefs[1024]);
void bin_dense_1(Input input[1024], Output output[1024], Weight weights[1024 * 1024], Norm_coef norm_coefs[1024]);
void bin_dense_2(Input input[1024], Pred & pred, Weight weights[1024 * 10], Scale scales[10], Offset offsets[10]);
template <unsigned in_cnt, unsigned out_cnt> int bin_dense_tb_core()
{
std::random_device rd;
std::default_random_engine generator;
std::uniform_int_distribution<long long unsigned> distribution(0, 0xFFFFFFFFFFFFFFFF);
auto wt_mem = new Word[CONVOLVERS][C_WT_WORDS];
for (int i = 0; i < CONVOLVERS; i++)
for (int j = 0; j < C_WT_WORDS; j++)
wt_mem[i][j] = distribution(generator);
auto kh_mem = new Word[KH_WORDS];
for (int i = 0; i < KH_WORDS; i++)
kh_mem[i] = distribution(generator);
auto dmem = new Word[2][CONVOLVERS][C_DMEM_WORDS];
for (int i = 0; i < 2; i++)
for (int j = 0; j < CONVOLVERS; j++)
for (int k = 0; k < C_DMEM_WORDS; k++)
dmem[i][j][k] = distribution(generator);
bin_dense_orig(wt_mem, kh_mem, dmem, out_cnt == 1024 ? LAYER_DENSE : LAYER_LAST, 0, 1, 0, in_cnt, out_cnt);
auto input = new Input[in_cnt];
for (int i = 0; i < in_cnt / WORD_SIZE / CONVOLVERS; i++)
for (int j = 0; j < CONVOLVERS; j++)
for (int k = 0; k < WORD_SIZE; k++)
input[(i * CONVOLVERS + j) * WORD_SIZE + k] = dmem[0][j][i][k];
auto output = new Output[out_cnt];
Pred pred;
auto weights = new Weight[in_cnt * out_cnt];
for (int i = 0; i < in_cnt * out_cnt / WORD_SIZE / CONVOLVERS; i++)
for (int j = 0; j < CONVOLVERS; j++)
for (int k = 0; k < WORD_SIZE; k++)
weights[(i * CONVOLVERS + j) * WORD_SIZE + k] = wt_mem[j][i][k];
auto norm_coefs = new Norm_coef[out_cnt];
for (int i = 0; i < out_cnt; i++)
norm_coefs[i] = kh_mem[i / 4].range(16 * (i % 4) + 15, 16 * (i % 4));
auto scales = new Scale[out_cnt];
auto offsets = new Offset[out_cnt];
for (int i = 0; i < 2 * out_cnt; i++)
{
ap_uint<16> value = kh_mem[i / 4].range(16 * (i % 4) + 15, 16 * (i % 4));
if (i % 2 == 0)
scales[i / 2](15, 0) = value;
else
offsets[i / 2](15, 0) = value;
}
if (in_cnt == 8192)
bin_dense_0(input, output, weights, norm_coefs);
else if (out_cnt == 1024)
bin_dense_1(input, output, weights, norm_coefs);
else
bin_dense_2(input, pred, weights, scales, offsets);
if (out_cnt == 1024)
{
for (int i = 0; i < out_cnt / WORD_SIZE / CONVOLVERS; i++)
for (int j = 0; j < CONVOLVERS; j++)
for (int k = 0; k < WORD_SIZE; k++)
if (output[(i * CONVOLVERS + j) * WORD_SIZE + k] != dmem[1][j][i][k])
return true;
}
else
if (dmem[1][0][0].range(3, 0) != pred)
return true;
delete[] wt_mem;
delete[] kh_mem;
delete[] dmem;
delete[] input;
delete[] output;
delete[] weights;
delete[] norm_coefs;
delete[] scales;
delete[] offsets;
return false;
}
int bin_dense_tb()
{
if (bin_dense_tb_core<8192, 1024>())
return true;
if (bin_dense_tb_core<1024, 1024>())
return true;
if (bin_dense_tb_core<1024, 10>())
return true;
printf("bin_dense_tb was successful.\n");
return false;
}
| 31.585714
| 128
| 0.644731
|
HansGiesen
|
27cc89b508504ad3d2e1b8f11c79735721451191
| 1,441
|
cpp
|
C++
|
src/image/todo/bezier.cpp
|
TurkMvc/lol
|
c3fb98c6f371e4648891b59b4adc6cb95ae73451
|
[
"WTFPL"
] | 4
|
2015-02-14T21:14:25.000Z
|
2021-12-12T15:45:44.000Z
|
src/image/todo/bezier.cpp
|
TurkMvc/lol
|
c3fb98c6f371e4648891b59b4adc6cb95ae73451
|
[
"WTFPL"
] | 3
|
2015-02-14T20:56:26.000Z
|
2015-02-16T08:50:54.000Z
|
src/image/todo/bezier.cpp
|
TurkMvc/lol
|
c3fb98c6f371e4648891b59b4adc6cb95ae73451
|
[
"WTFPL"
] | 1
|
2021-10-06T16:01:03.000Z
|
2021-10-06T16:01:03.000Z
|
/*
* Lol Engine
*
* Copyright © 2004—2008 Sam Hocevar <sam@hocevar.net>
* © 2008 Jean-Yves Lamoureux <jylam@lnxscene.org>
*
* This library is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What the Fuck You Want
* to Public License, Version 2, as published by the WTFPL Task Force.
* See http://www.wtfpl.net/ for more details.
*/
/*
* bezier.c: bezier curves rendering functions
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pipi.h"
#include "pipi-internals.h"
int pipi_draw_bezier4(pipi_image_t *img ,
int x1, int y1,
int x2, int y2,
int x3, int y3,
int x4, int y4,
uint32_t c, int n, int aa)
{
if(img->last_modified == PIPI_PIXELS_RGBA_U8)
{
float t;
float x= x1, y= y1;
float lx, ly;
for(t=0; t<1; t+=(1.0f/n))
{
float a = t;
float b = 1 - t;
lx = x; ly = y;
x = (x1*(b*b*b)) + 3*x2*(b*b)*a + 3*x4*b*(a*a) + x3*(a*a*a);
y = (y1*(b*b*b)) + 3*y2*(b*b)*a + 3*y4*b*(a*a) + y3*(a*a*a);
pipi_draw_line(img , lx, ly, x, y, c, aa);
}
pipi_draw_line(img , x, y, x3, y3, c, aa);
}
return 0;
}
| 25.280702
| 72
| 0.517696
|
TurkMvc
|
27d0429e58d7d8f5e96edd66b15c88fb56dc89ac
| 21,788
|
cc
|
C++
|
wrappers/7.0.0/vtkPointSetToLabelHierarchyWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | 6
|
2016-02-03T12:48:36.000Z
|
2020-09-16T15:07:51.000Z
|
wrappers/7.0.0/vtkPointSetToLabelHierarchyWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | 4
|
2016-02-13T01:30:43.000Z
|
2020-03-30T16:59:32.000Z
|
wrappers/7.0.0/vtkPointSetToLabelHierarchyWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | null | null | null |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkLabelHierarchyAlgorithmWrap.h"
#include "vtkPointSetToLabelHierarchyWrap.h"
#include "vtkObjectWrap.h"
#include "vtkTextPropertyWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkPointSetToLabelHierarchyWrap::ptpl;
VtkPointSetToLabelHierarchyWrap::VtkPointSetToLabelHierarchyWrap()
{ }
VtkPointSetToLabelHierarchyWrap::VtkPointSetToLabelHierarchyWrap(vtkSmartPointer<vtkPointSetToLabelHierarchy> _native)
{ native = _native; }
VtkPointSetToLabelHierarchyWrap::~VtkPointSetToLabelHierarchyWrap()
{ }
void VtkPointSetToLabelHierarchyWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkPointSetToLabelHierarchy").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("PointSetToLabelHierarchy").ToLocalChecked(), ConstructorGetter);
}
void VtkPointSetToLabelHierarchyWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkPointSetToLabelHierarchyWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkLabelHierarchyAlgorithmWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkLabelHierarchyAlgorithmWrap::ptpl));
tpl->SetClassName(Nan::New("VtkPointSetToLabelHierarchyWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "GetBoundedSizeArrayName", GetBoundedSizeArrayName);
Nan::SetPrototypeMethod(tpl, "getBoundedSizeArrayName", GetBoundedSizeArrayName);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "GetIconIndexArrayName", GetIconIndexArrayName);
Nan::SetPrototypeMethod(tpl, "getIconIndexArrayName", GetIconIndexArrayName);
Nan::SetPrototypeMethod(tpl, "GetLabelArrayName", GetLabelArrayName);
Nan::SetPrototypeMethod(tpl, "getLabelArrayName", GetLabelArrayName);
Nan::SetPrototypeMethod(tpl, "GetMaximumDepth", GetMaximumDepth);
Nan::SetPrototypeMethod(tpl, "getMaximumDepth", GetMaximumDepth);
Nan::SetPrototypeMethod(tpl, "GetOrientationArrayName", GetOrientationArrayName);
Nan::SetPrototypeMethod(tpl, "getOrientationArrayName", GetOrientationArrayName);
Nan::SetPrototypeMethod(tpl, "GetPriorityArrayName", GetPriorityArrayName);
Nan::SetPrototypeMethod(tpl, "getPriorityArrayName", GetPriorityArrayName);
Nan::SetPrototypeMethod(tpl, "GetSizeArrayName", GetSizeArrayName);
Nan::SetPrototypeMethod(tpl, "getSizeArrayName", GetSizeArrayName);
Nan::SetPrototypeMethod(tpl, "GetTargetLabelCount", GetTargetLabelCount);
Nan::SetPrototypeMethod(tpl, "getTargetLabelCount", GetTargetLabelCount);
Nan::SetPrototypeMethod(tpl, "GetTextProperty", GetTextProperty);
Nan::SetPrototypeMethod(tpl, "getTextProperty", GetTextProperty);
Nan::SetPrototypeMethod(tpl, "GetUseUnicodeStrings", GetUseUnicodeStrings);
Nan::SetPrototypeMethod(tpl, "getUseUnicodeStrings", GetUseUnicodeStrings);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetBoundedSizeArrayName", SetBoundedSizeArrayName);
Nan::SetPrototypeMethod(tpl, "setBoundedSizeArrayName", SetBoundedSizeArrayName);
Nan::SetPrototypeMethod(tpl, "SetIconIndexArrayName", SetIconIndexArrayName);
Nan::SetPrototypeMethod(tpl, "setIconIndexArrayName", SetIconIndexArrayName);
Nan::SetPrototypeMethod(tpl, "SetLabelArrayName", SetLabelArrayName);
Nan::SetPrototypeMethod(tpl, "setLabelArrayName", SetLabelArrayName);
Nan::SetPrototypeMethod(tpl, "SetMaximumDepth", SetMaximumDepth);
Nan::SetPrototypeMethod(tpl, "setMaximumDepth", SetMaximumDepth);
Nan::SetPrototypeMethod(tpl, "SetOrientationArrayName", SetOrientationArrayName);
Nan::SetPrototypeMethod(tpl, "setOrientationArrayName", SetOrientationArrayName);
Nan::SetPrototypeMethod(tpl, "SetPriorityArrayName", SetPriorityArrayName);
Nan::SetPrototypeMethod(tpl, "setPriorityArrayName", SetPriorityArrayName);
Nan::SetPrototypeMethod(tpl, "SetSizeArrayName", SetSizeArrayName);
Nan::SetPrototypeMethod(tpl, "setSizeArrayName", SetSizeArrayName);
Nan::SetPrototypeMethod(tpl, "SetTargetLabelCount", SetTargetLabelCount);
Nan::SetPrototypeMethod(tpl, "setTargetLabelCount", SetTargetLabelCount);
Nan::SetPrototypeMethod(tpl, "SetTextProperty", SetTextProperty);
Nan::SetPrototypeMethod(tpl, "setTextProperty", SetTextProperty);
Nan::SetPrototypeMethod(tpl, "SetUseUnicodeStrings", SetUseUnicodeStrings);
Nan::SetPrototypeMethod(tpl, "setUseUnicodeStrings", SetUseUnicodeStrings);
Nan::SetPrototypeMethod(tpl, "UseUnicodeStringsOff", UseUnicodeStringsOff);
Nan::SetPrototypeMethod(tpl, "useUnicodeStringsOff", UseUnicodeStringsOff);
Nan::SetPrototypeMethod(tpl, "UseUnicodeStringsOn", UseUnicodeStringsOn);
Nan::SetPrototypeMethod(tpl, "useUnicodeStringsOn", UseUnicodeStringsOn);
#ifdef VTK_NODE_PLUS_VTKPOINTSETTOLABELHIERARCHYWRAP_INITPTPL
VTK_NODE_PLUS_VTKPOINTSETTOLABELHIERARCHYWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkPointSetToLabelHierarchyWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkPointSetToLabelHierarchy> native = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
VtkPointSetToLabelHierarchyWrap* obj = new VtkPointSetToLabelHierarchyWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkPointSetToLabelHierarchyWrap::GetBoundedSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBoundedSizeArrayName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetIconIndexArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetIconIndexArrayName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetLabelArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLabelArrayName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetMaximumDepth(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaximumDepth();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkPointSetToLabelHierarchyWrap::GetOrientationArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOrientationArrayName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetPriorityArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPriorityArrayName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetSizeArrayName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkPointSetToLabelHierarchyWrap::GetTargetLabelCount(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTargetLabelCount();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkPointSetToLabelHierarchyWrap::GetTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
vtkTextProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextProperty();
VtkTextPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTextPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTextPropertyWrap *w = new VtkTextPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkPointSetToLabelHierarchyWrap::GetUseUnicodeStrings(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetUseUnicodeStrings();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkPointSetToLabelHierarchyWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
vtkPointSetToLabelHierarchy * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkPointSetToLabelHierarchyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPointSetToLabelHierarchyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPointSetToLabelHierarchyWrap *w = new VtkPointSetToLabelHierarchyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkPointSetToLabelHierarchyWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkPointSetToLabelHierarchy * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkPointSetToLabelHierarchyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPointSetToLabelHierarchyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPointSetToLabelHierarchyWrap *w = new VtkPointSetToLabelHierarchyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetBoundedSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBoundedSizeArrayName(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetIconIndexArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetIconIndexArrayName(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetLabelArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLabelArrayName(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetMaximumDepth(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMaximumDepth(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetOrientationArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrientationArrayName(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetPriorityArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPriorityArrayName(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetSizeArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetSizeArrayName(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetTargetLabelCount(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTargetLabelCount(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTextPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkTextPropertyWrap *a0 = ObjectWrap::Unwrap<VtkTextPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextProperty(
(vtkTextProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::SetUseUnicodeStrings(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetUseUnicodeStrings(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkPointSetToLabelHierarchyWrap::UseUnicodeStringsOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UseUnicodeStringsOff();
}
void VtkPointSetToLabelHierarchyWrap::UseUnicodeStringsOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkPointSetToLabelHierarchyWrap *wrapper = ObjectWrap::Unwrap<VtkPointSetToLabelHierarchyWrap>(info.Holder());
vtkPointSetToLabelHierarchy *native = (vtkPointSetToLabelHierarchy *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UseUnicodeStringsOn();
}
| 35.085346
| 118
| 0.760694
|
axkibe
|
27d2471f54f504a268038549362c62d3e2f861f2
| 1,954
|
cpp
|
C++
|
cpp/sololearn/s31_operator_overloading.cpp
|
bayramcicek/py-repo
|
e99d8881dd3eb5296ec5dcfba4de2c3418044897
|
[
"Unlicense"
] | null | null | null |
cpp/sololearn/s31_operator_overloading.cpp
|
bayramcicek/py-repo
|
e99d8881dd3eb5296ec5dcfba4de2c3418044897
|
[
"Unlicense"
] | null | null | null |
cpp/sololearn/s31_operator_overloading.cpp
|
bayramcicek/py-repo
|
e99d8881dd3eb5296ec5dcfba4de2c3418044897
|
[
"Unlicense"
] | null | null | null |
// C11 standard
// created by cicek on Feb 05, 2021 8:29 PM
#include <iostream>
#include <string>
using namespace std;
// Our class has two constructors and one member variable.
class MyClass {
public:
int var;
MyClass() {}
MyClass(int a)
: var(a) {}
/*
* Overloaded operators are functions, defined by the keyword operator followed by the
* symbol for the operator being defined.
An overloaded operator is similar to other functions in that it has a return type and a parameter list.
In our example we will be overloading the + operator. It will return an object of our class and take an
object of our class as its parameter.
*/
MyClass operator+(MyClass &obj) {
// Now, we need to define what the function does.
MyClass res;
res.var = this->var + obj.var;
return res;
}
/*
* Here, we declared a new res object. We then assigned the sum of the member variables
* of the current object (this) and the parameter object (obj) to the res object's var member variable.
* The res object is returned as the result.
This gives us the ability to create objects in main and use the overloaded + operator to add them together.
*/
// Which choice is the keyword for overloading an operator in C++?: operator
};
int main(int argc, char **argv) {
/*
* Most of the C++ built-in operators can be redefined or overloaded.
Thus, operators can be used with user-defined types as well (for example, allowing you to add two objects together).
*/
// Operators that can't be overloaded include :: | .* | . | ?:
MyClass abc(2);
cout << abc.var; // 2
MyClass obj1(12), obj2(54);
MyClass res = obj1 + obj2;
/*
* With overloaded operators, you can use any custom logic needed.
* However, it's not possible to alter the operators' precedence, grouping, or number of operands.
*/
return 0;
}
| 29.164179
| 116
| 0.66172
|
bayramcicek
|
27d526834319a6235abb936f009d3d0696ae33c9
| 34
|
cpp
|
C++
|
src/MinoGame/ApplicationBuilder.cpp
|
Nicowcow/Minotaur
|
74689a1a76b0577138009acc5f8cd37db7bd7630
|
[
"MIT"
] | 5
|
2017-07-09T08:24:24.000Z
|
2021-01-11T21:32:39.000Z
|
src/MinoGame/ApplicationBuilder.cpp
|
Nicowcow/Minotaur
|
74689a1a76b0577138009acc5f8cd37db7bd7630
|
[
"MIT"
] | 1
|
2018-03-06T18:55:13.000Z
|
2018-12-21T14:20:23.000Z
|
src/MinoGame/ApplicationBuilder.cpp
|
Nicowcow/Minotaur
|
74689a1a76b0577138009acc5f8cd37db7bd7630
|
[
"MIT"
] | 1
|
2019-01-24T09:32:04.000Z
|
2019-01-24T09:32:04.000Z
|
namespace MinoGame {
}
| 2.428571
| 20
| 0.5
|
Nicowcow
|
27d975962cf6301c44ffaf27390159f286a0a5b9
| 2,891
|
hpp
|
C++
|
libs/Aether/include/Aether/primary/Text.hpp
|
tkgstrator/SeedHack
|
227566d993bdea7a2851a8fc664b539186509697
|
[
"MIT"
] | 1
|
2021-02-04T07:27:46.000Z
|
2021-02-04T07:27:46.000Z
|
libs/Aether/include/Aether/primary/Text.hpp
|
tkgstrator/SeedHack
|
227566d993bdea7a2851a8fc664b539186509697
|
[
"MIT"
] | null | null | null |
libs/Aether/include/Aether/primary/Text.hpp
|
tkgstrator/SeedHack
|
227566d993bdea7a2851a8fc664b539186509697
|
[
"MIT"
] | null | null | null |
#ifndef AETHER_TEXT_HPP
#define AETHER_TEXT_HPP
#include "Aether/base/BaseText.hpp"
namespace Aether {
/**
* @brief Text extends BaseText by implementing scrolling when the text overflows.
*
* It's for single-line text.
*/
class Text : public BaseText {
private:
/** @brief Indicator on whether the text is scrollable */
bool scroll_;
/** @brief Pixels to scroll per second */
int scrollSpeed_;
/** @brief Time since scroll finished (in ms) (only used internally) */
int scrollPauseTime;
/** @brief Generate a text surface */
void generateSurface();
public:
/**
* @brief Construct a new Text object
*
* @param x x-coordinate of start position offset
* @param y y-coordinate of start position offset
* @param s text string
* @param f font size
* @param l font style
* @param t \ref ::RenderType to use for texture generation
*/
Text(int x, int y, std::string s, unsigned int f, FontStyle l = FontStyle::Regular, RenderType t = RenderType::OnCreate);
/**
* @brief Indicator on whether the text is scrollable
*
* @return true if it is scrollable
* @return false otherwise
*/
bool scroll();
/**
* @brief Set whether the text is scrollable
*
* @param s true if text is scrollable, false otherwise
*/
void setScroll(bool s);
/**
* @brief Get the scroll speed for text
*
* @return scroll speed for text
*/
int scrollSpeed();
/**
* @brief Set the scroll speed for text
*
* @param s new scroll speed for text
*/
void setScrollSpeed(int s);
/**
* @brief Set the font size for the text
*
* @param f new font size
*/
void setFontSize(unsigned int f);
/**
* @brief Set text
*
* @param s new text to set
*/
void setString(std::string s);
/**
* @brief Updates the text.
*
* Update handles animating the scroll if necessary.
*
* @param dt change in time
*/
void update(uint32_t dt);
/**
* @brief Adjusts the text width.
*
* Adjusting width may need to adjust amount of text shown.
*
* @param w new width
*/
void setW(int w);
};
};
#endif
| 29.20202
| 133
| 0.471117
|
tkgstrator
|
27d9b546990c5c710f165f13626d9aab24f02301
| 1,020
|
cpp
|
C++
|
CTN_05_Hardware_3D_DirectX/src/PixelShader.cpp
|
TheUnicum/CTN_05_Hardware_3D_DirectX
|
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
|
[
"Apache-2.0"
] | null | null | null |
CTN_05_Hardware_3D_DirectX/src/PixelShader.cpp
|
TheUnicum/CTN_05_Hardware_3D_DirectX
|
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
|
[
"Apache-2.0"
] | null | null | null |
CTN_05_Hardware_3D_DirectX/src/PixelShader.cpp
|
TheUnicum/CTN_05_Hardware_3D_DirectX
|
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
|
[
"Apache-2.0"
] | null | null | null |
#include "PixelShader.h"
#include "GraphicsThrowMacros.h"
#include "BindableCodex.h"
#include "ChiliUtil.h"
namespace Bind
{
PixelShader::PixelShader(Graphics& gfx, const std::string& path)
:
path(path)
{
INFOMAN(gfx);
Microsoft::WRL::ComPtr<ID3DBlob> pBlob;
GFX_THROW_INFO(D3DReadFileToBlob(ToWide(path).c_str(), &pBlob));
GFX_THROW_INFO(GetDevice(gfx)->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), nullptr, &pPixelShader));
}
void PixelShader::Bind(Graphics& gfx) noxnd
{
INFOMAN_NOHR(gfx);
GFX_THROW_INFO_ONLY(GetContext(gfx)->PSSetShader(pPixelShader.Get(), nullptr, 0u));
}
std::shared_ptr<PixelShader> PixelShader::Resolve(Graphics& gfx, const std::string& path)
{
return Codex::Resolve<PixelShader>(gfx, path);
}
std::string PixelShader::GenerateUID(const std::string& path)
{
using namespace std::string_literals;
return typeid(PixelShader).name() + "#"s + path;
}
std::string PixelShader::GetUID() const noexcept
{
return GenerateUID(path);
}
}
| 26.842105
| 127
| 0.731373
|
TheUnicum
|
27dc65478aacdac1d26b33fa008c55c454198a04
| 5,526
|
cpp
|
C++
|
src/binaryServer/CachedConverterCallback.cpp
|
peramic/OPC-UA.Server
|
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
|
[
"Apache-2.0"
] | null | null | null |
src/binaryServer/CachedConverterCallback.cpp
|
peramic/OPC-UA.Server
|
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
|
[
"Apache-2.0"
] | null | null | null |
src/binaryServer/CachedConverterCallback.cpp
|
peramic/OPC-UA.Server
|
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
|
[
"Apache-2.0"
] | null | null | null |
#include "CachedConverterCallback.h"
#include <common/Exception.h>
#include <common/Mutex.h>
#include <common/MutexLock.h>
#include <common/ScopeGuard.h>
#include <common/logging/Logger.h>
#include <common/logging/LoggerFactory.h>
#include <sasModelProvider/base/ConversionException.h>
#include <uadatetime.h>
#include <sstream> // std::ostringstream
namespace SASModelProviderNamespace {
using namespace CommonNamespace;
class CachedConverterCallbackPrivate {
friend class CachedConverterCallback;
private:
Logger* log;
ConverterUa2IO::ConverterCallback* callback;
bool hasValuesAttached;
Mutex* mutex;
// type -> super types
std::map<UaNodeId, std::vector<UaNodeId>*> superTypes;
std::map<UaNodeId, UaStructureDefinition> structureDefinitions;
};
CachedConverterCallback::CachedConverterCallback(ConverterUa2IO::ConverterCallback& callback,
bool attachValue) /* throws MutexException */ {
d = new CachedConverterCallbackPrivate();
d->log = LoggerFactory::getLogger("CachedConverterCallback");
d->callback = &callback;
d->hasValuesAttached = attachValue;
d->mutex = new Mutex(); // MutexException
}
CachedConverterCallback::~CachedConverterCallback() {
clear();
if (d->hasValuesAttached) {
delete d->callback;
}
delete d->mutex;
delete d;
}
void CachedConverterCallback::clear() {
MutexLock lock(*d->mutex);
for (std::map<UaNodeId, std::vector<UaNodeId>*>::const_iterator it =
d->superTypes.begin(); it != d->superTypes.end(); it++) {
delete it->second;
}
d->superTypes.clear();
d->structureDefinitions.clear();
}
void CachedConverterCallback::preload(const UaNodeId& typeId) {
if (0 == typeId.namespaceIndex()) {
return;
}
// get base type
UaNodeId buildInDataTypeId;
std::vector<UaNodeId>* superTypes = getSuperTypes(typeId);
if (superTypes != NULL) {
ScopeGuard<std::vector<UaNodeId> > superTypesSG(superTypes);
if (superTypes->size() > 0) {
buildInDataTypeId = superTypes->back();
}
}
if (buildInDataTypeId.isNull()) {
std::ostringstream msg;
msg << "Cannot get base type of " << typeId.toXmlString().toUtf8();
throw ExceptionDef(ConversionException, msg.str());
}
switch (buildInDataTypeId.identifierNumeric()) {
case OpcUaId_Structure: // 22
case OpcUaId_Union: // 12756
{
UaStructureDefinition sd = getStructureDefinition(typeId);
if (!sd.isNull()) {
// for each field
for (int i = 0; i < sd.childrenCount(); i++) {
preload(sd.child(i).typeId());
}
} else {
std::ostringstream msg;
msg << "Cannot get structure definition of " << typeId.toXmlString().toUtf8();
throw ExceptionDef(ConversionException, msg.str());
}
break;
}
default:
break;
}
}
UaStructureDefinition CachedConverterCallback::getStructureDefinition(const UaNodeId& typeId)
/* throws ConversionException */ {
MutexLock lock(*d->mutex);
std::map<UaNodeId, UaStructureDefinition>::const_iterator it =
d->structureDefinitions.find(typeId);
if (it == d->structureDefinitions.end()) {
if (d->log->isDebugEnabled()) {
d->log->debug("Getting structure definition of %s", typeId.toXmlString().toUtf8());
}
UaStructureDefinition sd = d->callback->getStructureDefinition(typeId);
if (!sd.isNull()) {
d->structureDefinitions[typeId] = sd;
if (d->log->isDebugEnabled()) {
d->log->debug("Get structure definition");
}
return sd;
}
std::ostringstream msg;
msg << "Cannot get structure definition of " << typeId.toXmlString().toUtf8();
throw ExceptionDef(ConversionException, msg.str());
}
return it->second;
}
std::vector<UaNodeId>* CachedConverterCallback::getSuperTypes(const UaNodeId& typeId)
/* throws ConversionException */ {
MutexLock lock(*d->mutex);
std::map<UaNodeId, std::vector<UaNodeId>*>::const_iterator it = d->superTypes.find(typeId);
if (it == d->superTypes.end()) {
if (d->log->isDebugEnabled()) {
d->log->debug("Getting super types of %s", typeId.toXmlString().toUtf8());
}
std::vector<UaNodeId>* superTypeIds = d->callback->getSuperTypes(typeId);
if (superTypeIds != NULL) {
d->superTypes[typeId] = superTypeIds;
if (d->log->isDebugEnabled()) {
d->log->debug("Get %d super types", superTypeIds->size());
}
return new std::vector<UaNodeId>(*superTypeIds);
}
std::ostringstream msg;
msg << "Cannot get super types of " << typeId.toXmlString().toUtf8();
throw ExceptionDef(ConversionException, msg.str());
}
return new std::vector<UaNodeId>(*it->second);
}
}
| 38.643357
| 99
| 0.570575
|
peramic
|
27e252a5da99b05ecfa26445abd8b1f44f37d85a
| 722
|
cpp
|
C++
|
code/415.addStrings.cpp
|
T1mzhou/LeetCode
|
574540d30f5696e55799831dc3c8d8b7246b74f1
|
[
"MIT"
] | 1
|
2020-10-04T13:39:34.000Z
|
2020-10-04T13:39:34.000Z
|
code/415.addStrings.cpp
|
T1mzhou/LeetCode
|
574540d30f5696e55799831dc3c8d8b7246b74f1
|
[
"MIT"
] | null | null | null |
code/415.addStrings.cpp
|
T1mzhou/LeetCode
|
574540d30f5696e55799831dc3c8d8b7246b74f1
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<int> add(vector<int>& A, vector<int>& B) {
vector<int> C;
for (int i = 0, t = 0; i < A.size() || i < B.size() || t; i++) {
if (i < A.size()) t += A[i];
if (i < B.size()) t += B[i];
C.push_back(t % 10);
t /= 10;
}
return C;
}
string addStrings(string num1, string num2) {
vector<int> A, B;
for (int i = num1.size() - 1; i >= 0; i--) A.push_back(num1[i] - '0');
for (int i = num2.size() - 1; i >= 0; i--) B.push_back(num2[i] - '0');
auto C = add(A, B);
string c;
for (int i = C.size() - 1; i >= 0; i--) c += to_string(C[i]);
return c;
}
};
| 31.391304
| 78
| 0.414127
|
T1mzhou
|
27e699cf3d090e1f05b7311a45fa803498de7c0d
| 15,892
|
cpp
|
C++
|
Base/PLGui/src/Widgets/Controls/Label.cpp
|
naetherm/PixelLight
|
d7666f5b49020334cbb5debbee11030f34cced56
|
[
"MIT"
] | 1
|
2019-11-09T16:54:04.000Z
|
2019-11-09T16:54:04.000Z
|
Base/PLGui/src/Widgets/Controls/Label.cpp
|
naetherm/pixelligh
|
d7666f5b49020334cbb5debbee11030f34cced56
|
[
"MIT"
] | 27
|
2019-06-18T06:46:07.000Z
|
2020-02-02T11:11:28.000Z
|
Base/PLGui/src/Widgets/Controls/Label.cpp
|
naetherm/PixelLight
|
d7666f5b49020334cbb5debbee11030f34cced56
|
[
"MIT"
] | null | null | null |
/*********************************************************\
* File: Label.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLCore/String/RegEx.h>
#include "PLGui/Gui/Resources/Graphics.h"
#include "PLGui/Gui/Gui.h"
#include "PLGui/Themes/Theme.h"
#include "PLGui/Widgets/Controls/Label.h"
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
static const int GAP = 8; // Gap between two words
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
using namespace PLMath;
using namespace PLGraphics;
namespace PLGui {
//[-------------------------------------------------------]
//[ Class implementation ]
//[-------------------------------------------------------]
pl_class_metadata(Label, "PLGui", PLGui::Widget, "Widget that displays a static text")
// Constructors
pl_constructor_0_metadata(DefaultConstructor, "Default constructor", "")
// Attributes
pl_attribute_metadata(Color, PLGraphics::Color4, PLGraphics::Color4::Black, ReadWrite, "Text color", "")
pl_attribute_metadata(Align, pl_enum_type(EAlign), AlignLeft, ReadWrite, "Text alignment (horizontal)", "")
pl_attribute_metadata(VAlign, pl_enum_type(EVAlign), AlignMiddle, ReadWrite, "Text alignment (vertical)", "")
pl_attribute_metadata(Wrap, pl_enum_type(ETextWrap), TextWrap, ReadWrite, "Text wrapping", "")
pl_attribute_metadata(Style, pl_flag_type(ETextStyle), 0, ReadWrite, "Text style", "")
pl_attribute_metadata(Text, PLCore::String, "", ReadWrite, "Text label", "")
pl_class_metadata_end(Label)
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
Label::Label(Widget *pParent) : Widget(pParent),
Color(this),
Align(this),
VAlign(this),
Wrap(this),
Style(this),
Text(this),
m_cColor(Color4::Black),
m_nAlign(AlignLeft),
m_nVAlign(AlignMiddle),
m_nWrap(TextWrap),
m_nStyle(0),
m_cFont(*GetGui())
{
// Get default font
m_cFont = GetGui()->GetTheme()->GetDefaultFont();
// Don't accept keyboard focus
SetFocusStyle(NoFocus);
}
/**
* @brief
* Destructor
*/
Label::~Label()
{
}
/**
* @brief
* Get font
*/
const Font &Label::GetFont() const
{
// Return font
return m_cFont;
}
/**
* @brief
* Set font
*/
void Label::SetFont(const Font &cFont)
{
// Set font
m_cFont = cFont;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
/**
* @brief
* Get color
*/
Color4 Label::GetColor() const
{
// Return color
return m_cColor;
}
/**
* @brief
* Set color
*/
void Label::SetColor(const Color4 &cColor)
{
// Set color
m_cColor = cColor;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
/**
* @brief
* Get horizontal alignment
*/
EAlign Label::GetAlign() const
{
// Return alignment
return m_nAlign;
}
/**
* @brief
* Set horizontal alignment
*/
void Label::SetAlign(EAlign nAlign)
{
// Set alignment
m_nAlign = nAlign;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
/**
* @brief
* Get vertical alignment
*/
EVAlign Label::GetVAlign() const
{
// Return alignment
return m_nVAlign;
}
/**
* @brief
* Set vertical alignment
*/
void Label::SetVAlign(EVAlign nAlign)
{
// Set alignment
m_nVAlign = nAlign;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
/**
* @brief
* Get text wrapping
*/
ETextWrap Label::GetWrap() const
{
// Return wrapping
return m_nWrap;
}
/**
* @brief
* Set text wrapping
*/
void Label::SetWrap(ETextWrap nWrap)
{
// Set wrapping
m_nWrap = nWrap;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
/**
* @brief
* Get text style
*/
uint32 Label::GetStyle() const
{
// Return style
return m_nStyle;
}
/**
* @brief
* Set text style
*/
void Label::SetStyle(uint32 nStyle)
{
// Set style
m_nStyle = nStyle;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
/**
* @brief
* Get text
*/
String Label::GetText() const
{
// Return text
return m_sText;
}
/**
* @brief
* Set text
*/
void Label::SetText(const String &sText)
{
// Set text
m_sText = sText;
// Update widget
UpdateContent();
// Redraw
Redraw();
}
//[-------------------------------------------------------]
//[ Protected virtual WidgetFunctions functions ]
//[-------------------------------------------------------]
PLMath::Vector2i Label::OnPreferredSize(const Vector2i &vRefSize) const
{
// Call base function
Widget::OnPreferredSize(vRefSize);
// Try to calculate the size in Y direction. If X is already known, we can use the actual line width
// to calculate the height, otherwise we use a virtually endless line and therefore calculate only
// hard-coded line feeds.
// Create an offscreen graphics object
Graphics cGraphics(*GetGui());
// Get font
Font cFont = GetFont();
// Get underline mode
int nUnderline = 0;
if (GetStyle() & UnderlineText) {
nUnderline = 2;
}
// First of all: Is there any text?
String sText = GetText();
if (sText.GetLength()) {
// Get text width and height
uint32 nTextWidth = cGraphics.GetTextWidth (cFont, sText);
uint32 nTextHeight = cGraphics.GetTextHeight(cFont, sText);
// Get line with
int nLineWidth = vRefSize.x;
// Check if text has to be wrapped
bool bHasNewLines = (sText.IndexOf('\r') > -1) || (sText.IndexOf('\n') > -1);
if (GetWrap() == NoTextWrap || (nLineWidth > -1 && static_cast<int>(nTextWidth) < nLineWidth && !bHasNewLines) ) {
// No wrapping
Vector2i vPreferredSize;
vPreferredSize.x = (vRefSize.x > -1 ? vRefSize.x : nTextWidth);
vPreferredSize.y = nTextHeight + nUnderline;
return vPreferredSize;
} else {
// With text wrapping
int nGap = GAP; // Gap between two words
// Get words and mark newlines
RegEx cRegEx("([\\r\\n])|([\\s]*([\\S]+))");
Array<String> lstWords;
uint32 nParsePos = 0;
uint32 nLine = 0;
uint32 nNumLines = 0;
while (cRegEx.Match(sText, nParsePos)) {
// Get next word
nParsePos = cRegEx.GetPosition();
String sWord = cRegEx.GetResult(0);
if (sWord.GetLength() > 0) sWord = '\n';
else sWord = cRegEx.GetResult(2);
int nWidth = cGraphics.GetTextWidth(cFont, sWord);
// Add word to line
if ((sWord != '\n') && (static_cast<int>(nLine+nWidth) <= nLineWidth || nLineWidth <= -1 || nLine == 0)) {
// Add word
lstWords.Add(sWord);
nLine += nWidth + nGap;
} else {
// Add line wrap
lstWords.Add('\n');
nLine = 0;
nNumLines++;
// Add first word of next line
if (sWord != '\n') {
lstWords.Add(sWord);
nLine = nWidth + nGap;
}
}
}
// Add '\n' after last line
String sLastWord = lstWords.Get(lstWords.GetNumOfElements()-1);
if (sLastWord.GetLength() && sLastWord != '\n') {
lstWords.Add('\n');
nNumLines++;
}
// Set start position (Y)
Vector2i vPos(0, 0);
// Calculate lines
int nMaxLineWidth = -1;
uint32 nFirst = 0;
while (nFirst < lstWords.GetNumOfElements()) {
// Get end of line ('\n')
uint32 nLast;
for (nLast=nFirst; nLast<lstWords.GetNumOfElements(); nLast++) {
if (lstWords[nLast] == '\n') break;
}
// Get number of words in this line
uint32 nWords = nLast - nFirst;
if (nWords > 0) {
// Get width of line
uint32 nWidth = 0;
for (uint32 i=nFirst; i<nLast; i++) {
if (nWidth > 0 && GetWrap() != TextWrapBlock) nWidth += nGap;
nWidth += cGraphics.GetTextWidth(cFont, lstWords[i]);
}
// Set start position (X)
vPos.x = 0;
if (GetWrap() == TextWrapBlock) {
// Calculate size of gaps between words for block-text
if (nLineWidth > -1) nGap = (nLineWidth - nWidth) / (nWords>1 ? nWords-1 : 1);
else nGap = GAP;
if (nWords > 1) nWidth += (nWords-1) * nGap;
} else {
// No block text, use static gaps and align text by alignment options
nGap = GAP;
if (nLineWidth > -1) {
if (GetAlign() == AlignCenter) vPos.x = nLineWidth/2 - nWidth/2; // Center
else if (GetAlign() == AlignRight) vPos.x = nLineWidth - nWidth; // Right
}
}
Vector2i vStartPos = vPos;
// Calculate line
for (uint32 i=nFirst; i<nLast; i++) {
// Get word
String sWord = lstWords[i];
// Next word
vPos.x += cGraphics.GetTextWidth(cFont, sWord) + nGap;
}
// Save width of widest line
if (static_cast<int>(nWidth) > nMaxLineWidth)
nMaxLineWidth = nWidth;
}
// Next line
nFirst = nLast + 1;
vPos.y += nTextHeight;
}
// Return vertical size
Vector2i vPreferredSize;
vPreferredSize.x = (vRefSize.x > -1 ? vRefSize.x : nMaxLineWidth);
vPreferredSize.y = vPos.y + nUnderline;
return vPreferredSize;
}
}
// Use something like a standard text height
uint32 nTextHeight = cGraphics.GetTextHeight(cFont, "Text");
return Vector2i(-1, nTextHeight + nUnderline);
}
void Label::OnDraw(Graphics &cGraphics)
{
// Call base implementation
Widget::OnDraw(cGraphics);
// First of all: Is there any text?
String sText = GetText();
if (sText.GetLength()) {
// Get font
Font cFont = GetFont();
// Get text color
Color4 cColor = IsEnabled() ? GetColor() : Color4::Gray;
// Get text width and height
uint32 nTextWidth = cGraphics.GetTextWidth (cFont, sText);
uint32 nTextHeight = cGraphics.GetTextHeight(cFont, sText);
// Get line with
int nLineWidth = GetSize().x;
// Check if text has to be wrapped
bool bHasNewLines = (sText.IndexOf('\r') > -1) || (sText.IndexOf('\n') > -1);
if (GetWrap() == NoTextWrap || (static_cast<int>(nTextWidth) < nLineWidth && !bHasNewLines) ) {
// No wrapping
// Align text (horizontally)
uint32 nX = 0;
if (GetAlign() == AlignCenter) nX = GetSize().x/2 - nTextWidth/2; // Center
else if (GetAlign() == AlignRight) nX = GetSize().x - nTextWidth; // Right
// Align text (vertically)
uint32 nY = 0;
if (GetVAlign() == AlignBottom) nY = GetSize().y - nTextHeight; // Bottom
else if (GetVAlign() == AlignMiddle) nY = GetSize().y/2 - nTextHeight/2; // Middle
// Draw text
cGraphics.DrawText(cFont, cColor, Color4::Transparent, Vector2i(nX, nY), sText);
// Draw underline
if (GetStyle() & UnderlineText)
cGraphics.DrawLine(cColor, Vector2i(nX, nY + nTextHeight), Vector2i(nX + nTextWidth, nY + nTextHeight));
// Draw cross-out
if (GetStyle() & CrossoutText)
cGraphics.DrawLine(cColor, Vector2i(nX, nY + nTextHeight/2), Vector2i(nX + nTextWidth, nY + nTextHeight/2));
} else {
// Draw with text wrapping
int nGap = GAP; // Gap between two words
// Get words and mark newlines
RegEx cRegEx("([\\r\\n])|([\\s]*([\\S]+))");
Array<String> lstWords;
uint32 nParsePos = 0;
uint32 nLine = 0;
uint32 nNumLines = 0;
while (cRegEx.Match(sText, nParsePos)) {
// Get next word
nParsePos = cRegEx.GetPosition();
String sWord = cRegEx.GetResult(0);
if (sWord.GetLength() > 0) sWord = '\n';
else sWord = cRegEx.GetResult(2);
int nWidth = cGraphics.GetTextWidth(cFont, sWord);
// Add word to line
if ((sWord != '\n') && (static_cast<int>(nLine+nWidth) <= nLineWidth || nLine == 0)) {
// Add word
lstWords.Add(sWord);
nLine += nWidth + nGap;
} else {
// Add line wrap
lstWords.Add('\n');
nLine = 0;
nNumLines++;
// Add first word of next line
if (sWord != '\n') {
lstWords.Add(sWord);
nLine = nWidth + nGap;
}
}
}
// Add '\n' after last line
String sLastWord = lstWords.Get(lstWords.GetNumOfElements()-1);
if (sLastWord.GetLength() && sLastWord != '\n') {
lstWords.Add('\n');
nNumLines++;
}
// Set start position (Y)
Vector2i vPos(0, 0);
if (GetVAlign() == AlignBottom) vPos.y = GetSize().y - (nTextHeight*nNumLines); // Bottom
else if (GetVAlign() == AlignMiddle) vPos.y = GetSize().y/2 - (nTextHeight*nNumLines)/2; // Middle
// Print lines
uint32 nFirst = 0;
while (nFirst < lstWords.GetNumOfElements()) {
// Get end of line ('\n')
uint32 nLast;
for (nLast=nFirst; nLast<lstWords.GetNumOfElements(); nLast++) {
if (lstWords[nLast] == '\n') break;
}
// Get number of words in this line
uint32 nWords = nLast - nFirst;
if (nWords > 0) {
// Get width of line
uint32 nWidth = 0;
for (uint32 i=nFirst; i<nLast; i++) {
if (nWidth > 0 && GetWrap() != TextWrapBlock) nWidth += nGap;
nWidth += cGraphics.GetTextWidth(cFont, lstWords[i]);
}
// Set start position (X)
vPos.x = 0;
if (GetWrap() == TextWrapBlock) {
// Calculate size of gaps between words for block-text
nGap = (GetSize().x - nWidth) / (nWords>1 ? nWords-1 : 1);
if (nWords > 1) nWidth += (nWords-1) * nGap;
} else {
// No block text, use static gaps and align text by alignment options
nGap = GAP;
if (GetAlign() == AlignCenter) vPos.x = nLineWidth/2 - nWidth/2; // Center
else if (GetAlign() == AlignRight) vPos.x = nLineWidth - nWidth; // Right
}
Vector2i vStartPos = vPos;
// Print line
for (uint32 i=nFirst; i<nLast; i++) {
// Get word
String sWord = lstWords[i];
// Draw word
cGraphics.DrawText(cFont, cColor, Color4::Transparent, vPos, sWord);
// Next word
vPos.x += cGraphics.GetTextWidth(cFont, sWord) + nGap;
}
// Draw underline
if (GetStyle() & UnderlineText)
cGraphics.DrawLine(cColor, Vector2i(vStartPos.x, vStartPos.y+nTextHeight), Vector2i(vStartPos.x+nWidth, vStartPos.y+nTextHeight));
// Draw cross-out
if (GetStyle() & CrossoutText)
cGraphics.DrawLine(cColor, Vector2i(vStartPos.x, vStartPos.y+nTextHeight/2), Vector2i(vStartPos.x+nWidth, vStartPos.y+nTextHeight/2));
}
// Next line
nFirst = nLast + 1;
vPos.y += nTextHeight;
}
}
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLGui
| 26.267769
| 140
| 0.586333
|
naetherm
|
27ef3911b12e41cec13c81fd65eda459051308ba
| 6,818
|
cpp
|
C++
|
src/autoxtime/db/DbListener.cpp
|
nmaludy/autoxtime
|
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
|
[
"Apache-2.0"
] | null | null | null |
src/autoxtime/db/DbListener.cpp
|
nmaludy/autoxtime
|
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
|
[
"Apache-2.0"
] | 4
|
2021-02-23T20:56:42.000Z
|
2021-04-03T01:56:08.000Z
|
src/autoxtime/db/DbListener.cpp
|
nmaludy/autoxtime
|
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
|
[
"Apache-2.0"
] | null | null | null |
#include <autoxtime/db/DbListener.h>
#include <autoxtime/db/DbConnection.h>
#include <autoxtime/log/Log.h>
#include <google/protobuf/util/json_util.h>
#include <QSemaphore>
#include <iostream>
AUTOXTIME_DB_NAMESPACE_BEG
DbEmitter::DbEmitter(const google::protobuf::Message& prototype)
: QObject(),
mpPrototype(prototype.New())
{}
DbEmitter::~DbEmitter()
{}
void DbEmitter::emitNotification(const QString& name,
QSqlDriver::NotificationSource source,
const QVariant& payload)
{
// Note: as a measure of efficiency we convert and parse the JSON data once
// then pass the parsed google::protobuf::Message to the emitted signal
// so that we dont' have to parse the message over/over in each listener
QByteArray payload_ba = payload.toString().toUtf8();
QJsonDocument payload_doc = QJsonDocument::fromJson(payload_ba);
QJsonObject payload_json = payload_doc.object();
// payload contains following fields:
// "timestamp" - string
// "operation" - string (UPDATE, INSERT, DELETE, etc)
// "data" - data/row that was changed, encoded as JSON
QString timestamp_str = payload_json.value("timestamp").toString();
QString operation = payload_json.value("operation").toString();
QJsonDocument data_doc(payload_json.value("data").toObject());
// parse ISO 8601 timestamp
QDateTime timestamp = QDateTime::fromString(timestamp_str, Qt::ISODate);
// convert Qt string to string we can use for parsing
QString data_json(data_doc.toJson());
std::string data_str(data_json.toStdString());
google::protobuf::StringPiece piece(data_str.data());
// create a new message that will be filled in with the data from the JSON string
std::shared_ptr<google::protobuf::Message> msg(mpPrototype->New());
// parse JSON into the message
google::protobuf::util::Status status =
google::protobuf::util::JsonStringToMessage(piece, msg.get());
if (status.ok())
{
AXT_DEBUG << "DbEmitter - Notification name=" << name
<< " thread=" << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId())
<< " timestamp=" << timestamp
<< " operation=" << operation
<< " payload=" << payload_ba << "\n"
<< " msg=" << msg->DebugString();
emit notification(msg, timestamp, operation);
}
else
{
AXT_ERROR << "Error parsing JSON payload error='"<< status.ToString() << "'"
<< " channel=" << name
<< " timestamp=" << timestamp
<< " operation=" << operation
<< " payload=" << payload;
}
}
////////////////////////////////////////////////////////////////////////////////
DbListener::DbListener()
: QThread(),
mpStartSemaphore(new QSemaphore()),
mpConnection()
{
qRegisterMetaType<std::shared_ptr<google::protobuf::Message>>();
start();
// avoid race condition on start, wait until we're connected
mpStartSemaphore->acquire(1);
// move this object to "this" thread so that signals cross the right boundaries
moveToThread(this);
}
DbListener& DbListener::instance()
{
static DbListener thread;
return thread;
}
void DbListener::run()
{
AXT_DEBUG << "In DbListener thread"
<< QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId());
{
std::unique_lock<std::mutex> lock(mConnectionMutex);
mpConnection = std::make_unique<DbConnection>(this);
}
// hook up our listener before subscribing
connect(mpConnection->database().driver(),
qOverload<const QString&, QSqlDriver::NotificationSource , const QVariant&>(&QSqlDriver::notification),
this, &DbListener::recvNotification);
connect(this, &DbListener::subscribeSignal,
this, &DbListener::subscribeSlot);
// avoid race condition on start, wait until we're connected
mpStartSemaphore->release(1);
// run our event loop
QThread::run();
{
AXT_DEBUG << "Stopping DbListener thread"
<< QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId());
// destroy the connection, still in our thread, to avoid warnings about tearing
// down the QTimers in another thread
std::unique_lock<std::mutex> lock(mConnectionMutex);
mpConnection.reset();
}
}
DbEmitter* DbListener::emitter(const google::protobuf::Message& prototype,
const QString& tableName)
{
std::unique_lock<std::mutex> lock(mEmitterMutex);
std::unordered_map<QString, std::unique_ptr<DbEmitter>>::iterator iter =
mEmitters.find(tableName);
if (iter != mEmitters.end())
{
return iter->second.get();
}
else
{
mEmitters[tableName] = std::make_unique<DbEmitter>(prototype);
return mEmitters[tableName].get();
}
}
void DbListener::subscribe(const google::protobuf::Message& prototype,
const QString& tableName)
{
AXT_DEBUG << "subscribe for channel "
<< tableName
<< " called from thread: " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId());
// create an emitter for this subscription, just in case one doesn't exist
emitter(prototype, tableName);
// send signal to our background thread that we want to subscribe to this new channel
emit subscribeSignal(tableName);
}
void DbListener::subscribeSlot(const QString& channel)
{
AXT_DEBUG << "subscribeSlot for channel "
<< channel
<< " called in thread: " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId());
std::unique_lock<std::mutex> lock(mConnectionMutex);
if (mpConnection)
{
mpConnection->database().driver()->subscribeToNotification(channel);
}
}
void DbListener::recvNotification(const QString& name,
QSqlDriver::NotificationSource source,
const QVariant& payload)
{
std::unique_lock<std::mutex> lock(mEmitterMutex);
std::unordered_map<QString, std::unique_ptr<DbEmitter>>::iterator iter = mEmitters.find(name);
if (iter != mEmitters.end())
{
AXT_DEBUG << "Notification found_emitter=true name=" << name
<< " thread= " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId())
<< " payload=" << payload.toString();
iter->second->emitNotification(name, source, payload);
}
else
{
AXT_DEBUG << "Notification found_emitter=false name=" << name
<< " thread= " << QString("autoxtime::thread_") + QString::number((intptr_t)QThread::currentThreadId())
<< " payload=" << payload.toString();
}
emit notification(name, source, payload);
}
AUTOXTIME_DB_NAMESPACE_END
| 35.326425
| 128
| 0.652977
|
nmaludy
|
27f2e20ee83b2678a10d6728ab2b4ca3b15b0503
| 580
|
cpp
|
C++
|
ports/esp32/src/hSystem.cpp
|
ygjukim/hFramework
|
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
|
[
"MIT"
] | 33
|
2017-07-03T22:49:30.000Z
|
2022-03-31T19:32:55.000Z
|
ports/esp32/src/hSystem.cpp
|
ygjukim/hFramework
|
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
|
[
"MIT"
] | 6
|
2017-07-13T13:23:22.000Z
|
2019-10-25T17:51:28.000Z
|
ports/esp32/src/hSystem.cpp
|
ygjukim/hFramework
|
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
|
[
"MIT"
] | 17
|
2017-07-01T05:35:47.000Z
|
2022-03-22T23:33:00.000Z
|
/**
* Copyright (c) 2013-2017 Husarion Sp. z o.o.
* Distributed under the MIT license.
* For full terms see the file LICENSE.md.
*/
#include "hSystem.h"
#include <cstring>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
};
namespace hFramework {
uint32_t hSystem::getRandNr() {
return (uint32_t)esp_random();
}
uint64_t hSystem::getSerialNum() {
uint8_t mac[8];
esp_efuse_read_mac(mac);
uint64_t id;
memcpy(&id, mac, 8);
return id;
}
void hSystem::reset() {
system_restart();
}
hSystem sys;
}
| 15.675676
| 46
| 0.663793
|
ygjukim
|
27f85a367dbf23a4e12bc9099bddd1f19dd96cbe
| 5,936
|
hpp
|
C++
|
sol/function_types_member.hpp
|
SuperV1234/sol2
|
76b73bdfab4475933c42e715fd98737a4699794a
|
[
"MIT"
] | null | null | null |
sol/function_types_member.hpp
|
SuperV1234/sol2
|
76b73bdfab4475933c42e715fd98737a4699794a
|
[
"MIT"
] | null | null | null |
sol/function_types_member.hpp
|
SuperV1234/sol2
|
76b73bdfab4475933c42e715fd98737a4699794a
|
[
"MIT"
] | 1
|
2021-05-02T15:57:13.000Z
|
2021-05-02T15:57:13.000Z
|
// The MIT License (MIT)
// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors
// 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 SOL_FUNCTION_TYPES_MEMBER_HPP
#define SOL_FUNCTION_TYPES_MEMBER_HPP
#include "function_types_core.hpp"
namespace sol {
namespace function_detail {
template<typename Func>
struct free_function : public base_function {
typedef meta::unwrapped_t<meta::unqualified_t<Func>> Function;
typedef meta::function_return_t<Function> return_type;
typedef meta::function_args_t<Function> args_lists;
Function fx;
template<typename... Args>
free_function(Args&&... args): fx(std::forward<Args>(args)...) {}
int call(lua_State* L) {
return stack::call_into_lua(meta::tuple_types<return_type>(), args_lists(), L, 1, fx);
}
virtual int operator()(lua_State* L) override {
auto f = [&](lua_State* L) -> int { return this->call(L);};
return detail::trampoline(L, f);
}
};
template<typename Func>
struct functor_function : public base_function {
typedef meta::unwrapped_t<meta::unqualified_t<Func>> Function;
typedef decltype(&Function::operator()) function_type;
typedef meta::function_return_t<function_type> return_type;
typedef meta::function_args_t<function_type> args_lists;
Function fx;
template<typename... Args>
functor_function(Args&&... args): fx(std::forward<Args>(args)...) {}
int call(lua_State* L) {
return stack::call_into_lua(meta::tuple_types<return_type>(), args_lists(), L, 1, fx);
}
virtual int operator()(lua_State* L) override {
auto f = [&](lua_State* L) -> int { return this->call(L);};
return detail::trampoline(L, f);
}
};
template<typename T, typename Function>
struct member_function : public base_function {
typedef std::remove_pointer_t<std::decay_t<Function>> function_type;
typedef meta::function_return_t<function_type> return_type;
typedef meta::function_args_t<function_type> args_lists;
struct functor {
function_type invocation;
T member;
template<typename F, typename... Args>
functor(F&& f, Args&&... args): invocation(std::forward<F>(f)), member(std::forward<Args>(args)...) {}
template<typename... Args>
return_type operator()(Args&&... args) {
auto& mem = detail::unwrap(detail::deref(member));
return (mem.*invocation)(std::forward<Args>(args)...);
}
} fx;
template<typename F, typename... Args>
member_function(F&& f, Args&&... args) : fx(std::forward<F>(f), std::forward<Args>(args)...) {}
int call(lua_State* L) {
return stack::call_into_lua(meta::tuple_types<return_type>(), args_lists(), L, 1, fx);
}
virtual int operator()(lua_State* L) override {
auto f = [&](lua_State* L) -> int { return this->call(L);};
return detail::trampoline(L, f);
}
};
template<typename T, typename Function>
struct member_variable : public base_function {
typedef std::remove_pointer_t<std::decay_t<Function>> function_type;
typedef typename meta::bind_traits<function_type>::return_type return_type;
typedef typename meta::bind_traits<function_type>::args_list args_lists;
function_type var;
T member;
typedef std::add_lvalue_reference_t<meta::unwrapped_t<std::remove_reference_t<decltype(detail::deref(member))>>> M;
template<typename V, typename... Args>
member_variable(V&& v, Args&&... args): var(std::forward<V>(v)), member(std::forward<Args>(args)...) {}
int set_assignable(std::false_type, lua_State* L, M) {
lua_pop(L, 1);
return luaL_error(L, "sol: cannot write to this type: copy assignment/constructor not available");
}
int set_assignable(std::true_type, lua_State* L, M mem) {
(mem.*var) = stack::get<return_type>(L, 1);
lua_pop(L, 1);
return 0;
}
int set_variable(std::true_type, lua_State* L, M mem) {
return set_assignable(std::is_assignable<std::add_lvalue_reference_t<return_type>, return_type>(), L, mem);
}
int set_variable(std::false_type, lua_State* L, M) {
lua_pop(L, 1);
return luaL_error(L, "sol: cannot write to a const variable");
}
int call(lua_State* L) {
M mem = detail::unwrap(detail::deref(member));
switch (lua_gettop(L)) {
case 0:
stack::push(L, (mem.*var));
return 1;
case 1:
return set_variable(meta::neg<std::is_const<return_type>>(), L, mem);
default:
return luaL_error(L, "sol: incorrect number of arguments to member variable function");
}
}
virtual int operator()(lua_State* L) override {
auto f = [&](lua_State* L) -> int { return this->call(L);};
return detail::trampoline(L, f);
}
};
} // function_detail
} // sol
#endif // SOL_FUNCTION_TYPES_MEMBER_HPP
| 38.051282
| 119
| 0.673349
|
SuperV1234
|
27f90f4cda72a862e2d5853d1e85cef25c5ee71a
| 552
|
hpp
|
C++
|
P4/usuario_pedido.hpp
|
moooises/Practica-Global-de-Programacion-Orientada-a-Objetos
|
534f909c6cd731482baaf9682feb6d07d9d35fa6
|
[
"MIT"
] | null | null | null |
P4/usuario_pedido.hpp
|
moooises/Practica-Global-de-Programacion-Orientada-a-Objetos
|
534f909c6cd731482baaf9682feb6d07d9d35fa6
|
[
"MIT"
] | null | null | null |
P4/usuario_pedido.hpp
|
moooises/Practica-Global-de-Programacion-Orientada-a-Objetos
|
534f909c6cd731482baaf9682feb6d07d9d35fa6
|
[
"MIT"
] | null | null | null |
#ifndef USUARIO_PEDIDO_HPP_
#define USUARIO_PEDIDO_HPP_
#include "usuario.hpp"
#include "pedido.hpp"
#include<set>
#include<map>
class Usuario;
class Pedido;
class Usuario_Pedido{
public:
typedef set<Pedido*> Pedidos;
void asocia(Usuario& user, Pedido& p);
void asocia(Pedido& p,Usuario& user){asocia(user,p);}
Pedidos pedidos(Usuario& user);
Usuario* cliente(Pedido& p);
private:
map<Usuario*,Pedidos> UP;//insert se usa para los set
map<Pedido*,Usuario*> PU;
};
#endif // USUARIO_PEDIDO_HPP_
| 21.230769
| 58
| 0.681159
|
moooises
|
27fb12c20936fbd399932af3586df1acb164d0df
| 29,028
|
inl
|
C++
|
include/sre/impl/ShaderSource.inl
|
KasperHdL/SimpleRenderEngine
|
2d7edeead1d14e00c3d41a29cf9880e216d366e0
|
[
"MIT"
] | null | null | null |
include/sre/impl/ShaderSource.inl
|
KasperHdL/SimpleRenderEngine
|
2d7edeead1d14e00c3d41a29cf9880e216d366e0
|
[
"MIT"
] | null | null | null |
include/sre/impl/ShaderSource.inl
|
KasperHdL/SimpleRenderEngine
|
2d7edeead1d14e00c3d41a29cf9880e216d366e0
|
[
"MIT"
] | null | null | null |
// autogenerated by
// files_to_cpp shader src/embedded_deps/skybox_frag.glsl skybox_frag.glsl src/embedded_deps/skybox_vert.glsl skybox_vert.glsl src/embedded_deps/sre_utils_incl.glsl sre_utils_incl.glsl src/embedded_deps/debug_normal_frag.glsl debug_normal_frag.glsl src/embedded_deps/debug_normal_vert.glsl debug_normal_vert.glsl src/embedded_deps/debug_uv_frag.glsl debug_uv_frag.glsl src/embedded_deps/debug_uv_vert.glsl debug_uv_vert.glsl src/embedded_deps/light_incl.glsl light_incl.glsl src/embedded_deps/particles_frag.glsl particles_frag.glsl src/embedded_deps/particles_vert.glsl particles_vert.glsl src/embedded_deps/sprite_frag.glsl sprite_frag.glsl src/embedded_deps/sprite_vert.glsl sprite_vert.glsl src/embedded_deps/standard_pbr_frag.glsl standard_pbr_frag.glsl src/embedded_deps/standard_pbr_vert.glsl standard_pbr_vert.glsl src/embedded_deps/standard_blinn_phong_frag.glsl standard_blinn_phong_frag.glsl src/embedded_deps/standard_blinn_phong_vert.glsl standard_blinn_phong_vert.glsl src/embedded_deps/standard_phong_frag.glsl standard_phong_frag.glsl src/embedded_deps/standard_phong_vert.glsl standard_phong_vert.glsl src/embedded_deps/blit_frag.glsl blit_frag.glsl src/embedded_deps/blit_vert.glsl blit_vert.glsl src/embedded_deps/unlit_frag.glsl unlit_frag.glsl src/embedded_deps/unlit_vert.glsl unlit_vert.glsl src/embedded_deps/debug_tangent_frag.glsl debug_tangent_frag.glsl src/embedded_deps/debug_tangent_vert.glsl debug_tangent_vert.glsl src/embedded_deps/normalmap_incl.glsl normalmap_incl.glsl src/embedded_deps/global_uniforms_incl.glsl global_uniforms_incl.glsl include/sre/impl/ShaderSource.inl
#include <map>
#include <utility>
#include <string>
std::map<std::string, std::string> builtInShaderSource {
std::make_pair<std::string,std::string>("skybox_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec3 vUV;
uniform vec4 color;
uniform samplerCube tex;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = color * toLinear(texture(tex, vUV));
//fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("skybox_vert.glsl",R"(#version 330
in vec3 position;
out vec3 vUV;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
vec4 eyespacePos = (g_view * vec4(position, 0.0));
eyespacePos.w = 1.0;
gl_Position = g_model * eyespacePos; // model matrix here contains the infinite projection
vUV = position;
})"),
std::make_pair<std::string,std::string>("sre_utils_incl.glsl",R"(vec4 toLinear(vec4 col){
#ifndef SI_TEX_SAMPLER_SRGB
float gamma = 2.2;
return vec4 (
col.xyz = pow(col.xyz, vec3(gamma)),
col.w
);
#else
return col;
#endif
}
vec4 toOutput(vec4 colorLinear){
#ifndef SI_FRAMEBUFFER_SRGB
float gamma = 2.2;
return vec4(pow(colorLinear.xyz,vec3(1.0/gamma)), colorLinear.a); // gamma correction
#else
return colorLinear;
#endif
}
vec4 toOutput(vec3 colorLinear, float alpha){
#ifndef SI_FRAMEBUFFER_SRGB
float gamma = 2.2;
return vec4(pow(colorLinear,vec3(1.0/gamma)), alpha); // gamma correction
#else
return vec4(colorLinear, alpha); // pass through
#endif
})"),
std::make_pair<std::string,std::string>("debug_normal_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec3 vNormal;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = vec4(vNormal*0.5+0.5,1.0);
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("debug_normal_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
out vec3 vNormal;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
gl_Position = g_projection * g_view * g_model * vec4(position,1.0);
vNormal = normal;
})"),
std::make_pair<std::string,std::string>("debug_uv_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec4 vUV;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = vUV;
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("debug_uv_vert.glsl",R"(#version 330
in vec3 position;
in vec4 uv;
out vec4 vUV;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
gl_Position = g_projection * g_view * g_model * vec4(position,1.0);
vUV = uv;
})"),
std::make_pair<std::string,std::string>("light_incl.glsl",R"(
in vec4 vLightDir[SI_LIGHTS];
uniform vec4 specularity;
void lightDirectionAndAttenuation(vec4 lightPosType, float lightRange, vec3 pos, out vec3 lightDirection, out float attenuation){
bool isDirectional = lightPosType.w == 0.0;
bool isPoint = lightPosType.w == 1.0;
if (isDirectional){
lightDirection = lightPosType.xyz;
attenuation = 1.0;
} else if (isPoint) {
vec3 lightVector = lightPosType.xyz - pos;
float lightVectorLength = length(lightVector);
lightDirection = lightVector / lightVectorLength; // normalize
if (lightRange <= 0.0){ // attenuation disabled
attenuation = 1.0;
} else if (lightVectorLength >= lightRange){
attenuation = 0.0;
return;
} else {
attenuation = pow(1.0 - (lightVectorLength / lightRange), 1.5); // non physical range based attenuation
}
} else {
attenuation = 0.0;
lightDirection = vec3(0.0, 0.0, 0.0);
}
}
vec3 computeLightBlinnPhong(vec3 wsPos, vec3 wsCameraPos, vec3 normal, out vec3 specularityOut){
specularityOut = vec3(0.0, 0.0, 0.0);
vec3 lightColor = vec3(0.0,0.0,0.0);
vec3 cam = normalize(wsCameraPos - wsPos);
for (int i=0;i<SI_LIGHTS;i++){
vec3 lightDirection = vec3(0.0,0.0,0.0);
float att = 0.0;
lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, wsPos, lightDirection, att);
if (att <= 0.0){
continue;
}
// diffuse light
float diffuse = dot(lightDirection, normal);
if (diffuse > 0.0){
lightColor += (att * diffuse) * g_lightColorRange[i].xyz;
}
// specular light
if (specularity.a > 0.0){
vec3 H = normalize(lightDirection + cam);
float nDotHV = dot(normal, H);
if (nDotHV > 0.0){
float pf = pow(nDotHV, specularity.a);
specularityOut += specularity.rgb * pf * att * diffuse; // white specular highlights
}
}
}
lightColor = max(g_ambientLight.xyz, lightColor);
return lightColor;
}
vec3 computeLightBlinn(vec3 wsPos, vec3 wsCameraPos, vec3 normal){
vec3 lightColor = vec3(0.0,0.0,0.0);
for (int i=0;i<SI_LIGHTS;i++){
vec3 lightDirection = vec3(0.0,0.0,0.0);
float att = 0.0;
lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, wsPos, lightDirection, att);
if (att <= 0.0){
continue;
}
// diffuse light
float diffuse = dot(lightDirection, normal);
if (diffuse > 0.0){
lightColor += (att * diffuse) * g_lightColorRange[i].xyz;
}
}
lightColor = max(g_ambientLight.xyz, lightColor);
return lightColor;
}
vec3 computeLightPhong(vec3 wsPos, vec3 wsCameraPos, vec3 normal, out vec3 specularityOut){
specularityOut = vec3(0.0, 0.0, 0.0);
vec3 lightColor = vec3(0.0,0.0,0.0);
vec3 cam = normalize(wsCameraPos - wsPos);
for (int i=0;i<SI_LIGHTS;i++){
vec3 lightDirection = vec3(0.0,0.0,0.0);
float att = 0.0;
lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, wsPos, lightDirection, att);
if (att <= 0.0){
continue;
}
// diffuse light
float diffuse = dot(lightDirection, normal);
if (diffuse > 0.0){
lightColor += (att * diffuse) * g_lightColorRange[i].xyz;
}
// specular light
if (specularity.a > 0.0){
vec3 R = reflect(-lightDirection, normal);
float nDotRV = dot(cam, R);
if (nDotRV > 0.0){
float pf = pow(nDotRV, specularity.a);
specularityOut += specularity.rgb * (pf * att); // white specular highlights
}
}
}
lightColor = max(g_ambientLight.xyz, lightColor);
return lightColor;
})"),
std::make_pair<std::string,std::string>("particles_frag.glsl",R"(#version 330
out vec4 fragColor;
in mat3 vUVMat;
in vec3 uvSize;
in vec4 vColor;
#pragma include "global_uniforms_incl.glsl"
uniform sampler2D tex;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
vec2 uv = (vUVMat * vec3(gl_PointCoord,1.0)).xy;
if (uv != clamp(uv, uvSize.xy, uvSize.xy + uvSize.zz)){
discard;
}
vec4 c = vColor * toLinear(texture(tex, uv));
fragColor = c;
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("particles_vert.glsl",R"(#version 330
in vec3 position;
in float particleSize;
in vec4 uv;
in vec4 vertex_color;
out mat3 vUVMat;
out vec4 vColor;
out vec3 uvSize;
#pragma include "global_uniforms_incl.glsl"
mat3 translate(vec2 p){
return mat3(1.0,0.0,0.0,0.0,1.0,0.0,p.x,p.y,1.0);
}
mat3 rotate(float rad){
float s = sin(rad);
float c = cos(rad);
return mat3(c,s,0.0,-s,c,0.0,0.0,0.0,1.0);
}
mat3 scale(float s){
return mat3(s,0.0,0.0,0.0,s,0.0,0.0,0.0,1.0);
}
void main(void) {
vec4 pos = vec4( position, 1.0);
vec4 eyeSpacePos = g_view * g_model * pos;
gl_Position = g_projection * eyeSpacePos;
if (g_projection[2][3] != 0.0){ // if perspective projection
gl_PointSize = (g_viewport.y / 600.0) * particleSize * 1.0 / -eyeSpacePos.z;
} else {
gl_PointSize = particleSize*(g_viewport.y / 600.0);
}
vUVMat = translate(uv.xy)*scale(uv.z) * translate(vec2(0.5,0.5))*rotate(uv.w) * translate(vec2(-0.5,-0.5));
vColor = vertex_color;
uvSize = uv.xyz;
})"),
std::make_pair<std::string,std::string>("sprite_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec2 vUV;
in vec4 vColor;
uniform sampler2D tex;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = vColor * toLinear(texture(tex, vUV));
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("sprite_vert.glsl",R"(#version 330
in vec3 position;
in vec4 uv;
in vec4 vertex_color;
out vec2 vUV;
out vec4 vColor;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
gl_Position = g_projection * g_view * g_model * vec4(position,1.0);
vUV = uv.xy;
vColor = vertex_color;
})"),
std::make_pair<std::string,std::string>("standard_pbr_frag.glsl",R"(#version 330
#extension GL_EXT_shader_texture_lod: enable
#extension GL_OES_standard_derivatives : enable
out vec4 fragColor;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in mat3 vTBN;
#else
in vec3 vNormal;
#endif
in vec2 vUV;
in vec3 vWsPos;
uniform vec4 color;
uniform vec4 metallicRoughness;
uniform sampler2D tex;
#ifdef S_METALROUGHNESSMAP
uniform sampler2D mrTex;
#endif
#ifdef S_NORMALMAP
uniform sampler2D normalTex;
uniform float normalScale;
#endif
#ifdef S_EMISSIVEMAP
uniform sampler2D emissiveTex;
uniform vec4 emissiveFactor;
#endif
#ifdef S_OCCLUSIONMAP
uniform sampler2D occlusionTex;
uniform float occlusionStrength;
#endif
#ifdef S_VERTEX_COLOR
in vec4 vColor;
#endif
#pragma include "global_uniforms_incl.glsl"
#pragma include "normalmap_incl.glsl"
#pragma include "light_incl.glsl"
#pragma include "sre_utils_incl.glsl"
// Encapsulate the various inputs used by the various functions in the shading equation
// We store values in this struct to simplify the integration of alternative implementations
// of the shading terms, outlined in the Readme.MD Appendix.
struct PBRInfo
{
float NdotL; // cos angle between normal and light direction
float NdotV; // cos angle between normal and view direction
float NdotH; // cos angle between normal and half vector
float LdotH; // cos angle between light direction and half vector
float VdotH; // cos angle between view direction and half vector
float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)
float metalness; // metallic value at the surface
vec3 reflectance0; // full reflectance color (normal incidence angle)
vec3 reflectance90; // reflectance color at grazing angle
float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])
vec3 diffuseColor; // color contribution from diffuse lighting
vec3 specularColor; // color contribution from specular lighting
};
const float M_PI = 3.141592653589793;
const float c_MinRoughness = 0.04;
// The following equation models the Fresnel reflectance term of the spec equation (aka F())
// Implementation of fresnel from [4], Equation 15
vec3 specularReflection(PBRInfo pbrInputs)
{
return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
}
// Basic Lambertian diffuse
// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
// See also [1], Equation 1
vec3 diffuse(PBRInfo pbrInputs)
{
return pbrInputs.diffuseColor / M_PI;
}
// This calculates the specular geometric attenuation (aka G()),
// where rougher material will reflect less light back to the viewer.
// This implementation is based on [1] Equation 4, and we adopt their modifications to
// alphaRoughness as input as originally proposed in [2].
float geometricOcclusion(PBRInfo pbrInputs)
{
float NdotL = pbrInputs.NdotL;
float NdotV = pbrInputs.NdotV;
float r = pbrInputs.alphaRoughness;
float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
return attenuationL * attenuationV;
}
// The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D())
// Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
// Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3.
float microfacetDistribution(PBRInfo pbrInputs)
{
float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;
return roughnessSq / (M_PI * f * f);
}
void main(void)
{
float perceptualRoughness = metallicRoughness.y;
float metallic = metallicRoughness.x;
#ifdef S_METALROUGHNESSMAP
// Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
// This layout intentionally reserves the 'r' channel for (optional) occlusion map data
vec4 mrSample = texture(mrTex, vUV);
perceptualRoughness = mrSample.g * perceptualRoughness;
metallic = mrSample.b * metallic;
#endif
perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
metallic = clamp(metallic, 0.0, 1.0);
// Roughness is authored as perceptual roughness; as is convention,
// convert to material roughness by squaring the perceptual roughness [2].
float alphaRoughness = perceptualRoughness * perceptualRoughness;
#ifndef S_NO_BASECOLORMAP
vec4 baseColor = toLinear(texture(tex, vUV)) * color;
#else
vec4 baseColor = color;
#endif
#ifdef S_VERTEX_COLOR
baseColor = baseColor * vColor;
#endif
vec3 f0 = vec3(0.04);
vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
diffuseColor *= 1.0 - metallic;
vec3 specularColor = mix(f0, baseColor.rgb, metallic);
// Compute reflectance.
float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
// For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect.
// For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflectance to 0%.
float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
vec3 specularEnvironmentR0 = specularColor.rgb;
vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
vec3 color = baseColor.rgb * g_ambientLight.rgb; // non pbr
vec3 n = getNormal(); // Normal at surface point
vec3 v = normalize(g_cameraPos.xyz - vWsPos.xyz); // Vector from surface point to camera
for (int i=0;i<SI_LIGHTS;i++) {
float attenuation = 0.0;
vec3 l = vec3(0.0,0.0,0.0);
lightDirectionAndAttenuation(g_lightPosType[i], g_lightColorRange[i].w, vWsPos, l, attenuation);
if (attenuation <= 0.0){
continue;
}
vec3 h = normalize(l+v); // Half vector between both l and v
vec3 reflection = -normalize(reflect(v, n));
float NdotL = clamp(dot(n, l), 0.0001, 1.0);
float NdotV = abs(dot(n, v)) + 0.0001;
float NdotH = clamp(dot(n, h), 0.0, 1.0);
float LdotH = clamp(dot(l, h), 0.0, 1.0);
float VdotH = clamp(dot(v, h), 0.0, 1.0);
PBRInfo pbrInputs = PBRInfo(
NdotL,
NdotV,
NdotH,
LdotH,
VdotH,
perceptualRoughness,
metallic,
specularEnvironmentR0,
specularEnvironmentR90,
alphaRoughness,
diffuseColor,
specularColor
);
// Calculate the shading terms for the microfacet specular shading model
vec3 F = specularReflection(pbrInputs);
float G = geometricOcclusion(pbrInputs);
float D = microfacetDistribution(pbrInputs);
// Calculation of analytical lighting contribution
vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);
color += attenuation * NdotL * g_lightColorRange[i].xyz * (diffuseContrib + specContrib);
}
// Apply optional PBR terms for additional (optional) shading
#ifdef S_OCCLUSIONMAP
float ao = texture(occlusionTex, vUV).r;
color = mix(color, color * ao, occlusionStrength);
#endif
#ifdef S_EMISSIVEMAP
vec3 emissive = toLinear(texture(emissiveTex, vUV)).rgb * emissiveFactor.xyz;
color += emissive;
#endif
fragColor = toOutput(color,baseColor.a);
})"),
std::make_pair<std::string,std::string>("standard_pbr_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
in vec4 uv;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in vec4 tangent;
out mat3 vTBN;
#else
out vec3 vNormal;
#endif
#ifdef S_VERTEX_COLOR
in vec4 vertex_color;
out vec4 vColor;
#endif
out vec2 vUV;
out vec3 vWsPos;
#pragma include "global_uniforms_incl.glsl"
#pragma include "normalmap_incl.glsl"
void main(void) {
vec4 wsPos = g_model * vec4(position,1.0);
vWsPos = wsPos.xyz;
gl_Position = g_projection * g_view * wsPos;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
vTBN = computeTBN(g_model_it, normal, tangent);
#else
vNormal = normalize(g_model_it * normal);
#endif
vUV = uv.xy;
#ifdef S_VERTEX_COLOR
vColor = vertex_color;
#endif
})"),
std::make_pair<std::string,std::string>("standard_blinn_phong_frag.glsl",R"(#version 330
out vec4 fragColor;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in mat3 vTBN;
#else
in vec3 vNormal;
#endif
in vec2 vUV;
in vec3 vWsPos;
#ifdef S_NORMALMAP
uniform sampler2D normalTex;
uniform float normalScale;
#endif
#ifdef S_VERTEX_COLOR
in vec4 vColor;
#endif
uniform vec4 color;
uniform sampler2D tex;
#pragma include "global_uniforms_incl.glsl"
#pragma include "light_incl.glsl"
#pragma include "normalmap_incl.glsl"
#pragma include "sre_utils_incl.glsl"
void main()
{
vec4 c = color * toLinear(texture(tex, vUV));
#ifdef S_VERTEX_COLOR
c = c * vColor;
#endif
vec3 normal = getNormal();
vec3 specularLight = vec3(0.0,0.0,0.0);
vec3 l = computeLightBlinnPhong(vWsPos, g_cameraPos.xyz, normal, specularLight);
fragColor = c * vec4(l, 1.0) + vec4(specularLight,0);
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("standard_blinn_phong_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
in vec4 uv;
out vec2 vUV;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in vec4 tangent;
out mat3 vTBN;
#else
out vec3 vNormal;
#endif
out vec3 vWsPos;
#ifdef S_VERTEX_COLOR
in vec4 vertex_color;
out vec4 vColor;
#endif
#pragma include "global_uniforms_incl.glsl"
#pragma include "normalmap_incl.glsl"
void main(void) {
vec4 wsPos = g_model * vec4(position,1.0);
gl_Position = g_projection * g_view * wsPos;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
vTBN = computeTBN(g_model_it, normal, tangent);
#else
vNormal = normalize(g_model_it * normal);
#endif
vUV = uv.xy;
vWsPos = wsPos.xyz;
#ifdef S_VERTEX_COLOR
vColor = vertex_color;
#endif
})"),
std::make_pair<std::string,std::string>("standard_phong_frag.glsl",R"(#version 330
out vec4 fragColor;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in mat3 vTBN;
#else
in vec3 vNormal;
#endif
in vec2 vUV;
in vec3 vWsPos;
#ifdef S_NORMALMAP
uniform sampler2D normalTex;
uniform float normalScale;
#endif
#ifdef S_VERTEX_COLOR
in vec4 vColor;
#endif
uniform vec4 color;
uniform sampler2D tex;
#pragma include "global_uniforms_incl.glsl"
#pragma include "light_incl.glsl"
#pragma include "normalmap_incl.glsl"
#pragma include "sre_utils_incl.glsl"
void main()
{
vec4 c = color * toLinear(texture(tex, vUV));
#ifdef S_VERTEX_COLOR
c = c * vColor;
#endif
vec3 normal = getNormal();
vec3 specularLight = vec3(0.0,0.0,0.0);
vec3 l = computeLightPhong(vWsPos, g_cameraPos.xyz, normal, specularLight);
fragColor = c * vec4(l, 1.0) + vec4(specularLight,0);
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("standard_phong_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
in vec4 uv;
out vec2 vUV;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in vec4 tangent;
out mat3 vTBN;
#else
out vec3 vNormal;
#endif
out vec3 vWsPos;
#ifdef S_VERTEX_COLOR
in vec4 vertex_color;
out vec4 vColor;
#endif
#pragma include "global_uniforms_incl.glsl"
#pragma include "normalmap_incl.glsl"
void main(void) {
vec4 wsPos = g_model * vec4(position,1.0);
gl_Position = g_projection * g_view * wsPos;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
vTBN = computeTBN(g_model_it, normal, tangent);
#else
vNormal = normalize(g_model_it * normal);
#endif
vUV = uv.xy;
vWsPos = wsPos.xyz;
#ifdef S_VERTEX_COLOR
vColor = vertex_color;
#endif
})"),
std::make_pair<std::string,std::string>("blit_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec2 vUV;
uniform sampler2D tex;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = toLinear(texture(tex, vUV));
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("blit_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
in vec4 uv;
out vec2 vUV;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
gl_Position = g_model * vec4(position,1.0);
vUV = uv.xy;
})"),
std::make_pair<std::string,std::string>("unlit_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec2 vUV;
#ifdef S_VERTEX_COLOR
in vec4 vColor;
#endif
uniform vec4 color;
uniform sampler2D tex;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = color * toLinear(texture(tex, vUV));
#ifdef S_VERTEX_COLOR
fragColor = fragColor * vColor;
#endif
//fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("unlit_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
#ifdef S_VERTEX_COLOR
in vec4 vertex_color;
out vec4 vColor;
#endif
in vec4 uv;
out vec2 vUV;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
gl_Position = g_projection * g_view * g_model * vec4(position,1.0);
vUV = uv.xy;
#ifdef S_VERTEX_COLOR
vColor = vertex_color;
#endif
})"),
std::make_pair<std::string,std::string>("debug_tangent_frag.glsl",R"(#version 330
out vec4 fragColor;
in vec3 vTangent;
#pragma include "sre_utils_incl.glsl"
void main(void)
{
fragColor = vec4(vTangent*0.5+0.5,1.0);
fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("debug_tangent_vert.glsl",R"(#version 330
in vec3 position;
in vec4 tangent;
out vec3 vTangent;
#pragma include "global_uniforms_incl.glsl"
void main(void) {
gl_Position = g_projection * g_view * g_model * vec4(position,1.0);
vTangent = tangent.xyz * tangent.w;
})"),
std::make_pair<std::string,std::string>("normalmap_incl.glsl",R"(#ifdef SI_VERTEX
mat3 computeTBN(mat3 g_model_it, vec3 normal, vec4 tangent){
vec3 wsNormal = normalize(g_model_it * normal);
vec3 wsTangent = normalize(g_model_it * tangent.xyz);
vec3 wsBitangent = cross(wsNormal, wsTangent) * tangent.w;
return mat3(wsTangent, wsBitangent, wsNormal);
}
#endif
#ifdef SI_FRAGMENT
// Find the normal for this fragment, pulling either from a predefined normal map
// or from the interpolated mesh normal and tangent attributes.
vec3 getNormal()
{
#ifdef S_NORMALMAP
// Retrieve the tangent space matrix
#ifndef S_TANGENTS
vec3 pos_dx = dFdx(vWsPos);
vec3 pos_dy = dFdy(vWsPos);
vec3 tex_dx = dFdx(vec3(vUV, 0.0));
vec3 tex_dy = dFdy(vec3(vUV, 0.0));
vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
vec3 ng = normalize(vNormal);
t = normalize(t - ng * dot(ng, t));
vec3 b = normalize(cross(ng, t));
mat3 tbn = mat3(t, b, ng);
#else // S_TANGENTS
mat3 tbn = vTBN;
#endif
vec3 n = texture(normalTex, vUV).rgb;
n = normalize(tbn * ((2.0 * n - 1.0) * vec3(normalScale, normalScale, 1.0)));
#else
vec3 n = normalize(vNormal);
#endif
return n;
}
#endif)"),
std::make_pair<std::string,std::string>("global_uniforms_incl.glsl",R"(// Per render-pass uniforms
#if __VERSION__ > 100
layout(std140) uniform g_global_uniforms {
#endif
#ifdef GL_ES
#ifdef GL_FRAGMENT_PRECISION_HIGH
uniform highp mat4 g_view;
uniform highp mat4 g_projection;
uniform highp vec4 g_viewport;
uniform highp vec4 g_cameraPos;
uniform highp vec4 g_ambientLight;
uniform highp vec4 g_lightColorRange[SI_LIGHTS];
uniform highp vec4 g_lightPosType[SI_LIGHTS];
#else
uniform mediump mat4 g_view;
uniform mediump mat4 g_projection;
uniform mediump vec4 g_viewport;
uniform mediump vec4 g_cameraPos;
uniform mediump vec4 g_ambientLight;
uniform mediump vec4 g_lightColorRange[SI_LIGHTS];
uniform mediump vec4 g_lightPosType[SI_LIGHTS];
#endif
#else
uniform mat4 g_view;
uniform mat4 g_projection;
uniform vec4 g_viewport;
uniform vec4 g_cameraPos;
uniform vec4 g_ambientLight;
uniform vec4 g_lightColorRange[SI_LIGHTS];
uniform vec4 g_lightPosType[SI_LIGHTS];
#endif
#if __VERSION__ > 100
};
#endif
#ifdef GL_ES
// Per draw call uniforms
#ifdef GL_FRAGMENT_PRECISION_HIGH
uniform highp mat4 g_model;
uniform highp mat3 g_model_it;
uniform highp mat3 g_model_view_it;
#else
uniform mediump mat4 g_model;
uniform mediump mat3 g_model_it;
uniform mediump mat3 g_model_view_it;
#endif
#else
uniform mat4 g_model;
uniform mat3 g_model_it;
uniform mat3 g_model_view_it;
#endif)"),
std::make_pair<std::string,std::string>("standard_blinn_frag.glsl",R"(#version 330
out vec4 fragColor;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in mat3 vTBN;
#else
in vec3 vNormal;
#endif
in vec2 vUV;
in vec3 vWsPos;
#ifdef S_NORMALMAP
uniform sampler2D normalTex;
uniform float normalScale;
#endif
#ifdef S_VERTEX_COLOR
in vec4 vColor;
#endif
uniform vec4 color;
uniform sampler2D tex;
#pragma include "global_uniforms_incl.glsl"
#pragma include "light_incl.glsl"
#pragma include "normalmap_incl.glsl"
#pragma include "sre_utils_incl.glsl"
void main()
{
vec4 c = color * toLinear(texture(tex, vUV));
#ifdef S_VERTEX_COLOR
c = c * vColor;
#endif
vec3 normal = getNormal();
vec3 l = computeLightBlinn(vWsPos, g_cameraPos.xyz, normal);
fragColor = c * vec4(l, 1.0);
//fragColor = toOutput(fragColor);
})"),
std::make_pair<std::string,std::string>("standard_blinn_vert.glsl",R"(#version 330
in vec3 position;
in vec3 normal;
in vec4 uv;
out vec2 vUV;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
in vec4 tangent;
out mat3 vTBN;
#else
out vec3 vNormal;
#endif
out vec3 vWsPos;
#ifdef S_VERTEX_COLOR
in vec4 vertex_color;
out vec4 vColor;
#endif
#pragma include "global_uniforms_incl.glsl"
#pragma include "normalmap_incl.glsl"
void main(void) {
vec4 wsPos = g_model * vec4(position,1.0);
gl_Position = g_projection * g_view * wsPos;
#if defined(S_TANGENTS) && defined(S_NORMALMAP)
vTBN = computeTBN(g_model_it, normal, tangent);
#else
vNormal = normalize(g_model_it * normal);
#endif
vUV = uv.xy;
vWsPos = wsPos.xyz;
#ifdef S_VERTEX_COLOR
vColor = vertex_color;
#endif
})"),
};
| 30.427673
| 1,608
| 0.701805
|
KasperHdL
|
27fb453dc6c7a40951d513a131c0e349d4c57920
| 1,040
|
hpp
|
C++
|
Pi/server.hpp
|
FundCompXbee/XBeeMessenger
|
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
|
[
"MIT"
] | 1
|
2016-04-29T22:30:58.000Z
|
2016-04-29T22:30:58.000Z
|
Pi/server.hpp
|
FundCompXbee/XBeeMessenger
|
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
|
[
"MIT"
] | null | null | null |
Pi/server.hpp
|
FundCompXbee/XBeeMessenger
|
f3210077cb82e1597980b33bc6e2f8f9cf7bc042
|
[
"MIT"
] | null | null | null |
// Team: XBeeMessenger
// Course: Fundamentals of Computing II
// Assignment: Final Project
// Purpose: Interface for a server which receives requests, handles
// requests, and broadcasts responses
#ifndef SERVER
#define SERVER
#include <string>
#include <unistd.h>
#include <cstdlib>
#include "IRCCommandHandler.hpp"
#include "serial.hpp"
#include "envelope.hpp"
class Server {
public:
Server(int baud); // contructor, initializes serial and gets hostname
void run(); // Sets the server into action
private:
static const char delimiter; // signals the end of a serial transmission
std::string name; // The server's name. By default this is retrieved from the
// server's hostname
IRCCommandHandler IRCHandler; // Handles commands
Serial serial; // Handles data transmission
std::string retrieveSerialData(); // retrieves raw JSON-string from serial
void broadcastSerialData(std::string broadcastMessage); // broadcasts message
std::string validateRequest(Envelope& request);
};
#endif
| 28.888889
| 79
| 0.735577
|
FundCompXbee
|
7e0119a4fd94dd780940a2fc66941202f79fc7b6
| 2,088
|
cpp
|
C++
|
libs/libvtrutil/src/vtr_list.cpp
|
rding2454/IndeStudy
|
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
|
[
"MIT"
] | null | null | null |
libs/libvtrutil/src/vtr_list.cpp
|
rding2454/IndeStudy
|
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
|
[
"MIT"
] | null | null | null |
libs/libvtrutil/src/vtr_list.cpp
|
rding2454/IndeStudy
|
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
|
[
"MIT"
] | null | null | null |
#include <cstdlib>
#include "vtr_list.h"
#include "vtr_memory.h"
namespace vtr {
t_linked_vptr *insert_in_vptr_list(t_linked_vptr *head, void *vptr_to_add) {
/* Inserts a new element at the head of a linked list of void pointers. *
* Returns the new head of the list. */
t_linked_vptr *linked_vptr;
linked_vptr = (t_linked_vptr *) vtr::malloc(sizeof(t_linked_vptr));
linked_vptr->data_vptr = vptr_to_add;
linked_vptr->next = head;
return (linked_vptr); /* New head of the list */
}
/* Deletes the element at the head of a linked list of void pointers. *
* Returns the new head of the list. */
t_linked_vptr *delete_in_vptr_list(t_linked_vptr *head) {
t_linked_vptr *linked_vptr;
if (head == NULL )
return NULL ;
linked_vptr = head->next;
free(head);
return linked_vptr; /* New head of the list */
}
t_linked_int *insert_in_int_list(t_linked_int * head, int data,
t_linked_int ** free_list_head_ptr) {
/* Inserts a new element at the head of a linked list of integers. Returns *
* the new head of the list. One argument is the address of the head of *
* a list of free ilist elements. If there are any elements on this free *
* list, the new element is taken from it. Otherwise a new one is malloced. */
t_linked_int *linked_int;
if (*free_list_head_ptr != NULL ) {
linked_int = *free_list_head_ptr;
*free_list_head_ptr = linked_int->next;
} else {
linked_int = (t_linked_int *) vtr::malloc(sizeof(t_linked_int));
}
linked_int->data = data;
linked_int->next = head;
return (linked_int);
}
void free_int_list(t_linked_int ** int_list_head_ptr) {
/* This routine truly frees (calls free) all the integer list elements *
* on the linked list pointed to by *head, and sets head = NULL. */
t_linked_int *linked_int, *next_linked_int;
linked_int = *int_list_head_ptr;
while (linked_int != NULL ) {
next_linked_int = linked_int->next;
free(linked_int);
linked_int = next_linked_int;
}
*int_list_head_ptr = NULL;
}
} //namespace
| 27.84
| 80
| 0.688218
|
rding2454
|
7e02f72ff574211551d229e1e0fc74712916682b
| 4,370
|
hxx
|
C++
|
opencascade/HLRBRep_EdgeData.hxx
|
valgur/OCP
|
2f7d9da73a08e4ffe80883614aedacb27351134f
|
[
"Apache-2.0"
] | 117
|
2020-03-07T12:07:05.000Z
|
2022-03-27T07:35:22.000Z
|
opencascade/HLRBRep_EdgeData.hxx
|
CadQuery/cpp-py-bindgen
|
66e7376d3a27444393fc99acbdbef40bbc7031ae
|
[
"Apache-2.0"
] | 66
|
2019-12-20T16:07:36.000Z
|
2022-03-15T21:56:10.000Z
|
opencascade/HLRBRep_EdgeData.hxx
|
CadQuery/cpp-py-bindgen
|
66e7376d3a27444393fc99acbdbef40bbc7031ae
|
[
"Apache-2.0"
] | 76
|
2020-03-16T01:47:46.000Z
|
2022-03-21T16:37:07.000Z
|
// Created on: 1997-04-17
// Created by: Christophe MARION
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _HLRBRep_EdgeData_HeaderFile
#define _HLRBRep_EdgeData_HeaderFile
#include <HLRAlgo_WiresBlock.hxx>
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Integer.hxx>
#include <HLRAlgo_EdgeStatus.hxx>
#include <HLRBRep_Curve.hxx>
#include <Standard_ShortReal.hxx>
#include <Standard_Real.hxx>
class TopoDS_Edge;
// resolve name collisions with X11 headers
#ifdef Status
#undef Status
#endif
class HLRBRep_EdgeData
{
public:
DEFINE_STANDARD_ALLOC
HLRBRep_EdgeData() :
myFlags(0),
myHideCount(0)
{
Selected(Standard_True);
}
Standard_EXPORT void Set (const Standard_Boolean Reg1, const Standard_Boolean RegN, const TopoDS_Edge& EG, const Standard_Integer V1, const Standard_Integer V2, const Standard_Boolean Out1, const Standard_Boolean Out2, const Standard_Boolean Cut1, const Standard_Boolean Cut2, const Standard_Real Start, const Standard_ShortReal TolStart, const Standard_Real End, const Standard_ShortReal TolEnd);
Standard_Boolean Selected() const;
void Selected (const Standard_Boolean B);
Standard_Boolean Rg1Line() const;
void Rg1Line (const Standard_Boolean B);
Standard_Boolean RgNLine() const;
void RgNLine (const Standard_Boolean B);
Standard_Boolean Vertical() const;
void Vertical (const Standard_Boolean B);
Standard_Boolean Simple() const;
void Simple (const Standard_Boolean B);
Standard_Boolean OutLVSta() const;
void OutLVSta (const Standard_Boolean B);
Standard_Boolean OutLVEnd() const;
void OutLVEnd (const Standard_Boolean B);
Standard_Boolean CutAtSta() const;
void CutAtSta (const Standard_Boolean B);
Standard_Boolean CutAtEnd() const;
void CutAtEnd (const Standard_Boolean B);
Standard_Boolean VerAtSta() const;
void VerAtSta (const Standard_Boolean B);
Standard_Boolean VerAtEnd() const;
void VerAtEnd (const Standard_Boolean B);
Standard_Boolean AutoIntersectionDone() const;
void AutoIntersectionDone (const Standard_Boolean B);
Standard_Boolean Used() const;
void Used (const Standard_Boolean B);
Standard_Integer HideCount() const;
void HideCount (const Standard_Integer I);
Standard_Integer VSta() const;
void VSta (const Standard_Integer I);
Standard_Integer VEnd() const;
void VEnd (const Standard_Integer I);
void UpdateMinMax (const HLRAlgo_EdgesBlock::MinMaxIndices& theTotMinMax)
{
myMinMax = theTotMinMax;
}
HLRAlgo_EdgesBlock::MinMaxIndices& MinMax()
{
return myMinMax;
}
HLRAlgo_EdgeStatus& Status();
HLRBRep_Curve& ChangeGeometry();
const HLRBRep_Curve& Geometry() const;
HLRBRep_Curve* Curve()
{
return &myGeometry;
}
Standard_ShortReal Tolerance() const;
protected:
enum EMaskFlags
{
EMaskSelected = 1,
EMaskUsed = 2,
EMaskRg1Line = 4,
EMaskVertical = 8,
EMaskSimple = 16,
EMaskOutLVSta = 32,
EMaskOutLVEnd = 64,
EMaskIntDone = 128,
EMaskCutAtSta = 256,
EMaskCutAtEnd = 512,
EMaskVerAtSta = 1024,
EMaskVerAtEnd = 2048,
EMaskRgNLine = 4096
};
private:
Standard_Integer myFlags;
Standard_Integer myHideCount;
Standard_Integer myVSta;
Standard_Integer myVEnd;
HLRAlgo_EdgesBlock::MinMaxIndices myMinMax;
HLRAlgo_EdgeStatus myStatus;
HLRBRep_Curve myGeometry;
Standard_ShortReal myTolerance;
};
#include <HLRBRep_EdgeData.lxx>
#endif // _HLRBRep_EdgeData_HeaderFile
| 24.829545
| 399
| 0.731579
|
valgur
|
7e03a73e36dc22f3de69ca364f53f10da5f6634b
| 769
|
cpp
|
C++
|
dbms/src/Parsers/ASTTTLElement.cpp
|
sunadm/ClickHouse
|
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
|
[
"Apache-2.0"
] | 7
|
2021-02-26T04:34:22.000Z
|
2021-12-31T08:15:47.000Z
|
dbms/src/Parsers/ASTTTLElement.cpp
|
sunadm/ClickHouse
|
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
|
[
"Apache-2.0"
] | 1
|
2019-10-13T16:06:13.000Z
|
2019-10-13T16:06:13.000Z
|
dbms/src/Parsers/ASTTTLElement.cpp
|
sunadm/ClickHouse
|
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
|
[
"Apache-2.0"
] | 3
|
2020-02-24T12:57:54.000Z
|
2021-10-04T13:29:00.000Z
|
#include <Columns/Collator.h>
#include <Common/quoteString.h>
#include <Parsers/ASTTTLElement.h>
namespace DB
{
void ASTTTLElement::formatImpl(const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const
{
children.front()->formatImpl(settings, state, frame);
if (destination_type == PartDestinationType::DISK)
{
settings.ostr << " TO DISK " << quoteString(destination_name);
}
else if (destination_type == PartDestinationType::VOLUME)
{
settings.ostr << " TO VOLUME " << quoteString(destination_name);
}
else if (destination_type == PartDestinationType::DELETE)
{
/// It would be better to output "DELETE" here but that will break compatibility with earlier versions.
}
}
}
| 27.464286
| 116
| 0.694408
|
sunadm
|
7e042ee4252496e14df8e3c73c6b1adecbcd3299
| 1,248
|
cc
|
C++
|
StatModules/src/ToyMCLikelihoodEvaluator.cc
|
GooStats/GooStats
|
5a8bc35736eb390d658c790fa0026b576898a462
|
[
"MIT"
] | 3
|
2020-01-28T21:51:46.000Z
|
2021-09-06T18:43:00.000Z
|
StatModules/src/ToyMCLikelihoodEvaluator.cc
|
GooStats/GooStats
|
5a8bc35736eb390d658c790fa0026b576898a462
|
[
"MIT"
] | 12
|
2019-08-09T08:58:49.000Z
|
2022-03-16T04:00:11.000Z
|
StatModules/src/ToyMCLikelihoodEvaluator.cc
|
GooStats/GooStats
|
5a8bc35736eb390d658c790fa0026b576898a462
|
[
"MIT"
] | 3
|
2018-04-12T11:53:55.000Z
|
2022-03-17T13:06:06.000Z
|
/*****************************************************************************/
// Author: Xuefeng Ding <xuefeng.ding.physics@gmail.com>
// Insitute: Gran Sasso Science Institute, L'Aquila, 67100, Italy
// Date: 2018 April 7th
// Version: v1.0
// Description: GooStats, a statistical analysis toolkit that runs on GPU.
//
// All rights reserved. 2018 copyrighted.
/*****************************************************************************/
#include "ToyMCLikelihoodEvaluator.h"
#include "InputManager.h"
#include "SumLikelihoodPdf.h"
#include "GSFitManager.h"
void ToyMCLikelihoodEvaluator::get_p_value(GSFitManager *gsFitManager,InputManager *manager,double LL,double &p,double &perr,FitControl *fit) {
const OptionManager *gOp = manager->GlobalOption();
int N = gOp->has("toyMC_size")?gOp->get<double>("toyMC_size"):100;
if(N==0) return;
SumLikelihoodPdf *totalPdf = manager->getTotalPdf();
totalPdf->setFitControl(fit);
totalPdf->copyParams();
totalPdf->cache();
LLs.clear();
int n = 0;
for(int i = 0;i<N;++i) {
manager->fillRandomData();
LLs.push_back(totalPdf->calculateNLL());
if(LLs.back()>LL) ++n;
}
totalPdf->restore();
gsFitManager->restoreFitControl();
p = n*1./N;
perr = sqrt(p*(1-p)/N);
}
| 36.705882
| 143
| 0.614583
|
GooStats
|
7e06656f021627fc251d7c71b350492b3a325178
| 7,917
|
cpp
|
C++
|
test/stkdatatest/ManyRecords.cpp
|
Aekras1a/YaizuComLib
|
470d33376add0d448002221b75f7efd40eec506f
|
[
"MIT"
] | 1
|
2022-01-30T20:17:16.000Z
|
2022-01-30T20:17:16.000Z
|
test/stkdatatest/ManyRecords.cpp
|
Aekras1a/YaizuComLib
|
470d33376add0d448002221b75f7efd40eec506f
|
[
"MIT"
] | null | null | null |
test/stkdatatest/ManyRecords.cpp
|
Aekras1a/YaizuComLib
|
470d33376add0d448002221b75f7efd40eec506f
|
[
"MIT"
] | null | null | null |
#include "../../src/stkpl/StkPl.h"
#include "../../src/stkdata/stkdata.h"
#include "../../src/stkdata/stkdataapi.h"
/*
ManyRecords
・WStr(256)×32カラム×16383レコードのテーブルを作成することができる。InsertRecordを16383回繰り返しレコードを追加できる
・既存の[焼津沼津辰口町和泉町中田北白楽]テーブルから10レコードを削除できる。条件として連結されたレコードを指定する
・存在しないカラム名を指定してZaSortRecordを実行したとき,-1が返却される。
*/
int ManyRecords()
{
{
StkPlPrintf("Table can be created defined as WStr(256) x 32 columns×16383 records. Records can be inserted 16383 times using InsertRecord.");
ColumnDefWStr* ColDef[32];
TableDef LargeTable(L"焼津沼津辰口町和泉町中田北白楽", 16383);
for (int i = 0; i < 32; i++) {
wchar_t ColName[16];
StkPlSwPrintf(ColName, 16, L"東西南北老若男女焼肉定食愛%d", i);
ColDef[i] = new ColumnDefWStr(ColName, 256);
LargeTable.AddColumnDef(ColDef[i]);
}
if (CreateTable(&LargeTable) != 0) {
StkPlPrintf("...[NG]\n");
return -1;
}
for (int i = 0; i < 32; i++) {
delete ColDef[i];
}
for (int k = 0; k < 16383; k++) {
RecordData* RecDat;
ColumnData* ColDat[32];
for (int i = 0; i < 32; i++) {
wchar_t ColName[16];
wchar_t Val[256] = L"";
StkPlSwPrintf(ColName, 16, L"東西南北老若男女焼肉定食愛%d", i);
StkPlSwPrintf(Val, 256, L"%d %d :12345", k, i);
for (int j = 0; j < 24; j++) {
StkPlWcsCat(Val, 256, L"一二三四五六七八九十");
}
ColDat[i] = new ColumnDataWStr(ColName, Val);
}
RecDat = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 32);
LockTable(L"焼津沼津辰口町和泉町中田北白楽", 2);
if (InsertRecord(RecDat) != 0) {
StkPlPrintf("...[NG]\n");
return -1;
}
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
delete RecDat;
}
StkPlPrintf("...[OK]\n");
}
{
StkPlPrintf("Records can be acquired from exising table.");
LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE);
RecordData* RecDat = GetRecord(L"焼津沼津辰口町和泉町中田北白楽");
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
RecordData* CurRecDat = RecDat;
StkPlPrintf("Column information can be acquired with column name specification.");
do {
ColumnDataWStr* ColDat0 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛0");
if (ColDat0 == NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
wchar_t* ColDat0Value = ColDat0->GetValue();
if (ColDat0Value == NULL || StkPlWcsLen(ColDat0Value) == 0) {
StkPlPrintf("...[NG]\n");
return -1;
}
ColumnDataWStr* ColDat31 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛31");
if (ColDat31 == NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
wchar_t* ColDat31Value = ColDat0->GetValue();
if (ColDat31Value == NULL || StkPlWcsLen(ColDat31Value) == 0) {
StkPlPrintf("...[NG]\n");
return -1;
}
} while (CurRecDat = CurRecDat->GetNextRecord());
StkPlPrintf("...[OK]\n");
delete RecDat;
}
{
StkPlPrintf("Search records from existing table. Search criteria=WStr:multi+CONTAIN");
ColumnData* ColDat[2];
ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :");
ColDat[0]->SetComparisonOperator(COMP_CONTAIN);
ColDat[1] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛3", L"100 3 :");
ColDat[1]->SetComparisonOperator(COMP_CONTAIN);
RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 2);
LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE);
RecordData* RecDatRet = GetRecord(RecDatSch);
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
RecordData* CurRecDat = RecDatRet;
do {
ColumnDataWStr* ColDat2 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛2");
ColumnDataWStr* ColDat3 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛3");
if (ColDat2 == NULL || ColDat3 == NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
wchar_t* ColDat0Value2 = ColDat2->GetValue();
wchar_t* ColDat0Value3 = ColDat3->GetValue();
if (StkPlWcsStr(ColDat0Value2, L"100 2 :") == NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
if (StkPlWcsStr(ColDat0Value3, L"100 3 :") == NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
} while (CurRecDat = CurRecDat->GetNextRecord());
delete RecDatSch;
delete RecDatRet;
StkPlPrintf("...[OK]\n");
}
{
StkPlPrintf("Search records from existing table. Search criteria=WStr:multi+EQUAL(invalid)");
ColumnData* ColDat[1];
ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :");
ColDat[0]->SetComparisonOperator(COMP_EQUAL);
RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 1);
LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE);
RecordData* RecDatRet = GetRecord(RecDatSch);
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
if (RecDatRet != NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
delete RecDatSch;
StkPlPrintf("...[OK]\n");
}
{
StkPlPrintf("Search records from existing table. Search criteria=WStr:multi+NOT CONTAIN");
ColumnData* ColDat[2];
ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :", COMP_NOT_CONTAIN);
ColDat[1] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛3", L"100 3 :", COMP_NOT_CONTAIN);
RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 2);
LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE);
RecordData* RecDatRet = GetRecord(RecDatSch);
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
RecordData* CurRecDat = RecDatRet;
int NumOfDat = 0;
do {
ColumnDataWStr* ColDat2 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛2");
ColumnDataWStr* ColDat3 = (ColumnDataWStr*)CurRecDat->GetColumn(L"東西南北老若男女焼肉定食愛3");
if (ColDat2 == NULL || ColDat3 == NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
wchar_t* ColDat0Value2 = ColDat2->GetValue();
wchar_t* ColDat0Value3 = ColDat3->GetValue();
if (StkPlWcsStr(ColDat0Value2, L"100 2 :") != NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
if (StkPlWcsStr(ColDat0Value3, L"100 3 :") != NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
NumOfDat++;
} while (CurRecDat = CurRecDat->GetNextRecord());
delete RecDatSch;
delete RecDatRet;
StkPlPrintf("...%d[OK]\n", NumOfDat);
}
{
StkPlPrintf("Search records from existing table. Search criteria=WStr:multi(invalid)");
ColumnData* ColDat[2];
ColDat[0] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛2", L"100 2 :", COMP_CONTAIN);
ColDat[1] = new ColumnDataWStr(L"東西南北老若男女焼肉定食愛3", L"100 3 :", COMP_NOT_CONTAIN);
RecordData* RecDatSch = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", ColDat, 2);
LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_SHARE);
RecordData* RecDatRet = GetRecord(RecDatSch);
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
if (RecDatRet != NULL) {
StkPlPrintf("...[NG]\n");
return -1;
}
delete RecDatSch;
StkPlPrintf("...[OK]\n");
}
{
StkPlPrintf("10 records can be acquired from specified table. Connected records are specified.");
RecordData* RecDat;
RecordData* TopRecDat;
RecordData* PrvRecDat;
ColumnData* ColDat;
for (int i = 0; i < 10; i ++) {
wchar_t ColName[16];
wchar_t Val[256] = L"";
StkPlSwPrintf(ColName, 16, L"東西南北老若男女焼肉定食愛%d", 0);
StkPlSwPrintf(Val, 256, L"%d %d :12345", i, 0);
for (int j = 0; j < 24; j++) {
StkPlWcsCat(Val, 256, L"一二三四五六七八九十");
}
ColDat = new ColumnDataWStr(ColName, Val);
RecDat = new RecordData(L"焼津沼津辰口町和泉町中田北白楽", &ColDat, 1);
if (i == 0) {
TopRecDat = RecDat;
}
if (i >= 1) {
PrvRecDat->SetNextRecord(RecDat);
}
PrvRecDat = RecDat;
}
LockTable(L"焼津沼津辰口町和泉町中田北白楽", 2);
DeleteRecord(TopRecDat);
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
delete TopRecDat;
if (GetNumOfRecords(L"焼津沼津辰口町和泉町中田北白楽") != 16373) {
StkPlPrintf("...[NG]\n");
return -1;
}
StkPlPrintf("...[OK]\n");
}
{
StkPlPrintf("-1 is returned if non existing column name is specified to ZaSortRecord.");
LockTable(L"焼津沼津辰口町和泉町中田北白楽", LOCK_EXCLUSIVE);
if (ZaSortRecord(L"焼津沼津辰口町和泉町中田北白楽", L"aaa") != -1) {
StkPlPrintf("...[NG]\n");
return -1;
}
UnlockTable(L"焼津沼津辰口町和泉町中田北白楽");
StkPlPrintf("...[OK]\n");
}
StkPlPrintf("Delete a table which contains large number of records.");
if (DeleteTable(L"焼津沼津辰口町和泉町中田北白楽") != 0) {
StkPlPrintf("...[NG]\n");
return -1;
}
StkPlPrintf("...[OK]\n");
return 0;
}
| 31.795181
| 143
| 0.662372
|
Aekras1a
|
7e0671a6332d41f1426f827a417780c062d6f38d
| 35,068
|
cpp
|
C++
|
earth_enterprise/src/fusion/gst/gstGeometryChecker_unittest.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 2,661
|
2017-03-20T22:12:50.000Z
|
2022-03-30T09:43:19.000Z
|
earth_enterprise/src/fusion/gst/gstGeometryChecker_unittest.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 1,531
|
2017-03-24T17:20:32.000Z
|
2022-03-16T18:11:14.000Z
|
earth_enterprise/src/fusion/gst/gstGeometryChecker_unittest.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 990
|
2017-03-24T11:54:28.000Z
|
2022-03-22T11:51:47.000Z
|
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Unit tests for GeometryChecker functionality.
#include <gtest/gtest.h>
#include <string>
#include "fusion/gst/gstVertex.h"
#include "fusion/gst/gstGeode.h"
#include "fusion/gst/gstMathUtils.h"
#include "fusion/gst/gstGeometryChecker.h"
#include "fusion/gst/gstUnitTestUtils.h"
namespace fusion_gst {
// GeometryChecker test class.
class GeometryCheckerTest : public testing::Test {
protected:
// Utility method for checking the result of
// RemoveCoincidentVertex()-function.
void CheckRemoveCoincidentVertex(const gstGeodeHandle &geodeh,
const gstGeodeHandle &expected_geodeh,
const std::string &message) const;
// Utility method for checking the result of RemoveSpike()-function.
void CheckRemoveSpikes(const gstGeodeHandle &geodeh,
const gstGeodeHandle &expected_geodeh,
const std::string &message) const;
// Utility method for checking the result of
// CheckAndFixCycleOrientation()-function.
void CheckAndFixCycleOrientation(const gstGeodeHandle &geodeh,
const gstGeodeHandle &expected_geodeh,
const std::string &message) const;
private:
GeometryChecker checker_;
};
// Utility method for checking the result of RemoveCoincidentVertex-function.
void GeometryCheckerTest::CheckRemoveCoincidentVertex(
const gstGeodeHandle &geodeh,
const gstGeodeHandle &expected_geodeh,
const std::string &message) const {
gstGeodeHandle gh = geodeh->Duplicate();
checker_.RemoveCoincidentVertices(&gh);
TestUtils::CompareGeodes(gh, expected_geodeh, message);
}
// Utility method for checking the result of RemoveSpikes-function.
void GeometryCheckerTest::CheckRemoveSpikes(
const gstGeodeHandle &geodeh,
const gstGeodeHandle &expected_geodeh,
const std::string &message) const {
gstGeodeHandle gh = geodeh->Duplicate();
checker_.RemoveSpikes(&gh);
TestUtils::CompareGeodes(gh, expected_geodeh, message);
}
// Utility method for checking the result of CheckAndFixCycleOrientation()
// -fucntion.
void GeometryCheckerTest::CheckAndFixCycleOrientation(
const gstGeodeHandle &geodeh,
const gstGeodeHandle &expected_geodeh,
const std::string &message) const {
gstGeodeHandle gh = geodeh->Duplicate();
checker_.CheckAndFixCycleOrientation(&gh);
TestUtils::CompareGeodes(gh, expected_geodeh, message);
}
// Tests RemoveCoincidentVertex-functionality.
TEST_F(GeometryCheckerTest, RemoveCoincidentVertexTest) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(6);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(6);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveCoincidentVertex(
geodeh, exp_geodeh,
"Coincident vertex removing: coincident vertices at the beginning.");
}
{
geode->Clear();
geode->AddPart(6);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(6);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveCoincidentVertex(
geodeh, exp_geodeh,
"Coincident vertex removing: coincident vertices at the end.");
}
{
geode->Clear();
geode->AddPart(8);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(8);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveCoincidentVertex(
geodeh, exp_geodeh,
"Coincident vertex removing: coincident vertices in the middle.");
}
{
geode->Clear();
geode->AddPart(11);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(11);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveCoincidentVertex(
geodeh, exp_geodeh,
"Coincident vertex removing: coincident vertices everewhere.");
}
}
// CheckRemoveSpikesTest1 - generic test 1.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest1) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(7);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.320, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.50, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(7);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.220, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.050, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: generic test 1.");
}
}
// CheckRemoveSpikesTest2 - generic test 2.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest2) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(9);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.320, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.400, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.040, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.50, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(9);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.220, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.350, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.110, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.050, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: generic test 2.");
}
}
// CheckRemoveSpikesTest3 - generic test 3.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest3) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.220, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.220, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.160, 0.160, .0));
exp_geode->AddVertex(gstVertex(0.160, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(7);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.280, 0.280, .0));
geode->AddVertex(gstVertex(0.220, 0.220, .0));
geode->AddVertex(gstVertex(0.040, 0.220, .0));
geode->AddVertex(gstVertex(0.100, 0.220, .0));
geode->AddVertex(gstVertex(0.100, 0.50, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(7);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.180, 0.180, .0));
geode->AddVertex(gstVertex(0.160, 0.160, .0));
geode->AddVertex(gstVertex(0.160, 0.120, .0));
geode->AddVertex(gstVertex(0.180, 0.120, .0));
geode->AddVertex(gstVertex(0.050, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: generic test 3.");
}
}
// CheckRemoveSpikesTest4 - polygon cycles with collinear points.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest4) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.170, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.150, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.180, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.130, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.140, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.170, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.145, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.135, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(7);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.170, 0.100, .0));
geode->AddVertex(gstVertex(0.320, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.150, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.180, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.130, .0));
geode->AddVertex(gstVertex(0.100, 0.050, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddPart(7);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.140, .0));
geode->AddVertex(gstVertex(0.120, 0.220, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.170, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.145, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.135, 0.120, .0));
geode->AddVertex(gstVertex(0.050, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: collinear points test.");
}
}
// CheckRemoveSpikesTest5 - small triangle from real data set.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest5) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
gstVertex pt1 = gstVertex(
khTilespaceBase::Normalize(-90.6035304620),
khTilespaceBase::Normalize(34.9918161022),
.0);
gstVertex pt2 = gstVertex(
khTilespaceBase::Normalize(-90.6035310000),
khTilespaceBase::Normalize(34.9918180000),
.0);
gstVertex pt3 = gstVertex(
khTilespaceBase::Normalize(-90.6035342156),
khTilespaceBase::Normalize(34.9918172140),
.0);
exp_geode->AddPart(4);
exp_geode->AddVertex(pt1);
exp_geode->AddVertex(pt2);
exp_geode->AddVertex(pt3);
exp_geode->AddVertex(pt1);
{
geode->Clear();
geode->AddPart(4);
geode->AddVertex(pt1);
geode->AddVertex(pt2);
geode->AddVertex(pt3);
geode->AddVertex(pt1);
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: small triangle from real data set.");
}
}
// CheckRemoveSpikesTest6 - polygon w/ spike from real data set 1.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest6) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
gstVertex pt1 = gstVertex(
khTilespaceBase::Normalize(106.8182506368),
khTilespaceBase::Normalize(10.6542182242),
.0);
gstVertex pt2 = gstVertex(
khTilespaceBase::Normalize(106.8124851861),
khTilespaceBase::Normalize(10.6542509147),
.0);
gstVertex pt3 = gstVertex(
khTilespaceBase::Normalize(106.8155637637),
khTilespaceBase::Normalize(10.6542318523),
.0);
gstVertex pt4 = gstVertex(
khTilespaceBase::Normalize(106.8159899627),
khTilespaceBase::Normalize(10.6527421661),
.0);
exp_geode->AddPart(5);
exp_geode->AddVertex(pt1);
// exp_geode->AddVertex(pt2); // spike vertex.
exp_geode->AddVertex(pt3);
exp_geode->AddVertex(pt4);
exp_geode->AddVertex(pt1);
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(pt1);
geode->AddVertex(pt2);
geode->AddVertex(pt3);
geode->AddVertex(pt4);
geode->AddVertex(pt1);
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: polygon w/ spike from real data set 1.");
}
}
// CheckRemoveSpikesTest7 - polygon w/ spike from real data set 2.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest7) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
gstVertex pt1 = gstVertex(
khTilespaceBase::Normalize(-8.9993160617),
khTilespaceBase::Normalize(43.2081516536),
.0);
gstVertex pt2 = gstVertex(
khTilespaceBase::Normalize(-8.9994751791),
khTilespaceBase::Normalize(43.2077953989),
.0);
gstVertex pt3 = gstVertex(
khTilespaceBase::Normalize(-8.9994724853),
khTilespaceBase::Normalize(43.2078014303),
.0);
gstVertex pt4 = gstVertex(
khTilespaceBase::Normalize(-8.9993440068),
khTilespaceBase::Normalize(43.2074263067),
.0);
exp_geode->AddPart(5);
exp_geode->AddVertex(pt1);
// exp_geode->AddVertex(pt2); // spike vertex.
exp_geode->AddVertex(pt3);
exp_geode->AddVertex(pt4);
exp_geode->AddVertex(pt1);
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(pt1);
geode->AddVertex(pt2);
geode->AddVertex(pt3);
geode->AddVertex(pt4);
geode->AddVertex(pt1);
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: simple polygon w/ spike from real data set 2.");
}
}
// CheckRemoveSpikesTest8 - collinear vertices at the end of cycle.
TEST_F(GeometryCheckerTest, CheckRemoveSpikesTest8) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
{
geode->Clear();
geode->AddPart(9);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.320, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.100, 0.50, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
CheckRemoveSpikes(
geodeh, exp_geodeh,
"Spikes removing: collinear vertices at the end of cycle 8.");
}
}
// CheckAndFixCycleOrientationTest1 - single-part geode with correct
// orientation - rectangle.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest1) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with correct"
" orientation - rectangle.");
}
}
// CheckAndFixCycleOrientationTest2 - single-part geode with correct
// orientation - obtuse angle is incident to most left-lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest2) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.050, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.050, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with correct"
" orientation and obtuse angle 1.");
}
}
// CheckAndFixCycleOrientationTest3 - single-part geode with correct
// orientation - obtuse angle is incident to most left-lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest3) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.050, .0));
exp_geode->AddVertex(gstVertex(0.220, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.050, 0.200, .0));
exp_geode->AddVertex(gstVertex(0.100, 0.100, .0));
{
geode->Clear();
geode->AddPart(6);
geode->AddVertex(gstVertex(0.100, 0.100, .0));
geode->AddVertex(gstVertex(0.220, 0.050, .0));
geode->AddVertex(gstVertex(0.220, 0.200, .0));
geode->AddVertex(gstVertex(0.050, 0.200, .0));
geode->AddVertex(gstVertex(0.100, 0.100, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with correct"
" orientation and obtuse angle 2.");
}
}
// CheckAndFixCycleOrientationTest4 - single-part geode with incorrect
// orientation - rectangle.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest4) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with incorrect"
" orientation - rectangle.");
}
}
// CheckAndFixCycleOrientationTest5 - single-part geode with incorrect
// orientation - obtuse angle is incident to most left-lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest5) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.60, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.60, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with incorrect"
" orientation - obtuse angle.");
}
}
// CheckAndFixCycleOrientationTest6 - single-part geode with incorrect
// orientation - acute angle is incident to most left lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest6) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.180, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.180, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with incorrect"
" orientation - acute angle 1.");
}
}
// CheckAndFixCycleOrientationTest7 - single-part geode with incorrect
// orientation - acute angle is incident to most left lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest7) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.160, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.180, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.180, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.160, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with incorrect"
" orientation - acute angle 2.");
}
}
// CheckAndFixCycleOrientationTest8 - single-part geode with incorrect
// orientation - right angle is incident to most left lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationTest8) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.200, .0, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.180, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.180, 0.180, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.200, .0, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: single-part geode with incorrect"
" orientation - right angle.");
}
}
// CheckAndFixCycleOrientationMultiPartGeodeTest1 - multi-part geode with
// incorrect orientation - rectangles.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationMultiPartGeodeTest1) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.020, 0.050, .0));
exp_geode->AddVertex(gstVertex(0.400, 0.050, .0));
exp_geode->AddVertex(gstVertex(0.400, 0.400, .0));
exp_geode->AddVertex(gstVertex(0.020, 0.400, .0));
exp_geode->AddVertex(gstVertex(0.020, 0.050, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.020, 0.050, .0));
geode->AddVertex(gstVertex(0.020, 0.400, .0));
geode->AddVertex(gstVertex(0.400, 0.400, .0));
geode->AddVertex(gstVertex(0.400, 0.050, .0));
geode->AddVertex(gstVertex(0.020, 0.050, .0));
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.120, 0.180, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: multi-part geode with incorrect"
" orientation - rectangles.");
}
}
// CheckAndFixCycleOrientationMultiPartGeodeTest2 - multi-part geode with
// incorrect orientation - acute/obtuse angles are incident to most left
// lower vertex.
TEST_F(GeometryCheckerTest, CheckAndFixCycleOrientationMultiPartGeodeTest2) {
gstGeodeHandle geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *geode = static_cast<gstGeode*>(&(*geodeh));
gstGeodeHandle exp_geodeh = gstGeodeImpl::Create(gstPolygon);
gstGeode *exp_geode = static_cast<gstGeode*>(&(*exp_geodeh));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.010, 0.020, .0));
exp_geode->AddVertex(gstVertex(0.400, 0.050, .0));
exp_geode->AddVertex(gstVertex(0.400, 0.400, .0));
exp_geode->AddVertex(gstVertex(0.020, 0.400, .0));
exp_geode->AddVertex(gstVertex(0.010, 0.020, .0));
exp_geode->AddPart(5);
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.050, 0.150, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.180, .0));
exp_geode->AddVertex(gstVertex(0.200, 0.120, .0));
exp_geode->AddVertex(gstVertex(0.120, 0.120, .0));
{
geode->Clear();
geode->AddPart(5);
geode->AddVertex(gstVertex(0.010, 0.020, .0));
geode->AddVertex(gstVertex(0.020, 0.400, .0));
geode->AddVertex(gstVertex(0.400, 0.400, .0));
geode->AddVertex(gstVertex(0.400, 0.050, .0));
geode->AddVertex(gstVertex(0.010, 0.020, .0));
geode->AddPart(5);
geode->AddVertex(gstVertex(0.120, 0.120, .0));
geode->AddVertex(gstVertex(0.200, 0.120, .0));
geode->AddVertex(gstVertex(0.200, 0.180, .0));
geode->AddVertex(gstVertex(0.050, 0.150, .0));
geode->AddVertex(gstVertex(0.120, 0.120, .0));
CheckAndFixCycleOrientation(
geodeh, exp_geodeh,
"CheckAndFix cycle orientation: multi-part geode with incorrect"
" orientation - acute/obtuse angles.");
}
}
} // namespace fusion_gst
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.820225
| 77
| 0.678767
|
ezeeyahoo
|
7e0765782b6bd26a518cb85d5d7cc059157aefbb
| 1,148
|
hpp
|
C++
|
_engine/code/include/global/component/profiler.hpp
|
Shelim/pixie_engine
|
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
|
[
"MIT"
] | null | null | null |
_engine/code/include/global/component/profiler.hpp
|
Shelim/pixie_engine
|
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
|
[
"MIT"
] | null | null | null |
_engine/code/include/global/component/profiler.hpp
|
Shelim/pixie_engine
|
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
|
[
"MIT"
] | null | null | null |
#ifndef ENGINE_GLOBAL_COMPONENT_PROFILER_HPP
#define ENGINE_GLOBAL_COMPONENT_PROFILER_HPP
#pragma once
#include "utility/text/ustring.hpp"
namespace engine
{
class profiler_t
{
public:
virtual ~profiler_t()
{
}
virtual void prof_begin_section(const char * name)
{
}
virtual void prof_end_section()
{
}
virtual void name_current_thread(const ustring_t & name)
{
}
class section_t
{
public:
section_t(std::shared_ptr<profiler_t> profiler, const char * name) : profiler(profiler)
{
profiler->prof_begin_section(name);
}
~section_t()
{
profiler->prof_end_section();
}
private:
std::shared_ptr<profiler_t> profiler;
};
};
}
#define prof_function(profiler) engine::profiler_t::section_t _function_section_at_##__LINE__(profiler, __FUNCTION__)
#include "global/component/profiler/dummy.hpp"
#include "global/component/profiler/real.hpp"
#endif
| 17.661538
| 117
| 0.577526
|
Shelim
|
7e086850a54e4560c0bc1ff6f6ab4de9098222e9
| 2,803
|
hxx
|
C++
|
src/control/genai/c_frontal.hxx
|
AltSysrq/Abendstern
|
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/control/genai/c_frontal.hxx
|
AltSysrq/Abendstern
|
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/control/genai/c_frontal.hxx
|
AltSysrq/Abendstern
|
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
|
[
"BSD-3-Clause"
] | 1
|
2022-01-29T11:54:41.000Z
|
2022-01-29T11:54:41.000Z
|
/**
* @file
* @author Jason Lingle
* @brief Contains the FrontalCortex
*/
/*
* c_frontal.hxx
*
* Created on: 02.11.2011
* Author: jason
*/
#ifndef C_FRONTAL_HXX_
#define C_FRONTAL_HXX_
#include "src/sim/objdl.hxx"
#include "cortex.hxx"
#include "ci_nil.hxx"
#include "ci_self.hxx"
#include "ci_objective.hxx"
class GameObject;
class Ship;
/**
* The FrontalCortex examines possible objectives and returns the one
* given the highest score.
*
* All FrontalCortices maintain a global telepathy map of
* (insignia,objective) --> cortices...
*/
class FrontalCortex: public Cortex, private
cortex_input::Self
<cortex_input::Objective
<cortex_input::Nil> > {
Ship*const ship;
ObjDL objective;
float objectiveScore; //Telepathy output
const float distanceParm, scoreWeightParm, dislikeWeightParm, happyWeightParm;
//The last known insignia of the ship
//(Specifically, the insignia when we inserted ourselves
// into the global map).
//0 indicates not inserted
unsigned long insertedInsignia;
//The GameObject* used to insert us into the global map.
//This may be a dangling pointer, never dereference
GameObject* insertedObjective;
//Milliseconds until the next scan
float timeUntilRescan;
//Add the opriority, ocurr, and otel inputs
static const unsigned cipe_last = cip_last+3,
cip_opriority = cip_last,
cip_ocurr = cip_last+1,
cip_otel = cip_last+2;
enum Output { target = 0 };
static const unsigned numOutputs = 1+(unsigned)target;
public:
class input_map: public cip_input_map {
public:
input_map() {
ins("opriority", cip_opriority);
ins("ocurr", cip_ocurr);
ins("otel", cip_otel);
}
};
/** Gives instructions on how to proceed */
struct Directive {
/** The objective to persue.
* If NULL, park.
*/
GameObject* objective;
/** What to do to the objective. */
enum Mode {
Attack, /// Proceed with the attack series of cortices
Navigate /// Phoceed with the Navigation cortex
} mode;
};
/**
* Constructs a new SelfSource.
* @param species The root of the species data to read from
* @param s The Ship to operate on
* @param ss The SelfSource to use
*/
FrontalCortex(const libconfig::Setting& species, Ship* s, cortex_input::SelfSource* ss);
~FrontalCortex();
/**
* Evaluates the cortex and returns its decision, given te elapsed time.
*/
Directive evaluate(float);
/** Returns the score of the cortex. */
float getScore() const;
private:
//Remove from global multimap if inserted
void unmap();
//Insert to global multimap;
//if inserted, unmap first.
//Does nothing if no objective.
void mapins();
};
#endif /* C_FRONTAL_HXX_ */
| 24.80531
| 90
| 0.674278
|
AltSysrq
|
7e0960ec09e3cb190439b783fe4f7141de760acb
| 2,479
|
cpp
|
C++
|
Infinit/src/Platform/OpenGL/OpenGLFrameBuffer.cpp
|
J4m3s00/Infinit
|
dd877100f8529e4a97c13f0d179b356800ef2eb9
|
[
"Apache-2.0"
] | null | null | null |
Infinit/src/Platform/OpenGL/OpenGLFrameBuffer.cpp
|
J4m3s00/Infinit
|
dd877100f8529e4a97c13f0d179b356800ef2eb9
|
[
"Apache-2.0"
] | 6
|
2019-07-03T14:21:06.000Z
|
2019-12-22T12:37:56.000Z
|
Infinit/src/Platform/OpenGL/OpenGLFrameBuffer.cpp
|
J4m3s00/Infinit
|
dd877100f8529e4a97c13f0d179b356800ef2eb9
|
[
"Apache-2.0"
] | null | null | null |
#include "inpch.h"
namespace Infinit {
OpenGLFrameBuffer::OpenGLFrameBuffer(uint width, uint height, FramebufferFormat format)
: m_Format(format), m_Width(0), m_Height(0), m_RendererID(0)
{
Resize(width, height);
}
OpenGLFrameBuffer::~OpenGLFrameBuffer()
{
}
void OpenGLFrameBuffer::Resize(uint width, uint height)
{
if (width == m_Width && height == m_Height) return;
m_Width = width;
m_Height = height;
if (m_RendererID)
{
IN_RENDER_S({
glDeleteFramebuffers(1, &self->m_RendererID);
glDeleteTextures(1, &self->m_ColorAttachment);
glDeleteTextures(1, &self->m_DepthAttachment);
})
}
IN_RENDER_S({
glGenFramebuffers(1, &self->m_RendererID);
glBindFramebuffer(GL_FRAMEBUFFER, self->m_RendererID);
glGenTextures(1, &self->m_ColorAttachment);
glBindTexture(GL_TEXTURE_2D, self->m_ColorAttachment);
if (self->m_Format == FramebufferFormat::RGBA16F)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, self->m_Width, self->m_Height, 0, GL_RGBA, GL_FLOAT, nullptr);
}
else if (self->m_Format == FramebufferFormat::RGBA8)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self->m_Width, self->m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self->m_ColorAttachment, 0);
glGenTextures(1, &self->m_DepthAttachment);
glBindTexture(GL_TEXTURE_2D, self->m_DepthAttachment);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, self->m_Width, self->m_Height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, self->m_DepthAttachment, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
IN_CORE_ERROR("Framebuffer is incomplete!");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
})
}
void OpenGLFrameBuffer::Bind() const
{
IN_RENDER_S({
glBindFramebuffer(GL_FRAMEBUFFER, self->m_RendererID);
glViewport(0, 0, self->m_Width, self->m_Height);
})
}
void OpenGLFrameBuffer::Unbind() const
{
IN_RENDER({
glBindFramebuffer(GL_FRAMEBUFFER, 0);
})
}
void OpenGLFrameBuffer::BindTexture(uint slot) const
{
IN_RENDER_S1(slot, {
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, self->m_ColorAttachment);
})
}
}
| 28.170455
| 135
| 0.736587
|
J4m3s00
|
7e182c2caf9e70471094294efe271e0b5c274604
| 10,961
|
cc
|
C++
|
chrome/browser/extensions/api/bluetooth/bluetooth_api.cc
|
1065672644894730302/Chromium
|
239dd49e906be4909e293d8991e998c9816eaa35
|
[
"BSD-3-Clause"
] | 1
|
2019-04-23T15:57:04.000Z
|
2019-04-23T15:57:04.000Z
|
chrome/browser/extensions/api/bluetooth/bluetooth_api.cc
|
1065672644894730302/Chromium
|
239dd49e906be4909e293d8991e998c9816eaa35
|
[
"BSD-3-Clause"
] | null | null | null |
chrome/browser/extensions/api/bluetooth/bluetooth_api.cc
|
1065672644894730302/Chromium
|
239dd49e906be4909e293d8991e998c9816eaa35
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 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 "chrome/browser/extensions/api/bluetooth/bluetooth_api.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/experimental_bluetooth.h"
#include "content/public/browser/browser_thread.h"
#if defined(OS_CHROMEOS)
#include "base/memory/ref_counted.h"
#include "base/safe_strerror_posix.h"
#include "base/synchronization/lock.h"
#include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/bluetooth_device.h"
#include "chrome/browser/chromeos/bluetooth/bluetooth_socket.h"
#include "chrome/browser/chromeos/extensions/bluetooth_event_router.h"
#include <errno.h>
using chromeos::BluetoothAdapter;
using chromeos::BluetoothDevice;
namespace {
chromeos::ExtensionBluetoothEventRouter* GetEventRouter(Profile* profile) {
return profile->GetExtensionService()->bluetooth_event_router();
}
const chromeos::BluetoothAdapter* GetAdapter(Profile* profile) {
return GetEventRouter(profile)->adapter();
}
chromeos::BluetoothAdapter* GetMutableAdapter(Profile* profile) {
return GetEventRouter(profile)->GetMutableAdapter();
}
} // namespace
#endif
namespace {
const char kSocketNotFoundError[] = "Socket not found: invalid socket id";
} // namespace
namespace Connect = extensions::api::experimental_bluetooth::Connect;
namespace Disconnect = extensions::api::experimental_bluetooth::Disconnect;
namespace GetDevicesWithServiceName =
extensions::api::experimental_bluetooth::GetDevicesWithServiceName;
namespace GetDevicesWithServiceUUID =
extensions::api::experimental_bluetooth::GetDevicesWithServiceUUID;
namespace Read = extensions::api::experimental_bluetooth::Read;
namespace Write = extensions::api::experimental_bluetooth::Write;
namespace extensions {
namespace api {
#if defined(OS_CHROMEOS)
bool BluetoothIsAvailableFunction::RunImpl() {
result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPresent()));
return true;
}
bool BluetoothIsPoweredFunction::RunImpl() {
result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPowered()));
return true;
}
bool BluetoothGetAddressFunction::RunImpl() {
result_.reset(Value::CreateStringValue(GetAdapter(profile())->address()));
return true;
}
bool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() {
scoped_ptr<GetDevicesWithServiceUUID::Params> params(
GetDevicesWithServiceUUID::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
const BluetoothAdapter::ConstDeviceList& devices =
GetAdapter(profile())->GetDevices();
ListValue* matches = new ListValue;
for (BluetoothAdapter::ConstDeviceList::const_iterator i =
devices.begin(); i != devices.end(); ++i) {
if ((*i)->ProvidesServiceWithUUID(params->uuid)) {
experimental_bluetooth::Device device;
device.name = UTF16ToUTF8((*i)->GetName());
device.address = (*i)->address();
matches->Append(device.ToValue().release());
}
}
result_.reset(matches);
return true;
}
BluetoothGetDevicesWithServiceNameFunction::
BluetoothGetDevicesWithServiceNameFunction() : callbacks_pending_(0) {}
void BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue(
ListValue* list, const BluetoothDevice* device, bool result) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (result) {
experimental_bluetooth::Device device_result;
device_result.name = UTF16ToUTF8(device->GetName());
device_result.address = device->address();
list->Append(device_result.ToValue().release());
}
callbacks_pending_--;
if (callbacks_pending_ == 0) {
SendResponse(true);
Release(); // Added in RunImpl
}
}
bool BluetoothGetDevicesWithServiceNameFunction::RunImpl() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
ListValue* matches = new ListValue;
result_.reset(matches);
BluetoothAdapter::DeviceList devices =
GetMutableAdapter(profile())->GetDevices();
if (devices.empty()) {
SendResponse(true);
return true;
}
callbacks_pending_ = devices.size();
AddRef(); // Released in AddDeviceIfTrue when callbacks_pending_ == 0
scoped_ptr<GetDevicesWithServiceName::Params> params(
GetDevicesWithServiceName::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
for (BluetoothAdapter::DeviceList::iterator i = devices.begin();
i != devices.end(); ++i) {
(*i)->ProvidesServiceWithName(params->name,
base::Bind(&BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue,
this,
matches,
*i));
}
return true;
}
void BluetoothConnectFunction::ConnectToServiceCallback(
const chromeos::BluetoothDevice* device,
const std::string& service_uuid,
scoped_refptr<chromeos::BluetoothSocket> socket) {
if (socket.get()) {
int socket_id = GetEventRouter(profile())->RegisterSocket(socket);
experimental_bluetooth::Socket result_socket;
result_socket.device.address = device->address();
result_socket.device.name = UTF16ToUTF8(device->GetName());
result_socket.service_uuid = service_uuid;
result_socket.id = socket_id;
result_.reset(result_socket.ToValue().release());
SendResponse(true);
} else {
SendResponse(false);
}
Release(); // Added in RunImpl
}
bool BluetoothConnectFunction::RunImpl() {
scoped_ptr<Connect::Params> params(Connect::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
chromeos::BluetoothDevice* device =
GetMutableAdapter(profile())->GetDevice(params->device.address);
if (!device) {
SendResponse(false);
return false;
}
AddRef();
device->ConnectToService(params->service,
base::Bind(&BluetoothConnectFunction::ConnectToServiceCallback,
this,
device,
params->service));
return true;
}
bool BluetoothDisconnectFunction::RunImpl() {
scoped_ptr<Disconnect::Params> params(Disconnect::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
return GetEventRouter(profile())->ReleaseSocket(params->socket.id);
}
bool BluetoothReadFunction::Prepare() {
scoped_ptr<Read::Params> params(Read::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
socket_ = GetEventRouter(profile())->GetSocket(params->socket.id);
if (socket_.get() == NULL) {
SetError(kSocketNotFoundError);
return false;
}
success_ = false;
return true;
}
void BluetoothReadFunction::Work() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
CHECK(socket_.get() != NULL);
char* all_bytes = NULL;
ssize_t buffer_size = 0;
ssize_t total_bytes_read = 0;
int errsv;
while (true) {
buffer_size += 1024;
all_bytes = static_cast<char*>(realloc(all_bytes, buffer_size));
CHECK(all_bytes) << "Failed to grow Bluetooth socket buffer";
// bluetooth sockets are non-blocking, so read until we hit an error
ssize_t bytes_read = read(socket_->fd(), all_bytes + total_bytes_read,
buffer_size - total_bytes_read);
errsv = errno;
if (bytes_read <= 0)
break;
total_bytes_read += bytes_read;
}
if (total_bytes_read > 0) {
success_ = true;
result_.reset(base::BinaryValue::Create(all_bytes, total_bytes_read));
} else {
success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK);
free(all_bytes);
}
if (!success_)
SetError(safe_strerror(errsv));
}
bool BluetoothReadFunction::Respond() {
return success_;
}
bool BluetoothWriteFunction::Prepare() {
// TODO(bryeung): update to new-style parameter passing when ArrayBuffer
// support is added
DictionaryValue* socket;
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &socket));
int socket_id;
EXTENSION_FUNCTION_VALIDATE(socket->GetInteger("id", &socket_id));
socket_ = GetEventRouter(profile())->GetSocket(socket_id);
if (socket_.get() == NULL) {
SetError(kSocketNotFoundError);
return false;
}
base::BinaryValue* tmp_data;
EXTENSION_FUNCTION_VALIDATE(args_->GetBinary(1, &tmp_data));
data_to_write_ = tmp_data;
success_ = false;
return socket_.get() != NULL;
}
void BluetoothWriteFunction::Work() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
if (socket_.get() == NULL)
return;
ssize_t bytes_written = write(socket_->fd(),
data_to_write_->GetBuffer(), data_to_write_->GetSize());
int errsv = errno;
if (bytes_written > 0) {
result_.reset(Value::CreateIntegerValue(bytes_written));
success_ = true;
} else {
result_.reset(0);
success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK);
}
if (!success_)
SetError(safe_strerror(errsv));
}
bool BluetoothWriteFunction::Respond() {
return success_;
}
#else
// -----------------------------------------------------------------------------
// NIY stubs
// -----------------------------------------------------------------------------
bool BluetoothIsAvailableFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothIsPoweredFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothGetAddressFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothGetDevicesWithServiceNameFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothConnectFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothDisconnectFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothReadFunction::Prepare() {
return true;
}
void BluetoothReadFunction::Work() {
}
bool BluetoothReadFunction::Respond() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothWriteFunction::Prepare() {
return true;
}
void BluetoothWriteFunction::Work() {
}
bool BluetoothWriteFunction::Respond() {
NOTREACHED() << "Not implemented yet";
return false;
}
#endif
BluetoothReadFunction::BluetoothReadFunction() {}
BluetoothReadFunction::~BluetoothReadFunction() {}
BluetoothWriteFunction::BluetoothWriteFunction() {}
BluetoothWriteFunction::~BluetoothWriteFunction() {}
bool BluetoothSetOutOfBandPairingDataFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
bool BluetoothGetOutOfBandPairingDataFunction::RunImpl() {
NOTREACHED() << "Not implemented yet";
return false;
}
} // namespace api
} // namespace extensions
| 28.47013
| 80
| 0.716632
|
1065672644894730302
|
7e1a088a7797a422fe47eb3c8731608f189a1c84
| 3,975
|
cpp
|
C++
|
Firmware/Src/io/lcd/LcdDriver.cpp
|
borgu/midi-grid
|
ce65669f55d5d5598a8ff185debcec76ab001bfa
|
[
"BSD-3-Clause"
] | null | null | null |
Firmware/Src/io/lcd/LcdDriver.cpp
|
borgu/midi-grid
|
ce65669f55d5d5598a8ff185debcec76ab001bfa
|
[
"BSD-3-Clause"
] | null | null | null |
Firmware/Src/io/lcd/LcdDriver.cpp
|
borgu/midi-grid
|
ce65669f55d5d5598a8ff185debcec76ab001bfa
|
[
"BSD-3-Clause"
] | null | null | null |
#include "io/lcd/LcdDriver.hpp"
#include "system/gpio_definitions.h"
#include "stm32f4xx_hal.h"
namespace lcd
{
static DMA_HandleTypeDef lcdSpiDma;
static SPI_HandleTypeDef lcdSpi;
extern "C" void DMA1_Stream4_IRQHandler()
{
HAL_DMA_IRQHandler(&lcdSpiDma);
}
LcdDriver::LcdDriver()
{
}
LcdDriver::~LcdDriver()
{
}
void LcdDriver::initialize()
{
initializeGpio();
initializeSpi();
initializeDma();
resetController();
writeCommand( 0x21 ); // LCD extended commands.
writeCommand( 0xB8 ); // set LCD Vop(Contrast).
writeCommand( 0x04 ); // set temp coefficent.
writeCommand( 0x15 ); // LCD bias mode 1:65. used to be 0x14 - 1:40
writeCommand( 0x20 ); // LCD basic commands.
writeCommand( 0x0C ); // LCD normal.
}
void LcdDriver::transmit( uint8_t* const buffer )
{
setCursor( 0, 0 );
while (HAL_DMA_STATE_BUSY == HAL_DMA_GetState( &lcdSpiDma ))
{
// wait until previous transfer is done
}
HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::DC_Pin, GPIO_PIN_SET ); //data mode
HAL_SPI_Transmit_DMA( &lcdSpi, &buffer[0], bufferSize );
}
void LcdDriver::initializeDma()
{
__HAL_RCC_DMA1_CLK_ENABLE();
// SPI2 DMA Init
// SPI2_TX Init
lcdSpiDma.Instance = DMA1_Stream4;
lcdSpiDma.Init.Channel = DMA_CHANNEL_0;
lcdSpiDma.Init.Direction = DMA_MEMORY_TO_PERIPH;
lcdSpiDma.Init.PeriphInc = DMA_PINC_DISABLE;
lcdSpiDma.Init.MemInc = DMA_MINC_ENABLE;
lcdSpiDma.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
lcdSpiDma.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
lcdSpiDma.Init.Mode = DMA_NORMAL;
lcdSpiDma.Init.Priority = DMA_PRIORITY_LOW;
lcdSpiDma.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
HAL_DMA_Init( &lcdSpiDma );
__HAL_LINKDMA( &lcdSpi, hdmatx, lcdSpiDma );
// DMA interrupt init
// DMA1_Stream4_IRQn interrupt configuration
HAL_NVIC_SetPriority( DMA1_Stream4_IRQn, 6, 0 );
HAL_NVIC_EnableIRQ( DMA1_Stream4_IRQn );
}
void LcdDriver::initializeGpio()
{
static GPIO_InitTypeDef gpioConfiguration;
__HAL_RCC_GPIOB_CLK_ENABLE();
gpioConfiguration.Pin = mcu::DC_Pin | mcu::RESET_Pin;
gpioConfiguration.Mode = GPIO_MODE_OUTPUT_PP;
gpioConfiguration.Pull = GPIO_NOPULL;
gpioConfiguration.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
HAL_GPIO_Init( mcu::LCD_GPIO_Port, &gpioConfiguration );
gpioConfiguration.Pin = mcu::CS_Pin | mcu::SCK_Pin | mcu::MOSI_Pin;
gpioConfiguration.Mode = GPIO_MODE_AF_PP;
gpioConfiguration.Alternate = GPIO_AF5_SPI2;
HAL_GPIO_Init( mcu::LCD_GPIO_Port, &gpioConfiguration );
}
void LcdDriver::initializeSpi()
{
__HAL_RCC_SPI2_CLK_ENABLE();
// SPI2 parameter configuration
lcdSpi.Instance = SPI2;
lcdSpi.Init.Mode = SPI_MODE_MASTER;
lcdSpi.Init.Direction = SPI_DIRECTION_2LINES;
lcdSpi.Init.DataSize = SPI_DATASIZE_8BIT;
lcdSpi.Init.CLKPolarity = SPI_POLARITY_LOW;
lcdSpi.Init.CLKPhase = SPI_PHASE_1EDGE;
lcdSpi.Init.NSS = SPI_NSS_HARD_OUTPUT;
lcdSpi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; // 3MBbit?
lcdSpi.Init.FirstBit = SPI_FIRSTBIT_MSB;
lcdSpi.Init.TIMode = SPI_TIMODE_DISABLE;
lcdSpi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
HAL_SPI_Init( &lcdSpi );
}
void LcdDriver::resetController()
{
HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::RESET_Pin, GPIO_PIN_RESET );
HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::RESET_Pin, GPIO_PIN_SET );
}
void LcdDriver::setCursor( const uint8_t x, const uint8_t y )
{
writeCommand( 0x80 | x ); // column.
writeCommand( 0x40 | y ); // row.
}
void LcdDriver::writeCommand( const uint8_t command )
{
uint8_t commandToWrite = command;
while (HAL_DMA_STATE_BUSY == HAL_DMA_GetState( &lcdSpiDma ))
{
// wait until previous transfer is done
}
HAL_GPIO_WritePin( mcu::LCD_GPIO_Port, mcu::DC_Pin, GPIO_PIN_RESET ); //command mode
HAL_SPI_Transmit_DMA( &lcdSpi, &commandToWrite, 1 );
}
} // namespace lcd
| 27.797203
| 88
| 0.720755
|
borgu
|
7e1ae4aa4ceb168d6d7f5a29b2f60d26b7096f1f
| 9,157
|
cpp
|
C++
|
Source/dvlnet/tcp_server.cpp
|
pionere/devilutionX
|
63f8deb298a00b040010fc299c0568eae19522e1
|
[
"Unlicense"
] | 2
|
2021-02-02T19:27:20.000Z
|
2022-03-07T16:50:55.000Z
|
Source/dvlnet/tcp_server.cpp
|
pionere/devilutionX
|
63f8deb298a00b040010fc299c0568eae19522e1
|
[
"Unlicense"
] | null | null | null |
Source/dvlnet/tcp_server.cpp
|
pionere/devilutionX
|
63f8deb298a00b040010fc299c0568eae19522e1
|
[
"Unlicense"
] | 1
|
2022-03-07T16:51:16.000Z
|
2022-03-07T16:51:16.000Z
|
#include "tcp_server.h"
#ifdef TCPIP
#include <chrono>
#include <memory>
#include "base.h"
DEVILUTION_BEGIN_NAMESPACE
namespace net {
tcp_server::tcp_server(asio::io_context &ioc, buffer_t info, unsigned srvType)
: ioc(ioc)
, acceptor(ioc)
, connTimer(ioc)
, game_init_info(info)
, serverType(srvType)
{
assert(game_init_info.size() == sizeof(SNetGameData));
}
bool tcp_server::setup_server(const char* bindAddr, unsigned short port, const char* passwd)
{
pktfty.setup_password(passwd);
asio::error_code err;
auto addr = asio::ip::address::from_string(bindAddr, err);
if (!err) {
auto ep = asio::ip::tcp::endpoint(addr, port);
connect_acceptor(acceptor, ep, err);
}
if (err) {
SDL_SetError("%s", err.message().c_str());
close();
return false;
}
start_accept();
start_timeout();
return true;
}
void tcp_server::connect_acceptor(asio::ip::tcp::acceptor &acceptor,
const asio::ip::tcp::endpoint& ep, asio::error_code &ec)
{
acceptor.open(ep.protocol(), ec);
if (ec)
return;
acceptor.set_option(asio::socket_base::reuse_address(true), ec);
assert(!ec);
acceptor.bind(ep, ec);
if (ec)
return;
acceptor.listen(2 * MAX_PLRS, ec);
}
void tcp_server::connect_socket(asio::ip::tcp::socket &sock,
const char* addrstr, unsigned port,
asio::io_context &ioc, asio::error_code &ec)
{
std::string strPort = std::to_string(port);
auto resolver = asio::ip::tcp::resolver(ioc);
auto addrList = resolver.resolve(addrstr, strPort, ec);
if (ec)
return;
asio::connect(sock, addrList, ec);
if (ec)
return;
asio::ip::tcp::no_delay option(true);
sock.set_option(option, ec);
assert(!ec);
}
void tcp_server::endpoint_to_string(const scc &con, std::string &addr)
{
asio::error_code err;
const auto &ep = con->socket.remote_endpoint(err);
assert(!err);
char buf[PORT_LENGTH + 2];
snprintf(buf, sizeof(buf), ":%05d", ep.port());
addr = ep.address().to_string();
addr.append(buf);
}
void tcp_server::make_default_gamename(char (&gamename)[128])
{
if (!getIniValue("Network", "Bind Address", gamename, sizeof(gamename) - 1)) {
copy_cstr(gamename, "127.0.0.1");
//SStrCopy(gamename, asio::ip::address_v4::loopback().to_string().c_str(), sizeof(gamename));
}
}
tcp_server::scc tcp_server::make_connection(asio::io_context &ioc)
{
return std::make_shared<client_connection>(ioc);
}
plr_t tcp_server::next_free_conn()
{
plr_t i;
for (i = 0; i < MAX_PLRS; i++)
if (connections[i] == NULL)
break;
return i < ((SNetGameData*)game_init_info.data())->bMaxPlayers ? i : MAX_PLRS;
}
plr_t tcp_server::next_free_queue()
{
plr_t i;
for (i = 0; i < MAX_PLRS; i++)
if (pending_connections[i] == NULL)
break;
return i;
}
void tcp_server::start_recv(const scc &con)
{
con->socket.async_receive(asio::buffer(con->recv_buffer),
std::bind(&tcp_server::handle_recv, this, con,
std::placeholders::_1,
std::placeholders::_2));
}
void tcp_server::handle_recv(const scc &con, const asio::error_code &ec, size_t bytesRead)
{
if (ec || bytesRead == 0) {
drop_connection(con);
return;
}
con->timeout = TIMEOUT_ACTIVE;
con->recv_buffer.resize(bytesRead);
con->recv_queue.write(std::move(con->recv_buffer));
con->recv_buffer.resize(frame_queue::MAX_FRAME_SIZE);
while (con->recv_queue.packet_ready()) {
auto pkt = pktfty.make_in_packet(con->recv_queue.read_packet());
if (pkt == NULL || !handle_recv_packet(con, *pkt)) {
drop_connection(con);
return;
}
}
start_recv(con);
}
/*void tcp_server::send_connect(const scc &con)
{
auto pkt = pktfty.make_out_packet<PT_CONNECT>(PLR_MASTER, PLR_BROADCAST,
con->pnum);
send_packet(*pkt);
}*/
bool tcp_server::handle_recv_newplr(const scc &con, packet &pkt)
{
plr_t i, pnum;
if (pkt.pktType() != PT_JOIN_REQUEST) {
// SDL_Log("Invalid join packet.");
return false;
}
pnum = next_free_conn();
for (i = 0; i < MAX_PLRS; i++) {
if (pending_connections[i] == con)
break;
}
if (pnum == MAX_PLRS || i == MAX_PLRS) {
// SDL_Log(pnum == MAX_PLRS ? "Server is full." : "Dropped connection.");
return false;
}
pending_connections[i] = NULL;
connections[pnum] = con;
con->pnum = pnum;
auto reply = pktfty.make_out_packet<PT_JOIN_ACCEPT>(PLR_MASTER, PLR_BROADCAST,
pkt.pktJoinReqCookie(), pnum, game_init_info);
start_send(con, *reply);
//send_connect(con);
if (serverType == SRV_DIRECT) {
std::string addr;
for (i = 0; i < MAX_PLRS; i++) {
if (connections[i] != NULL && connections[i] != con) {
endpoint_to_string(connections[i], addr);
auto oldConPkt = pktfty.make_out_packet<PT_CONNECT>(PLR_MASTER, PLR_BROADCAST,
i, buffer_t(addr.begin(), addr.end()));
start_send(con, *oldConPkt);
}
}
}
return true;
}
bool tcp_server::handle_recv_packet(const scc &con, packet &pkt)
{
if (con->pnum != PLR_BROADCAST) {
return con->pnum == pkt.pktSrc() && send_packet(pkt);
} else {
return handle_recv_newplr(con, pkt);
}
}
bool tcp_server::send_packet(packet &pkt)
{
plr_t dest = pkt.pktDest();
plr_t src = pkt.pktSrc();
if (dest == PLR_BROADCAST) {
for (int i = 0; i < MAX_PLRS; i++)
if (i != src && connections[i] != NULL)
start_send(connections[i], pkt);
} else {
if (dest >= MAX_PLRS) {
// SDL_Log("Invalid destination %d", dest);
return false;
}
if ((dest != src) && connections[dest] != NULL)
start_send(connections[dest], pkt);
}
return true;
}
void tcp_server::start_send(const scc &con, packet &pkt)
{
const auto *frame = new buffer_t(frame_queue::make_frame(pkt.encrypted_data()));
auto buf = asio::buffer(*frame);
asio::async_write(con->socket, buf,
[frame](const asio::error_code &ec, size_t bytesSent) {
delete frame;
});
}
void tcp_server::start_accept()
{
if (next_free_queue() != MAX_PLRS) {
nextcon = make_connection(ioc);
acceptor.async_accept(nextcon->socket,
std::bind(&tcp_server::handle_accept,
this, true,
std::placeholders::_1));
} else {
nextcon = NULL;
connTimer.expires_after(std::chrono::seconds(10));
connTimer.async_wait(std::bind(&tcp_server::handle_accept,
this, false,
std::placeholders::_1));
}
}
void tcp_server::handle_accept(bool valid, const asio::error_code &ec)
{
if (ec)
return;
if (valid) {
asio::error_code err;
asio::ip::tcp::no_delay option(true);
nextcon->socket.set_option(option, err);
assert(!err);
nextcon->timeout = TIMEOUT_CONNECT;
pending_connections[next_free_queue()] = nextcon;
start_recv(nextcon);
}
start_accept();
}
void tcp_server::start_timeout()
{
connTimer.expires_after(std::chrono::seconds(1));
connTimer.async_wait(std::bind(&tcp_server::handle_timeout, this,
std::placeholders::_1));
}
void tcp_server::handle_timeout(const asio::error_code &ec)
{
int i, n;
if (ec)
return;
scc expired_connections[2 * MAX_PLRS] = { };
n = 0;
for (i = 0; i < MAX_PLRS; i++) {
if (pending_connections[i] != NULL) {
if (pending_connections[i]->timeout > 0) {
pending_connections[i]->timeout--;
} else {
expired_connections[n] = pending_connections[i];
n++;
}
}
}
for (i = 0; i < MAX_PLRS; i++) {
if (connections[i] != NULL) {
if (connections[i]->timeout > 0) {
connections[i]->timeout--;
} else {
expired_connections[n] = connections[i];
n++;
}
}
}
for (i = 0; i < n; i++)
drop_connection(expired_connections[i]);
start_timeout();
}
void tcp_server::drop_connection(const scc &con)
{
plr_t i, pnum = con->pnum;
if (pnum != PLR_BROADCAST) {
// live connection
if (connections[pnum] == con) {
connections[pnum] = NULL;
// notify the other clients
auto pkt = pktfty.make_out_packet<PT_DISCONNECT>(PLR_MASTER, PLR_BROADCAST,
pnum, (leaveinfo_t)LEAVE_DROP);
send_packet(*pkt);
}
} else {
// pending connection
for (i = 0; i < MAX_PLRS; i++) {
if (pending_connections[i] == con) {
pending_connections[i] = NULL;
}
}
}
asio::error_code err;
con->socket.close(err);
}
void tcp_server::close()
{
int i;
asio::error_code err;
if (acceptor.is_open()) {
auto pkt = pktfty.make_out_packet<PT_DISCONNECT>(PLR_MASTER, PLR_BROADCAST,
PLR_MASTER, (leaveinfo_t)LEAVE_DROP);
send_packet(*pkt);
ioc.poll(err);
err.clear();
}
acceptor.close(err);
err.clear();
connTimer.cancel(err);
err.clear();
ioc.poll(err);
err.clear();
if (nextcon != NULL) {
nextcon->socket.close(err);
err.clear();
}
for (i = 0; i < MAX_PLRS; i++) {
if (connections[i] != NULL) {
connections[i]->socket.shutdown(asio::socket_base::shutdown_both, err);
err.clear();
connections[i]->socket.close(err);
err.clear();
}
}
for (i = 0; i < MAX_PLRS; i++) {
if (pending_connections[i] != NULL) {
pending_connections[i]->socket.close(err);
err.clear();
}
}
ioc.poll(err);
}
} // namespace net
DEVILUTION_END_NAMESPACE
#endif // TCPIP
| 24.748649
| 96
| 0.642569
|
pionere
|
7e1b2f410e7f84f5311dea12c79674b57900bc0a
| 758
|
cpp
|
C++
|
cpp/BalancedBinaryTree.cpp
|
thinksource/code_interview
|
08be992240508b73894eaf6b8c025168fd19df19
|
[
"Apache-2.0"
] | 12
|
2015-03-12T03:27:26.000Z
|
2021-03-11T09:26:16.000Z
|
cpp/BalancedBinaryTree.cpp
|
thinksource/code_interview
|
08be992240508b73894eaf6b8c025168fd19df19
|
[
"Apache-2.0"
] | null | null | null |
cpp/BalancedBinaryTree.cpp
|
thinksource/code_interview
|
08be992240508b73894eaf6b8c025168fd19df19
|
[
"Apache-2.0"
] | 11
|
2015-01-28T16:45:40.000Z
|
2017-03-28T20:01:38.000Z
|
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
int h = 0;
return isBalanced(root, h);
}
bool isBalanced(TreeNode* root, int& height) {
if(root==NULL) {
height = 0;
return true;
}
int heightLeft = 0;
int heightRight = 0;
bool isBLeft = isBalanced(root->left, heightLeft);
bool isBRight = isBalanced(root->right, heightRight);
height = 1+max(heightLeft, heightRight);
return abs(heightLeft-heightRight)<=1 && isBLeft && isBRight;
}
};
| 25.266667
| 69
| 0.555409
|
thinksource
|
7e1be89d5ebd582653ffef7f21993d81a14d0ab8
| 5,033
|
cpp
|
C++
|
gui/statuses/LocalStatuses.cpp
|
mail-ru-im/im-desktop
|
d6bb606650ad84b31046fe39b81db1fec4e6050b
|
[
"Apache-2.0"
] | 81
|
2019-09-18T13:53:17.000Z
|
2022-03-19T00:44:20.000Z
|
gui/statuses/LocalStatuses.cpp
|
mail-ru-im/im-desktop
|
d6bb606650ad84b31046fe39b81db1fec4e6050b
|
[
"Apache-2.0"
] | 4
|
2019-10-03T15:17:00.000Z
|
2019-11-03T01:05:41.000Z
|
gui/statuses/LocalStatuses.cpp
|
mail-ru-im/im-desktop
|
d6bb606650ad84b31046fe39b81db1fec4e6050b
|
[
"Apache-2.0"
] | 25
|
2019-09-27T16:56:02.000Z
|
2022-03-14T07:11:14.000Z
|
#include "stdafx.h"
#include "utils/JsonUtils.h"
#include "../utils/features.h"
#include "LocalStatuses.h"
#include "gui_settings.h"
#include "utils/utils.h"
#include "utils/InterConnector.h"
#include "rapidjson/writer.h"
namespace
{
inline QString getDefaultJSONPath()
{
return (Ui::get_gui_settings()->get_value(settings_language, QString()) == u"ru") ? qsl(":/statuses/default_statuses") : qsl(":/statuses/default_statuses_eng");
}
std::vector<Statuses::LocalStatus> defaultStatuses()
{
std::vector<Statuses::LocalStatus> statuses;
rapidjson::Document doc;
doc.Parse(Features::getStatusJson());
if (doc.HasParseError())
{
im_assert(QFile::exists(getDefaultJSONPath()));
QFile file(getDefaultJSONPath());
if (!file.open(QFile::ReadOnly | QFile::Text))
return statuses;
const auto json = file.readAll();
doc.Parse(json.constData(), json.size());
if (doc.HasParseError())
{
im_assert(false);
return statuses;
}
file.close();
}
if (doc.IsArray())
{
statuses.reserve(doc.Size());
for (const auto& item : doc.GetArray())
{
Statuses::LocalStatus status;
JsonUtils::unserialize_value(item, "status", status.status_);
JsonUtils::unserialize_value(item, "text", status.description_);
JsonUtils::unserialize_value(item, "duration", status.duration_);
statuses.push_back(std::move(status));
}
}
return statuses;
}
}
namespace Statuses
{
using namespace Ui;
class LocalStatuses_p
{
public:
void updateIndex()
{
index_.clear();
for (auto i = 0u; i < statuses_.size(); i++)
index_[statuses_[i].status_] = i;
}
void overrideStatusDurationsFromSettings()
{
for (auto& status : statuses_)
{
if (get_gui_settings()->contains_value(status_duration, status.status_))
status.duration_ = std::chrono::seconds(get_gui_settings()->get_value<int64_t>(status_duration, 0, status.status_));
}
}
void load()
{
statuses_ = defaultStatuses();
migrateOldSettingsData();
overrideStatusDurationsFromSettings();
updateIndex();
}
void resetToDefaults()
{
statuses_ = defaultStatuses();
updateIndex();
}
void migrateOldSettingsData()
{
const auto statusesStr = get_gui_settings()->get_value<QString>(statuses_user_statuses, QString());
const auto statuses = statusesStr.splitRef(ql1c(';'), QString::SkipEmptyParts);
for (const auto& s : boost::adaptors::reverse(statuses))
{
const auto& stat = s.split(ql1c(':'), QString::SkipEmptyParts);
if (!stat.isEmpty() && stat.size() == 2)
get_gui_settings()->set_value<int64_t>(status_duration, stat[1].toLongLong(), stat[0].toString());
}
get_gui_settings()->set_value(statuses_user_statuses, QString());
}
std::vector<LocalStatus> statuses_;
std::unordered_map<QString, size_t, Utils::QStringHasher> index_;
};
LocalStatuses::LocalStatuses()
: d(std::make_unique<LocalStatuses_p>())
{
d->load();
connect(&Utils::InterConnector::instance(), &Utils::InterConnector::omicronUpdated, this, &LocalStatuses::onOmicronUpdated);
}
LocalStatuses::~LocalStatuses() = default;
LocalStatuses* LocalStatuses::instance()
{
static LocalStatuses localStatuses;
return &localStatuses;
}
const LocalStatus& LocalStatuses::getStatus(const QString& _statusCode) const
{
auto it = d->index_.find(_statusCode);
if (it != d->index_.end())
return d->statuses_[it->second];
static LocalStatus empty;
return empty;
}
void LocalStatuses::setDuration(const QString& _statusCode, std::chrono::seconds _duration)
{
auto it = d->index_.find(_statusCode);
if (it != d->index_.end())
{
d->statuses_[it->second].duration_ = _duration;
get_gui_settings()->set_value<int64_t>(status_duration, _duration.count(), _statusCode);
}
}
std::chrono::seconds LocalStatuses::statusDuration(const QString& _statusCode) const
{
auto it = d->index_.find(_statusCode);
if (it != d->index_.end())
return d->statuses_[it->second].duration_;
return std::chrono::seconds::zero();
}
const QString& LocalStatuses::statusDescription(const QString& _statusCode) const
{
auto it = d->index_.find(_statusCode);
if (it != d->index_.end())
return d->statuses_[it->second].description_;
static QString empty;
return empty;
}
const std::vector<LocalStatus>& LocalStatuses::statuses() const
{
return d->statuses_;
}
void LocalStatuses::resetToDefaults()
{
d->resetToDefaults();
}
void LocalStatuses::onOmicronUpdated()
{
d->load();
}
}
| 25.943299
| 168
| 0.622293
|
mail-ru-im
|
7e1caedc68709129a2d488241201b6042bf4625e
| 1,608
|
cpp
|
C++
|
Native/Framework/source/Library.Shared/SpriteManager.cpp
|
btrowbridge/DirectX.2D.Bespoke.Games
|
382728f7c9d50597f9fc84e222efd468c33716a5
|
[
"MS-PL"
] | null | null | null |
Native/Framework/source/Library.Shared/SpriteManager.cpp
|
btrowbridge/DirectX.2D.Bespoke.Games
|
382728f7c9d50597f9fc84e222efd468c33716a5
|
[
"MS-PL"
] | null | null | null |
Native/Framework/source/Library.Shared/SpriteManager.cpp
|
btrowbridge/DirectX.2D.Bespoke.Games
|
382728f7c9d50597f9fc84e222efd468c33716a5
|
[
"MS-PL"
] | null | null | null |
#include "pch.h"
#include "SpriteManager.h"
using namespace std;
using namespace DirectX;
namespace Library
{
unique_ptr<SpriteManager> SpriteManager::sInstance;
SpriteManager::SpriteManager(Game& game) :
mGame(&game), mSpriteBatch(make_shared<DirectX::SpriteBatch>(mGame->Direct3DDeviceContext()))
{
}
shared_ptr<SpriteBatch> SpriteManager::SpriteBatch()
{
return sInstance->mSpriteBatch;
}
void SpriteManager::Initialize(Game& game)
{
sInstance = unique_ptr<SpriteManager>(new SpriteManager(game));
}
void SpriteManager::Shutdown()
{
sInstance = nullptr;
}
void SpriteManager::DrawTexture2D(ID3D11ShaderResourceView* texture, const XMFLOAT2& position, FXMVECTOR color)
{
assert(sInstance != nullptr);
sInstance->mSpriteBatch->Begin();
sInstance->mSpriteBatch->Draw(texture, position, color);
sInstance->mSpriteBatch->End();
}
void SpriteManager::DrawTexture2D(ID3D11ShaderResourceView* texture, const Rectangle& destinationRectangle, FXMVECTOR color)
{
assert(sInstance != nullptr);
sInstance->mSpriteBatch->Begin();
RECT destinationRect = { destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height };
sInstance->mSpriteBatch->Draw(texture, destinationRect, color);
sInstance->mSpriteBatch->End();
}
void SpriteManager::DrawString(shared_ptr<SpriteFont> font, const wstring& text, const XMFLOAT2& textPosition)
{
assert(sInstance != nullptr);
sInstance->mSpriteBatch->Begin();
font->DrawString(sInstance->mSpriteBatch.get(), text.c_str(), textPosition);
sInstance->mSpriteBatch->End();
}
}
| 27.724138
| 133
| 0.75995
|
btrowbridge
|
7e1dbbe5a0decdaec568540334ac2b00e0186796
| 5,991
|
cpp
|
C++
|
JNIManagedPeer.cpp
|
jessebenson/JNIManagedPeerBase
|
7188fc75ecd2010901c9baf98436e7f16eb488b2
|
[
"MIT"
] | null | null | null |
JNIManagedPeer.cpp
|
jessebenson/JNIManagedPeerBase
|
7188fc75ecd2010901c9baf98436e7f16eb488b2
|
[
"MIT"
] | null | null | null |
JNIManagedPeer.cpp
|
jessebenson/JNIManagedPeerBase
|
7188fc75ecd2010901c9baf98436e7f16eb488b2
|
[
"MIT"
] | 1
|
2019-01-03T12:34:01.000Z
|
2019-01-03T12:34:01.000Z
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Jesse Benson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "stdafx.h"
#include "JNIManagedPeer.h"
namespace JNI {
static JavaVM* s_JVM = nullptr;
void STDMETHODCALLTYPE SetJVM(JavaVM* jvm)
{
s_JVM = jvm;
}
JavaVM* STDMETHODCALLTYPE GetJVM()
{
return s_JVM;
}
static JNIEnv* GetEnvironment()
{
JNIEnv* env = nullptr;
if (s_JVM != nullptr)
s_JVM->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
return env;
}
JNIEnv& STDMETHODCALLTYPE GetEnv()
{
return *GetEnvironment();
}
JObject::JObject()
{
}
JObject::JObject(jobject object, bool releaseLocalRef)
{
JNIEnv* env = GetEnvironment();
AttachObject(env, object);
if (releaseLocalRef)
{
env->DeleteLocalRef(object);
}
}
JObject::JObject(const JObject& object)
{
AttachObject(GetEnvironment(), object.m_Object);
}
JObject::JObject(JObject&& object)
: m_Object(object.m_Object)
{
object.m_Object = nullptr;
}
JObject::~JObject()
{
ReleaseObject(GetEnvironment());
}
JObject& JObject::operator=(jobject object)
{
JNIEnv* env = GetEnvironment();
ReleaseObject(env);
AttachObject(env, object);
return *this;
}
JObject& JObject::operator=(const JObject& object)
{
if (this != &object)
{
JNIEnv* env = GetEnvironment();
ReleaseObject(env);
AttachObject(env, object.m_Object);
}
return *this;
}
JObject& JObject::operator=(JObject&& object)
{
if (this != &object)
{
ReleaseObject(GetEnvironment());
m_Object = object.m_Object;
object.m_Object = nullptr;
}
return *this;
}
void JObject::AttachObject(JNIEnv* env, jobject object)
{
if (object != nullptr)
{
m_Object = env->NewGlobalRef(object);
}
}
void JObject::ReleaseObject(JNIEnv* env)
{
if (m_Object != nullptr)
{
env->DeleteGlobalRef(m_Object);
m_Object = nullptr;
}
}
void JObject::AttachLocalObject(JNIEnv* env, jobject object)
{
if (object != nullptr)
{
m_Object = env->NewGlobalRef(object);
env->DeleteLocalRef(object);
}
}
JClass::JClass(const char* className)
: JObject(GetEnvironment()->FindClass(className), /*deleteLocalRef:*/ true)
{
}
JClass::~JClass()
{
}
JString::JString(jstring string, bool removeLocalRef)
: JObject(string, removeLocalRef)
{
}
JString::JString(const char* content)
{
JNIEnv* env = GetEnvironment();
AttachLocalObject(env, env->NewStringUTF(content));
}
JString::JString(const wchar_t* content)
{
JNIEnv* env = GetEnvironment();
AttachLocalObject(env, env->NewString((const jchar *)content, wcslen(content)));
}
JString::~JString()
{
Clear();
}
const char* JString::GetUTFString() const
{
if (m_pString == nullptr)
{
// Logically, this method doesn't change the JString
const_cast<JString*>(this)->m_pString = GetEnvironment()->GetStringUTFChars(String(), nullptr);
}
return m_pString;
}
int JString::GetUTFLength() const
{
return (int)GetEnvironment()->GetStringUTFLength(String());
}
const wchar_t* JString::GetStringChars() const
{
if (m_pWString == nullptr)
{
// Logically, this method doesn't change the JString
const_cast<JString*>(this)->m_pWString = (const wchar_t*)GetEnvironment()->GetStringChars(String(), nullptr);
}
return m_pWString;
}
int JString::GetLength() const
{
return (int)GetEnvironment()->GetStringLength(String());
}
void JString::Clear()
{
if (m_pString != nullptr && String() != nullptr)
{
GetEnvironment()->ReleaseStringUTFChars(String(), m_pString);
m_pString = nullptr;
}
if (m_pWString != nullptr && String() != nullptr)
{
GetEnvironment()->ReleaseStringChars(String(), (const jchar*)m_pWString);
m_pWString = nullptr;
}
}
ManagedPeer::ManagedPeer()
: m_Object(nullptr)
{
}
ManagedPeer::ManagedPeer(jobject object)
: m_Object(object)
{
}
ManagedPeer::~ManagedPeer()
{
}
ManagedPeer& ManagedPeer::operator=(jobject obj)
{
m_Object = obj;
return *this;
}
JNIEnv& ManagedPeer::Env()
{
return *GetEnvironment();
}
} // namespace JNI
| 24.157258
| 121
| 0.59122
|
jessebenson
|
7e249238e151222cbd66c831c38133c8da2bc74d
| 5,968
|
hpp
|
C++
|
include/gct/graphics_pipeline_create_info.hpp
|
Fadis/gct
|
bde211f9336e945e4db21f5abb4ce01dcad78049
|
[
"MIT"
] | 1
|
2022-03-03T09:27:09.000Z
|
2022-03-03T09:27:09.000Z
|
include/gct/graphics_pipeline_create_info.hpp
|
Fadis/gct
|
bde211f9336e945e4db21f5abb4ce01dcad78049
|
[
"MIT"
] | 1
|
2021-12-02T03:45:45.000Z
|
2021-12-03T23:44:37.000Z
|
include/gct/graphics_pipeline_create_info.hpp
|
Fadis/gct
|
bde211f9336e945e4db21f5abb4ce01dcad78049
|
[
"MIT"
] | null | null | null |
#ifndef GCT_GRAPHICS_PIPELINE_CREATE_INFO_HPP
#define GCT_GRAPHICS_PIPELINE_CREATE_INFO_HPP
#include <memory>
#include <optional>
#include <vulkan/vulkan.hpp>
#include <gct/extension.hpp>
#include <gct/pipeline_shader_stage_create_info.hpp>
#include <gct/pipeline_vertex_input_state_create_info.hpp>
#include <gct/pipeline_input_assembly_state_create_info.hpp>
#include <gct/pipeline_tessellation_state_create_info.hpp>
#include <gct/pipeline_viewport_state_create_info.hpp>
#include <gct/pipeline_rasterization_state_create_info.hpp>
#include <gct/pipeline_multisample_state_create_info.hpp>
#include <gct/pipeline_depth_stencil_state_create_info.hpp>
#include <gct/pipeline_color_blend_state_create_info.hpp>
#include <gct/pipeline_dynamic_state_create_info.hpp>
namespace gct {
class pipeline_layout_t;
class render_pass_t;
class graphics_pipeline_create_info_t : public chained_t {
friend void to_json( nlohmann::json &root, const graphics_pipeline_create_info_t &v );
public:
using self_type = graphics_pipeline_create_info_t;
LIBGCT_EXTENSION_REBUILD_CHAIN_DEF
LIBGCT_BASIC_SETTER( vk::GraphicsPipelineCreateInfo )
#ifdef VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::AttachmentSampleCountInfoAMD , attachment_sample_count )
#endif
#ifdef VK_NV_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::GraphicsPipelineShaderGroupsCreateInfoNV , shader_group )
#endif
#if defined(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && defined(VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_EXTENSION_NAME)
LIBGCT_EXTENSION_SETTER( vk::MultiviewPerViewAttributesInfoNVX , multiview_per_view_attributes )
#endif
#ifdef VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineCreationFeedbackCreateInfoEXT, creation_feedback )
#endif
#ifdef VK_AMD_PIPELINE_COMPILER_CONTROL_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineCompilerControlCreateInfoAMD , compiler_control )
#endif
#ifdef VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineDiscardRectangleStateCreateInfoEXT , discard_rectangle )
#endif
#ifdef VK_NV_FRAGMENT_SHADING_RATE_ENUMS_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineFragmentShadingRateEnumStateCreateInfoNV , fragment_shading_rate_nv )
#endif
#ifdef VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineFragmentShadingRateStateCreateInfoKHR, fragment_shading_rate )
#endif
#ifdef VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineRenderingCreateInfoKHR, rendering )
#endif
#ifdef VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
LIBGCT_EXTENSION_SETTER( vk::PipelineRepresentativeFragmentTestStateCreateInfoNV, representative_fragment_test )
#endif
private:
std::vector< pipeline_shader_stage_create_info_t > stage;
std::vector< vk::PipelineShaderStageCreateInfo > raw_stage;
deep_copy_unique_ptr< pipeline_vertex_input_state_create_info_t > vertex_input;
deep_copy_unique_ptr< pipeline_input_assembly_state_create_info_t > input_assembly;
deep_copy_unique_ptr< pipeline_tessellation_state_create_info_t > tessellation;
deep_copy_unique_ptr< pipeline_viewport_state_create_info_t > viewport;
deep_copy_unique_ptr< pipeline_rasterization_state_create_info_t > rasterization;
deep_copy_unique_ptr< pipeline_multisample_state_create_info_t > multisample;
deep_copy_unique_ptr< pipeline_depth_stencil_state_create_info_t > depth_stencil;
deep_copy_unique_ptr< pipeline_color_blend_state_create_info_t > color_blend;
deep_copy_unique_ptr< pipeline_dynamic_state_create_info_t > dynamic;
std::shared_ptr< pipeline_layout_t > layout;
std::shared_ptr< render_pass_t > render_pass;
std::uint32_t subpass = 0u;
public:
graphics_pipeline_create_info_t &add_stage( const pipeline_shader_stage_create_info_t& );
graphics_pipeline_create_info_t &add_stage( const std::shared_ptr< shader_module_t >& );
graphics_pipeline_create_info_t &clear_stage();
graphics_pipeline_create_info_t &set_vertex_input( const pipeline_vertex_input_state_create_info_t& );
graphics_pipeline_create_info_t &clear_vertex_input();
graphics_pipeline_create_info_t &set_input_assembly( const pipeline_input_assembly_state_create_info_t& );
graphics_pipeline_create_info_t &clear_input_assembly();
graphics_pipeline_create_info_t &set_tessellation( const pipeline_tessellation_state_create_info_t& );
graphics_pipeline_create_info_t &clear_tessellation();
graphics_pipeline_create_info_t &set_viewport( const pipeline_viewport_state_create_info_t& );
graphics_pipeline_create_info_t &clear_viewport();
graphics_pipeline_create_info_t &set_rasterization( const pipeline_rasterization_state_create_info_t& );
graphics_pipeline_create_info_t &clear_rasterization();
graphics_pipeline_create_info_t &set_multisample( const pipeline_multisample_state_create_info_t& );
graphics_pipeline_create_info_t &clear_multisample();
graphics_pipeline_create_info_t &set_depth_stencil( const pipeline_depth_stencil_state_create_info_t& );
graphics_pipeline_create_info_t &clear_depth_stencil();
graphics_pipeline_create_info_t &set_color_blend( const pipeline_color_blend_state_create_info_t& );
graphics_pipeline_create_info_t &clear_color_blend();
graphics_pipeline_create_info_t &set_dynamic( const pipeline_dynamic_state_create_info_t& );
graphics_pipeline_create_info_t &clear_dynamic();
graphics_pipeline_create_info_t &set_layout( const std::shared_ptr< pipeline_layout_t >& );
graphics_pipeline_create_info_t &clear_layout();
graphics_pipeline_create_info_t &set_render_pass( const std::shared_ptr< render_pass_t >&, std::uint32_t );
graphics_pipeline_create_info_t &clear_render_pass();
void to_json( nlohmann::json &root );
};
void to_json( nlohmann::json &root, const graphics_pipeline_create_info_t &v );
}
#endif
| 56.838095
| 116
| 0.847185
|
Fadis
|
7e257d7e240a3539b250416a09ef45c6f35ba85d
| 345
|
hpp
|
C++
|
include/di/systems/display/opengl_profile.hpp
|
acdemiralp/nano_engine
|
64069cf300af574efb0c979dbc97eb0a03cdc7a3
|
[
"MIT"
] | 4
|
2021-02-24T14:13:47.000Z
|
2022-02-06T12:02:24.000Z
|
include/di/systems/display/opengl_profile.hpp
|
acdemiralp/nano_engine
|
64069cf300af574efb0c979dbc97eb0a03cdc7a3
|
[
"MIT"
] | 1
|
2018-01-06T11:52:16.000Z
|
2018-01-06T11:52:16.000Z
|
include/di/systems/display/opengl_profile.hpp
|
acdemiralp/nano_engine
|
64069cf300af574efb0c979dbc97eb0a03cdc7a3
|
[
"MIT"
] | 2
|
2018-02-11T14:51:17.000Z
|
2021-02-24T14:13:49.000Z
|
#ifndef DI_SYSTEMS_DISPLAY_OPENGL_PROFILE_HPP_
#define DI_SYSTEMS_DISPLAY_OPENGL_PROFILE_HPP_
#include <SDL2/SDL_video.h>
namespace di
{
enum class opengl_profile
{
core = SDL_GL_CONTEXT_PROFILE_CORE ,
compatibility = SDL_GL_CONTEXT_PROFILE_COMPATIBILITY,
embedded_systems = SDL_GL_CONTEXT_PROFILE_ES
};
}
#endif
| 20.294118
| 58
| 0.77971
|
acdemiralp
|
7e2b55280d92f7dfeaca8cb2e6e15423710fa09d
| 636
|
cpp
|
C++
|
Sources/11XXX/11651/11651.cpp
|
DDManager/Baekjoon-Online-Judge
|
7dd6d76838d3309bfe5bef46f1778c5776ebdf2a
|
[
"MIT"
] | 1
|
2019-07-02T09:07:58.000Z
|
2019-07-02T09:07:58.000Z
|
Sources/11XXX/11651/11651.cpp
|
DDManager/Baekjoon-Online-Judge
|
7dd6d76838d3309bfe5bef46f1778c5776ebdf2a
|
[
"MIT"
] | null | null | null |
Sources/11XXX/11651/11651.cpp
|
DDManager/Baekjoon-Online-Judge
|
7dd6d76838d3309bfe5bef46f1778c5776ebdf2a
|
[
"MIT"
] | 1
|
2022-02-13T04:17:10.000Z
|
2022-02-13T04:17:10.000Z
|
/**
* BOJ 11651번 C++ 소스 코드
* 작성자 : 동동매니저 (DDManager)
*
* ※ 실행 결과
* 사용 메모리 : 1,900 KB / 262,144 KB
* 소요 시간 : 60 ms / 1,000 ms
*
* Copyright 2020. DDManager all rights reserved.
*/
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef struct{
int x,y;
}Point;
bool comp(const Point a,const Point b){
if(a.y==b.y) return a.x<b.x;
return a.y<b.y;
}
int main(void){
int N;
Point *PA;
int i;
scanf("%d",&N);
PA=(Point*)calloc(N,sizeof(Point));
for(i=0;i<N;i++) scanf("%d %d",&PA[i].x,&PA[i].y);
sort(PA,PA+N,comp);
for(i=0;i<N;i++) printf("%d %d\n",PA[i].x,PA[i].y);
return 0;
}
| 17.666667
| 52
| 0.584906
|
DDManager
|
7e2ed3b3ff7340e46e18f1daf504f0c2408c0eee
| 4,692
|
cpp
|
C++
|
src/slam/instance.cpp
|
01org/node-realsense
|
9c000380f61912415c2943a20f8caeb41d579f7b
|
[
"MIT"
] | 12
|
2017-02-27T14:10:12.000Z
|
2017-09-25T08:02:07.000Z
|
src/slam/instance.cpp
|
01org/node-realsense
|
9c000380f61912415c2943a20f8caeb41d579f7b
|
[
"MIT"
] | 209
|
2017-02-22T08:02:38.000Z
|
2017-09-27T09:26:24.000Z
|
src/slam/instance.cpp
|
01org/node-realsense
|
9c000380f61912415c2943a20f8caeb41d579f7b
|
[
"MIT"
] | 18
|
2017-02-22T09:05:42.000Z
|
2017-09-21T07:52:40.000Z
|
// Copyright (c) 2016 Intel Corporation. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include "instance.h"
#include "gen/promise-helper.h"
Instance::Instance() {
}
Instance& Instance::operator=(const Instance& rhs) {
if (&rhs != this) {
this->js_this_.Reset(Nan::New(rhs.js_this_));
}
return *this;
}
Instance::~Instance() {
SlamRunner::DestroySlamRunner();
js_this_.Reset();
}
v8::Handle<v8::Promise> Instance::getCameraOptions() {
return SlamRunner::GetSlamRunner()->getCameraOptions();
}
v8::Handle<v8::Promise> Instance::getInstanceOptions() {
return SlamRunner::GetSlamRunner()->getInstanceOptions();
}
v8::Handle<v8::Promise> Instance::setCameraOptions(
const CameraOptions& options) {
std::string error;
if (!options.CheckType(&error)) {
PromiseHelper promise_helper;
auto promise = promise_helper.CreatePromise();
promise_helper.RejectPromise(error);
return promise;
}
return SlamRunner::GetSlamRunner()->setCameraOptions(options);
}
v8::Handle<v8::Promise> Instance::setInstanceOptions(
const InstanceOptions& options) {
std::string error;
if (!options.CheckType(&error)) {
PromiseHelper promise_helper;
auto promise = promise_helper.CreatePromise();
promise_helper.RejectPromise(error);
return promise;
}
return SlamRunner::GetSlamRunner()->setInstanceOptions(options);
}
v8::Handle<v8::Promise> Instance::setInstanceOptions() {
PromiseHelper promise_helper;
auto promise = promise_helper.CreatePromise();
promise_helper.ResolvePromise();
return promise;
}
v8::Handle<v8::Promise> Instance::start() {
return SlamRunner::GetSlamRunner()->start();
}
v8::Handle<v8::Promise> Instance::stop() {
return SlamRunner::GetSlamRunner()->stop();
}
v8::Handle<v8::Promise> Instance::pause() {
// TODO(widl-nan): fill your code here
}
v8::Handle<v8::Promise> Instance::resume() {
// TODO(widl-nan): fill your code here
}
v8::Handle<v8::Promise> Instance::reset() {
return SlamRunner::GetSlamRunner()->reset();
}
v8::Handle<v8::Promise> Instance::restartTracking() {
return SlamRunner::GetSlamRunner()->restartTracking();
}
v8::Handle<v8::Promise> Instance::getTrackingResult() {
return SlamRunner::GetSlamRunner()->getTrackingResult();
}
v8::Handle<v8::Promise> Instance::getOccupancyMap() {
return SlamRunner::GetSlamRunner()->getOccupancyMap(nullptr);
}
v8::Handle<v8::Promise> Instance::getOccupancyMap(
const RegionOfInterest& roi) {
std::string error;
if (!roi.CheckType(&error)) {
PromiseHelper promise_helper;
auto promise = promise_helper.CreatePromise();
promise_helper.RejectPromise(error);
return promise;
}
return SlamRunner::GetSlamRunner()->getOccupancyMap(&roi);
}
v8::Handle<v8::Promise> Instance::getOccupancyMapAsRgba(
const bool& drawPoseTrajectory, const bool& drawOccupancyMap) {
return SlamRunner::GetSlamRunner()->getOccupancyMapAsRgba(
drawPoseTrajectory, drawOccupancyMap);
}
v8::Handle<v8::Promise> Instance::getOccupancyMapUpdate(
const RegionOfInterest& roi) {
std::string error;
if (!roi.CheckType(&error)) {
PromiseHelper promise_helper;
auto promise = promise_helper.CreatePromise();
promise_helper.RejectPromise(error);
return promise;
}
return SlamRunner::GetSlamRunner()->getOccupancyMapUpdate(&roi);
}
v8::Handle<v8::Promise> Instance::getOccupancyMapUpdate() {
return SlamRunner::GetSlamRunner()->getOccupancyMapUpdate(nullptr);
}
v8::Handle<v8::Promise> Instance::getOccupancyMapBounds() {
return SlamRunner::GetSlamRunner()->getOccupancyMapBounds();
}
v8::Handle<v8::Promise> Instance::loadOccupancyMap(
const std::string& mapFileName) {
return SlamRunner::GetSlamRunner()->loadOccupancyMap(mapFileName);
}
v8::Handle<v8::Promise> Instance::saveOccupancyMap(
const std::string& mapFileName) {
return SlamRunner::GetSlamRunner()->saveOccupancyMap(mapFileName);
}
v8::Handle<v8::Promise> Instance::saveOccupancyMapAsPpm(
const std::string& mapFileName, const bool& drawCameraTrajectory) {
return SlamRunner::GetSlamRunner()->saveOccupancyMapAsPpm(
mapFileName, drawCameraTrajectory);
}
v8::Handle<v8::Promise> Instance::loadRelocalizationMap(
const std::string& mapFileName) {
return SlamRunner::GetSlamRunner()->loadRelocalizationMap(mapFileName);
}
v8::Handle<v8::Promise> Instance::saveRelocalizationMap(
const std::string& mapFileName) {
return SlamRunner::GetSlamRunner()->saveRelocalizationMap(mapFileName);
}
v8::Handle<v8::Promise> Instance::getRelocalizationPose() {
return SlamRunner::GetSlamRunner()->getRelocalizationPose();
}
| 28.609756
| 73
| 0.734015
|
01org
|
7e2ee7a99267f610e6b03bd97bb9fb7424d661bc
| 13,599
|
cpp
|
C++
|
src/plugins/summary/summarywidget.cpp
|
devel29a/leechcraft
|
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
|
[
"BSL-1.0"
] | null | null | null |
src/plugins/summary/summarywidget.cpp
|
devel29a/leechcraft
|
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
|
[
"BSL-1.0"
] | null | null | null |
src/plugins/summary/summarywidget.cpp
|
devel29a/leechcraft
|
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
|
[
"BSL-1.0"
] | null | null | null |
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "summarywidget.h"
#include <QTimer>
#include <QComboBox>
#include <QMenu>
#include <QToolBar>
#include <QMainWindow>
#include <QWidgetAction>
#include <QCloseEvent>
#include <QSortFilterProxyModel>
#include <QLineEdit>
#include <QtDebug>
#include <interfaces/structures.h>
#include <interfaces/ijobholder.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ipluginsmanager.h>
#include <interfaces/core/irootwindowsmanager.h>
#include <interfaces/core/iiconthememanager.h>
#include <interfaces/imwproxy.h>
#include <util/gui/clearlineeditaddon.h>
#include "core.h"
#include "summary.h"
#include "modeldelegate.h"
Q_DECLARE_METATYPE (QMenu*)
namespace LeechCraft
{
namespace Summary
{
QObject *SummaryWidget::S_ParentMultiTabs_ = 0;
class SearchWidget : public QWidget
{
QLineEdit *Edit_;
public:
SearchWidget (SummaryWidget *summary)
: Edit_ (new QLineEdit)
{
auto lay = new QHBoxLayout;
setLayout (lay);
Edit_->setPlaceholderText (SummaryWidget::tr ("Search..."));
Edit_->setMaximumWidth (400);
Edit_->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed);
lay->addStretch ();
lay->addWidget (Edit_, 0, Qt::AlignRight);
new Util::ClearLineEditAddon (Core::Instance ().GetProxy (), Edit_);
connect (Edit_,
SIGNAL (textChanged (QString)),
summary,
SLOT (filterParametersChanged ()));
connect (Edit_,
SIGNAL (returnPressed ()),
summary,
SLOT (feedFilterParameters ()));
}
QString GetText () const
{
return Edit_->text ();
}
void SetText (const QString& text)
{
Edit_->setText (text);
}
};
SummaryWidget::SummaryWidget (QWidget *parent)
: QWidget (parent)
, FilterTimer_ (new QTimer)
, SearchWidget_ (CreateSearchWidget ())
, Toolbar_ (new QToolBar)
, Sorter_ (Core::Instance ().GetTasksModel ())
{
Toolbar_->setWindowTitle ("Summary");
connect (Toolbar_.get (),
SIGNAL (actionTriggered (QAction*)),
this,
SLOT (handleActionTriggered (QAction*)));
Toolbar_->addWidget (SearchWidget_);
Ui_.setupUi (this);
Ui_.PluginsTasksTree_->setItemDelegate (new ModelDelegate (this));
FilterTimer_->setSingleShot (true);
FilterTimer_->setInterval (800);
connect (FilterTimer_,
SIGNAL (timeout ()),
this,
SLOT (feedFilterParameters ()));
Ui_.ControlsDockWidget_->hide ();
auto pm = Core::Instance ().GetProxy ()->GetPluginsManager ();
for (const auto plugin : pm->GetAllCastableRoots<IJobHolder*> ())
ConnectObject (plugin);
Ui_.PluginsTasksTree_->setModel (Sorter_);
connect (Sorter_,
SIGNAL (dataChanged (QModelIndex, QModelIndex)),
this,
SLOT (checkDataChanged (QModelIndex, QModelIndex)));
connect (Sorter_,
SIGNAL (modelAboutToBeReset ()),
this,
SLOT (handleReset ()));
connect (Sorter_,
SIGNAL (rowsAboutToBeRemoved (QModelIndex, int, int)),
this,
SLOT (checkRowsToBeRemoved (QModelIndex, int, int)));
connect (Ui_.PluginsTasksTree_->selectionModel (),
SIGNAL (currentRowChanged (QModelIndex, QModelIndex)),
this,
SLOT (updatePanes (QModelIndex, QModelIndex)));
connect (Ui_.PluginsTasksTree_->selectionModel (),
SIGNAL (currentRowChanged (QModelIndex, QModelIndex)),
this,
SLOT (syncSelection (QModelIndex)),
Qt::QueuedConnection);
const auto itemsHeader = Ui_.PluginsTasksTree_->header ();
const auto& fm = fontMetrics ();
itemsHeader->resizeSection (0,
fm.width ("Average download job or torrent name is just like this."));
itemsHeader->resizeSection (1,
fm.width ("Of the download."));
itemsHeader->resizeSection (2,
fm.width ("99.99% (1024.0 kb from 1024.0 kb at 1024.0 kb/s)"));
ReconnectModelSpecific ();
}
void SummaryWidget::ReconnectModelSpecific ()
{
const auto sel = Ui_.PluginsTasksTree_->selectionModel ();
#define C2(sig,sl,arg1,arg2) \
if (mo->indexOfMethod (QMetaObject::normalizedSignature ("handleTasksTreeSelection" #sl "(" #arg1 ", " #arg2 ")")) != -1) \
connect (sel, \
SIGNAL (sig (arg1, arg2)), \
object, \
SLOT (handleTasksTreeSelection##sl (arg1, arg2)));
auto pm = Core::Instance ().GetProxy ()->GetPluginsManager ();
Q_FOREACH (QObject *object, pm->GetAllCastableRoots<IJobHolder*> ())
{
const auto *mo = object->metaObject ();
C2 (currentChanged, CurrentChanged, QModelIndex, QModelIndex);
C2 (currentColumnChanged, CurrentColumnChanged, QModelIndex, QModelIndex);
C2 (currentRowChanged, CurrentRowChanged, QModelIndex, QModelIndex);
}
#undef C2
}
void SummaryWidget::ConnectObject (QObject *object)
{
const auto *mo = object->metaObject ();
#define C1(sig,sl,arg) \
if (mo->indexOfMethod (QMetaObject::normalizedSignature ("handleTasksTree" #sl "(" #arg ")")) != -1) \
connect (Ui_.PluginsTasksTree_, \
SIGNAL (sig (arg)), \
object, \
SLOT (handleTasksTree##sl (arg)));
C1 (activated, Activated, QModelIndex);
C1 (clicked, Clicked, QModelIndex);
C1 (doubleClicked, DoubleClicked, QModelIndex);
C1 (entered, Entered, QModelIndex);
C1 (pressed, Pressed, QModelIndex);
C1 (viewportEntered, ViewportEntered, );
#undef C1
}
SummaryWidget::~SummaryWidget ()
{
Toolbar_->clear ();
QWidget *widget = Ui_.ControlsDockWidget_->widget ();
Ui_.ControlsDockWidget_->setWidget (0);
if (widget)
widget->setParent (0);
delete Sorter_;
}
void SummaryWidget::SetParentMultiTabs (QObject *parent)
{
S_ParentMultiTabs_ = parent;
}
void SummaryWidget::Remove ()
{
emit needToClose ();
}
QToolBar* SummaryWidget::GetToolBar () const
{
return Toolbar_.get ();
}
QList<QAction*> SummaryWidget::GetTabBarContextMenuActions () const
{
return QList<QAction*> ();
}
QObject* SummaryWidget::ParentMultiTabs ()
{
return S_ParentMultiTabs_;
}
TabClassInfo SummaryWidget::GetTabClassInfo () const
{
return qobject_cast<Summary*> (S_ParentMultiTabs_)->GetTabClasses ().first ();
}
SearchWidget* SummaryWidget::CreateSearchWidget ()
{
return new SearchWidget (this);
}
void SummaryWidget::ReinitToolbar ()
{
Q_FOREACH (QAction *action, Toolbar_->actions ())
{
auto wa = qobject_cast<QWidgetAction*> (action);
if (!wa || wa->defaultWidget () != SearchWidget_)
{
Toolbar_->removeAction (action);
delete action;
}
else if (wa->defaultWidget () != SearchWidget_)
Toolbar_->removeAction (action);
}
}
QList<QAction*> SummaryWidget::CreateProxyActions (const QList<QAction*>& actions, QObject *parent) const
{
QList<QAction*> proxies;
Q_FOREACH (QAction *action, actions)
{
if (qobject_cast<QWidgetAction*> (action))
{
proxies << action;
continue;
}
QAction *pa = new QAction (action->icon (), action->text (), parent);
if (action->isSeparator ())
pa->setSeparator (true);
else
{
pa->setCheckable (action->isCheckable ());
pa->setChecked (action->isChecked ());
pa->setShortcuts (action->shortcuts ());
pa->setStatusTip (action->statusTip ());
pa->setToolTip (action->toolTip ());
pa->setWhatsThis (action->whatsThis ());
pa->setData (QVariant::fromValue<QObject*> (action));
connect (pa,
SIGNAL (hovered ()),
action,
SIGNAL (hovered ()));
connect (pa,
SIGNAL (toggled (bool)),
action,
SIGNAL (toggled (bool)));
}
proxies << pa;
}
return proxies;
}
QByteArray SummaryWidget::GetTabRecoverData () const
{
QByteArray result;
QDataStream out (&result, QIODevice::WriteOnly);
out << static_cast<quint8> (1);
return result;
}
QString SummaryWidget::GetTabRecoverName () const
{
return GetTabClassInfo ().VisibleName_;
}
QIcon SummaryWidget::GetTabRecoverIcon () const
{
return GetTabClassInfo ().Icon_;
}
void SummaryWidget::RestoreState (const QByteArray& data)
{
QDataStream in (data);
quint8 version = 0;
in >> version;
if (version != 1)
{
qWarning () << Q_FUNC_INFO
<< "unknown version";
return;
}
}
void SummaryWidget::SetUpdatesEnabled (bool)
{
// TODO implement this
}
Ui::SummaryWidget SummaryWidget::GetUi () const
{
return Ui_;
}
void SummaryWidget::handleActionTriggered (QAction *proxyAction)
{
QAction *action = qobject_cast<QAction*> (proxyAction->
data ().value<QObject*> ());
QItemSelectionModel *selModel =
Ui_.PluginsTasksTree_->selectionModel ();
QModelIndexList indexes = selModel->selectedRows ();
action->setProperty ("SelectedRows",
QVariant::fromValue<QList<QModelIndex>> (indexes));
action->setProperty ("ItemSelectionModel",
QVariant::fromValue<QObject*> (selModel));
action->activate (QAction::Trigger);
}
void SummaryWidget::checkDataChanged (const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
const QModelIndex& cur = Ui_.PluginsTasksTree_->
selectionModel ()->currentIndex ();
if (topLeft.row () <= cur.row () && bottomRight.row () >= cur.row ())
updatePanes (cur, cur);
}
void SummaryWidget::handleReset ()
{
Ui_.PluginsTasksTree_->selectionModel ()->clear ();
}
void SummaryWidget::checkRowsToBeRemoved (const QModelIndex&, int begin, int end)
{
const QModelIndex& cur = Ui_.PluginsTasksTree_->
selectionModel ()->currentIndex ();
if (begin <= cur.row () && end >= cur.row ())
Ui_.PluginsTasksTree_->selectionModel ()->clear ();
}
void SummaryWidget::updatePanes (const QModelIndex& newIndex, const QModelIndex& oldIndex)
{
QToolBar *controls = Core::Instance ().GetControls (newIndex);
QWidget *addiInfo = Core::Instance ().GetAdditionalInfo (newIndex);
if (oldIndex.isValid () &&
addiInfo != Ui_.ControlsDockWidget_->widget ())
Ui_.ControlsDockWidget_->hide ();
if (Core::Instance ().SameModel (newIndex, oldIndex))
return;
ReinitToolbar ();
if (newIndex.isValid ())
{
if (controls)
{
Q_FOREACH (QAction *action, controls->actions ())
{
QString ai = action->property ("ActionIcon").toString ();
if (!ai.isEmpty () &&
action->icon ().isNull ())
action->setIcon (Core::Instance ().GetProxy ()->
GetIconThemeManager ()->GetIcon (ai));
}
const auto& proxies = CreateProxyActions (controls->actions (), Toolbar_.get ());
Toolbar_->insertActions (Toolbar_->actions ().first (), proxies);
}
if (addiInfo != Ui_.ControlsDockWidget_->widget ())
Ui_.ControlsDockWidget_->setWidget (addiInfo);
if (addiInfo)
{
Ui_.ControlsDockWidget_->show ();
Core::Instance ().GetProxy ()->GetIconThemeManager ()->
UpdateIconset (addiInfo->findChildren<QAction*> ());
}
}
}
void SummaryWidget::filterParametersChanged ()
{
FilterTimer_->stop ();
FilterTimer_->start ();
}
void SummaryWidget::filterReturnPressed ()
{
FilterTimer_->stop ();
feedFilterParameters ();
}
void SummaryWidget::feedFilterParameters ()
{
Sorter_->setFilterFixedString (SearchWidget_->GetText ());
}
void SummaryWidget::on_PluginsTasksTree__customContextMenuRequested (const QPoint& pos)
{
QModelIndex current = Ui_.PluginsTasksTree_->currentIndex ();
QMenu *sourceMenu = current.data (RoleContextMenu).value<QMenu*> ();
if (!sourceMenu)
return;
QMenu *menu = new QMenu ();
connect (menu,
SIGNAL (triggered (QAction*)),
this,
SLOT (handleActionTriggered (QAction*)));
menu->setAttribute (Qt::WA_DeleteOnClose, true);
menu->addActions (CreateProxyActions (sourceMenu->actions (), menu));
menu->setTitle (sourceMenu->title ());
menu->popup (Ui_.PluginsTasksTree_->viewport ()->mapToGlobal (pos));
}
void SummaryWidget::syncSelection (const QModelIndex& current)
{
QItemSelectionModel *selm = Ui_.PluginsTasksTree_->selectionModel ();
const QModelIndex& now = selm->currentIndex ();
if (current != now ||
(now.isValid () &&
!selm->rowIntersectsSelection (now.row (), QModelIndex ())))
{
selm->select (now, QItemSelectionModel::ClearAndSelect |
QItemSelectionModel::Rows);
updatePanes (now, current);
}
}
}
}
| 28.390397
| 125
| 0.686521
|
devel29a
|
7e3044e1f0bee2fa979528e79a9b8a20527e7894
| 910
|
hpp
|
C++
|
mod08/ex02/mutantStack.hpp
|
paozer/piscine_cpp
|
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
|
[
"Unlicense"
] | null | null | null |
mod08/ex02/mutantStack.hpp
|
paozer/piscine_cpp
|
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
|
[
"Unlicense"
] | null | null | null |
mod08/ex02/mutantStack.hpp
|
paozer/piscine_cpp
|
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
|
[
"Unlicense"
] | 2
|
2021-01-31T13:52:11.000Z
|
2021-05-19T18:36:17.000Z
|
#pragma once
#ifndef MUTANTSTACK_HPP
#define MUTANTSTACK_HPP
#include <iterator>
#include <deque>
#include <stack>
template <typename T, typename Container = std::deque<T> >
class mutantStack : public std::stack<T, Container>
{
public:
mutantStack() {}
mutantStack(const mutantStack & other) { *this = other; }
~mutantStack() {}
mutantStack & operator=(const mutantStack & other)
{
// in stack class definition c is the underlying container here deque
if (this != &other)
std::stack<T, Container>::c = other.std::stack<T, Container>::c;
return *this;
}
typedef typename Container::iterator iterator; // necessary for mutantStack<T>::iterator
iterator begin() { return std::stack<T, Container>::c.begin(); }
iterator end() { return std::stack<T, Container>::c.end(); }
};
#endif
| 30.333333
| 96
| 0.617582
|
paozer
|
7e305c2400bc8774a10c5cc9dec4757f2847085b
| 1,031
|
hpp
|
C++
|
RayCharles/Sphere.hpp
|
CoderGirl42/RayTracer
|
4e370864ec6b9c02ea030a9cbe4354b2d55f3aba
|
[
"MIT"
] | null | null | null |
RayCharles/Sphere.hpp
|
CoderGirl42/RayTracer
|
4e370864ec6b9c02ea030a9cbe4354b2d55f3aba
|
[
"MIT"
] | null | null | null |
RayCharles/Sphere.hpp
|
CoderGirl42/RayTracer
|
4e370864ec6b9c02ea030a9cbe4354b2d55f3aba
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Entity.hpp"
class _MMX_ALIGN_ Sphere : public Entity
{
public:
Sphere() {}
Sphere(const Vec3& c, real r) : Center(c), Radius(r) {};
virtual bool Hit(const Ray& r, real t_min, real t_max, HitRecord& rec);
Vec3 Center;
real Radius;
Entity *Entity;
};
bool Sphere::Hit(const Ray& r, real t_min, real t_max, HitRecord& rec)
{
Vec3 oc = r.Origin() - Center;
real a = r.Direction().Dot(r.Direction());
real b = oc.Dot(r.Direction());
real c = oc.Dot(oc) - Radius * Radius;
real discriminant = b * b - a * c;
if (discriminant > 0)
{
float temp = (-b - SQRT(b * b - a * c)) / a;
if (temp < t_max && temp > t_min)
{
rec.t = temp;
rec.p = r.PointAtParameter(rec.t);
rec.normal = (rec.p - Center) / Radius;
rec.e = this;
return true;
}
temp = (-b + SQRT(b * b - a * c)) / a;
if (temp < t_max && temp > t_min)
{
rec.t = temp;
rec.p = r.PointAtParameter(rec.t);
rec.normal = (rec.p - Center) / Radius;
rec.e = this;
return true;
}
}
return false;
}
| 19.092593
| 72
| 0.587779
|
CoderGirl42
|
cce1758fd8acd349c852f95809bfb32fcc86af24
| 51,552
|
cpp
|
C++
|
solarpilot/Toolbox.cpp
|
rchintala13/ssc
|
3424d9b1bfab50cc11d1895d0893cf1771fd3a5e
|
[
"BSD-3-Clause"
] | null | null | null |
solarpilot/Toolbox.cpp
|
rchintala13/ssc
|
3424d9b1bfab50cc11d1895d0893cf1771fd3a5e
|
[
"BSD-3-Clause"
] | null | null | null |
solarpilot/Toolbox.cpp
|
rchintala13/ssc
|
3424d9b1bfab50cc11d1895d0893cf1771fd3a5e
|
[
"BSD-3-Clause"
] | 1
|
2017-10-01T08:36:05.000Z
|
2017-10-01T08:36:05.000Z
|
/**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "math.h"
#include <stdio.h>
#include <ctime>
#include <vector>
#include <algorithm>
#include "Toolbox.h"
#include "definitions.h"
using namespace std;
// ----------- points and vectors -----------------------
sp_point::sp_point(){};
sp_point::sp_point( const sp_point &P )
: x(P.x), y(P.y), z(P.z)
{
}
sp_point::sp_point(double X, double Y, double Z)
: x(X), y(Y), z(Z)
{
}
void sp_point::Set(double _x, double _y, double _z)
{
this->x = _x;
this->y = _y;
this->z = _z;
}
void sp_point::Set( sp_point &P )
{
this->x = P.x;
this->y = P.y;
this->z = P.z;
}
void sp_point::Add( sp_point &P )
{
this->x+=P.x;
this->y+=P.y;
this->z+=P.z;
}
void sp_point::Add(double _x, double _y, double _z)
{
this->x += _x;
this->y += _y;
this->z += _z;
}
void sp_point::Subtract( sp_point &P )
{
this->x += -P.x;
this->y += -P.y;
this->z += -P.z;
}
double& sp_point::operator [](const int &index){
switch (index)
{
case 0:
return x;
break;
case 1:
return y;
break;
case 2:
return z;
break;
default:
throw spexception("Index out of range in sp_point()");
break;
}
};
bool sp_point::operator <(const sp_point &p) const {
return this->x < p.x || (this->x == p.x && this->y < p.y);
};
Vect::Vect(){};
Vect::Vect( const Vect &V )
: i(V.i), j(V.j), k(V.k)
{}
Vect::Vect(double i, double j, double k )
: i(i), j(j), k(k)
{
}
void Vect::Set(double _i, double _j, double _k)
{
i=_i;
j=_j;
k=_k;
}
void Vect::Set( Vect &V )
{
i = V.i;
j = V.j;
k = V.k;
}
void Vect::Add( Vect &V )
{
i+=V.i;
j+=V.j;
k+=V.k;
}
void Vect::Subtract( Vect &V )
{
i+=-V.i;
j+=-V.j;
k+=-V.k;
}
void Vect::Add(double _i, double _j, double _k)
{
i+=_i;
j+=_j;
k+=_k;
}
void Vect::Scale( double m )
{
i *= m;
j *= m;
k *= m;
}
double &Vect::operator[](int index){
if( index == 0) return i;
if( index == 1) return j;
if( index == 2) return k;
throw spexception("Index out of range in Vect()"); //range error
};
PointVect::PointVect(const PointVect &v){
x = v.x; y=v.y; z=v.z;
i = v.i; j=v.j; k=v.k;
}
PointVect& PointVect::operator= (const PointVect &v) {
x = v.x; y=v.y; z=v.z;
i = v.i; j=v.j; k=v.k;
return *this;
}
PointVect::PointVect(double px, double py, double pz, double vi, double vj, double vk)
{
x=px; y=py; z=pz; i=vi; j=vj; k=vk;
}
sp_point *PointVect::point()
{
p.Set(x, y, z);
return &p;
};
Vect *PointVect::vect()
{
v.Set(i, j, k);
return &v;
};
//-------------------------------------------------------
//------------------ DTObj class -------------------------------------
DTobj::DTobj()
{
setZero();
}
void DTobj::setZero()
{
_year=0;
_month=0;
_yday=0;
_mday=0;
_wday=0;
_hour=0;
_min=0;
_sec=0;
_ms=0;
}
DTobj *DTobj::Now()
{
struct tm now;
#ifdef _MSC_VER
__time64_t long_time;
// Get time as 64-bit integer.
_time64( &long_time );
// Convert to local time.
_localtime64_s( &now, &long_time );
#else
time_t long_time;
// Get time as 64-bit integer.
time( &long_time );
// Convert to local time.
now = *localtime(&long_time);
#endif
_year=now.tm_year+1900;
_month=now.tm_mon;
_yday=now.tm_yday;
_mday=now.tm_mday;
_wday=now.tm_wday;
_hour=now.tm_hour;
_min=now.tm_min;
_sec=now.tm_sec;
_ms=0;
return this;
}
//-------------------------------------------------------
//-----------------------DateTime class-------------------
//accessors
//GETS
int DateTime::GetYear(){return _year;}
int DateTime::GetMonth(){return _month;}
int DateTime::GetYearDay(){return _yday;};
int DateTime::GetMonthDay(){return _mday;}
int DateTime::GetWeekDay(){return _wday;}
int DateTime::GetMinute(){return _min;};
int DateTime::GetSecond() {return _sec;};
int DateTime::GetMillisecond(){return _ms;};
// SETS
void DateTime::SetYear(const int val){_year=val; SetMonthLengths(_year);}
void DateTime::SetMonth(const int val){_month=val;}
void DateTime::SetYearDay(const int val){_yday=val;}
void DateTime::SetMonthDay(const int val){_mday=val;}
void DateTime::SetWeekDay(const int val){_wday=val;}
void DateTime::SetHour(const int val){_hour=val;}
void DateTime::SetMinute(const int val){_min=val;}
void DateTime::SetSecond(const int val){_sec=val;}
void DateTime::SetMillisecond(const int val){_ms=val;}
//Default constructor
DateTime::DateTime(){
//Initialize all variables to the current date and time
setDefaults();
}
DateTime::DateTime(double doy, double hour){
//Convert from fractional hours to integer values for hr, min, sec
int hr = int(floor(hour));
double minutes = 60. * (hour - double(hr));
int min = int(floor(minutes));
int sec = int(60.*(minutes - double(min)));
setZero(); //Zero values
SetYearDay(int(doy+.001)); //day of the year
SetHour(hr);
SetMinute(min);
SetSecond(sec);
}
//Fully specified constructor
DateTime::DateTime(DTobj &DT)
{
_year=DT._year; _month=DT._month; _yday=DT._yday; _mday=DT._mday; _wday=DT._wday;
_hour=DT._hour; _min=DT._min; _sec=DT._sec; _ms=DT._ms;
//Initialize the month lengths array
SetMonthLengths(_year);
}
void DateTime::setDefaults(){
setZero(); //everything zeros but the day of year and year (hr=12 is noon)
//Get the current year and set it as the default value
DTobj N;
N.Now();
//SetYear(N._year);
SetYear(2011); //Choose a non-leap year
SetMonth(6);
SetMonthDay(21);
SetYearDay( GetDayOfYear() ); //Summer solstice
SetHour(12);
}
void DateTime::SetDate(int year, int month, int day)
{
//Given a year, month (1-12), and day of the month (1-N), set the values. Leave the time as it is
SetYear(year);
SetMonth(month);
SetMonthDay(day);
SetMonthLengths(_year);
SetYearDay( GetDayOfYear(year, month, day) );
}
void DateTime::SetMonthLengths(const int year){
/* Calculate the number of days in each month and assign the result to the monthLength[] array.
Provide special handling for 4-year, 100-year, and 400-year leap years.*/
//Initialize the array of month lengths (accounting for leap year)
for (int i=0; i<12; i+=2){ monthLength[i]=31; };
for (int i=1; i<12; i+=2){ monthLength[i]=30; };
//Given the year, determine how many days are in Feb.
monthLength[1]=28; //Default
if(year%4==0) {monthLength[1]=29;} //All years divisible by 4 are leap years
if(year%100==0){ //All years divisible by 100 are not leap years, unless...
if(year%400 == 0){monthLength[1]=29;} //.. the year is also divisible by 400.
else {monthLength[1]=28;}
};
}
int DateTime::GetDayOfYear(){
int val = GetDayOfYear(_year, _month, _mday);
return val;
}
int DateTime::GetDayOfYear(int /*year*/, int month, int mday){
//Return the day of the year specified by the class day/month/year class members
//Day of the year runs from 1-365
int doy=0;
if(month>1) { for (int i=0; i<month-1; i++) {doy+=monthLength[i];}; };
doy+= mday;
return doy;
}
int DateTime::CalculateDayOfYear( int year, int month, int mday ){ //Static version
int monthLength[12];
//Initialize the array of month lengths (accounting for leap year)
for (int i=0; i<12; i+=2){ monthLength[i]=31; };
for (int i=1; i<12; i+=2){ monthLength[i]=30; };
//Given the year, determine how many days are in Feb.
monthLength[1]=28; //Default
if(year%4==0) {monthLength[1]=29;} //All years divisible by 4 are leap years
if(year%100==0){ //All years divisible by 100 are not leap years, unless...
if(year%400 == 0){monthLength[1]=29;} //.. the year is also divisible by 400.
else {monthLength[1]=28;}
};
int doy=0;
if(month>1) { for (int i=0; i<month-1; i++) {doy+=monthLength[i];}; };
doy+= mday;
return doy;
}
int DateTime::GetHourOfYear(){
//Return the hour of the year according to the values specified by the class members
int doy = GetDayOfYear();
int hr = (doy-1)*24 + _hour;
return hr;
};
void DateTime::hours_to_date(double hours, int &month, int &day_of_month){
/*
Take hour of the year (0-8759) and convert it to month and day of the month.
If the year is not provided, the default is 2011 (no leap year)
Month = 1-12
Day = 1-365
The monthLength[] array contains the number of days in each month.
This array is taken from the DateTime class and accounts for leap years.
To modify the year to not include leap year days, change the year in the
DateTime instance.
*/
double days = hours/24.;
int dsum=0;
for(int i=0; i<12; i++){
dsum += monthLength[i];
if(days <= dsum){month = i+1; break;}
}
day_of_month = (int)floor(days - (dsum - monthLength[month-1]))+1;
}
std::string DateTime::GetMonthName(int month){
switch(month)
{
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
return "";
}
}
//---------Weather data object class --------------------
//Copy constructor
WeatherData::WeatherData( const WeatherData &wd) :
_N_items( wd._N_items ),
Day( wd.Day ),
Hour( wd.Hour ),
Month( wd.Month ),
DNI( wd.DNI ),
T_db( wd.T_db ),
Pres( wd.Pres ),
V_wind( wd.V_wind ),
Step_weight( wd.Step_weight )
{
//Recreate the pointer array
initPointers();
}
WeatherData::WeatherData(){
initPointers();
};
void WeatherData::initPointers(){
//On initialization, create a vector of pointers to all of the data arrays
v_ptrs.resize(8);
v_ptrs.at(0) = &Day;
v_ptrs.at(1) = &Hour;
v_ptrs.at(2) = &Month;
v_ptrs.at(3) = &DNI;
v_ptrs.at(4) = &T_db;
v_ptrs.at(5) = &Pres;
v_ptrs.at(6) = &V_wind;
v_ptrs.at(7) = &Step_weight;
//Initialize the number of items
_N_items = (int)Day.size();
}
void WeatherData::resizeAll(int size, double val){
for(unsigned int i=0; i<v_ptrs.size(); i++){
v_ptrs.at(i)->resize(size, val);
_N_items = size;
}
};
void WeatherData::clear()
{
for(unsigned int i=0; i<v_ptrs.size(); i++){
v_ptrs.at(i)->clear();
_N_items = 0;
}
}
void WeatherData::getStep(int step, double &day, double &hour, double &dni, double &step_weight){
//retrieve weather data from the desired time step
day = Day.at(step);
hour = Hour.at(step);
dni = DNI.at(step);
step_weight = Step_weight.at(step);
}
void WeatherData::getStep(int step, double &day, double &hour, double &month, double &dni,
double &tdb, double &pres, double &vwind, double &step_weight){
double *args[] = {&day, &hour, &month, &dni, &tdb, &pres, &vwind, &step_weight};
//retrieve weather data from the desired time step
for(unsigned int i=0; i<v_ptrs.size(); i++){
*args[i] = v_ptrs.at(i)->at(step);
}
}
void WeatherData::append(double day, double hour, double dni, double step_weight){
Day.push_back(day);
Hour.push_back( hour );
DNI.push_back( dni );
Step_weight.push_back( step_weight );
_N_items ++;
}
void WeatherData::append(double day, double hour, double month, double dni,
double tdb, double pres, double vwind, double step_weight){
Day.push_back( day );
Hour.push_back( hour );
Month.push_back( month );
DNI.push_back( dni );
T_db.push_back( tdb );
Pres.push_back( pres );
V_wind.push_back( vwind );
Step_weight.push_back( step_weight );
_N_items ++;
}
void WeatherData::setStep(int step, double day, double hour, double dni, double step_weight){
Day.at(step) = day;
Hour.at(step) = hour;
DNI.at(step) = dni;
Step_weight.at(step) = step_weight;
}
void WeatherData::setStep(int step, double day, double hour, double month, double dni,
double tdb, double pres, double vwind, double step_weight){
Day.at(step) = day;
Hour.at(step) = hour;
Month.at(step) = month;
DNI.at(step) = dni;
T_db.at(step) = tdb;
Pres.at(step) = pres;
V_wind.at(step) = vwind;
Step_weight.at(step) = step_weight;
}
std::vector<std::vector<double>*> *WeatherData::getEntryPointers()
{
return &v_ptrs;
}
//-----------------------Toolbox namespace--------------------
//misc
double Toolbox::round(double x){
return fabs(x - ceil(x)) > 0.5 ? floor(x) : ceil(x);
}
void Toolbox::writeMatD(string dir, string name, matrix_t<double> &mat, bool clear){
//write the data to a log file
FILE *file;
//ofstream file;
string path;
path.append(dir);
path.append("\\matrix_data_log.txt");
if( clear ) {
file = fopen(path.c_str(), "w");
}
else{
file = fopen(path.c_str(), "a");
}
int nr = (int)mat.nrows();
int nc = (int)mat.ncols();
fprintf(file, "%s\n", name.c_str());
for (int i=0; i<nr; i++){
for (int j=0; j<nc; j++){
fprintf(file, "%e\t", mat.at(i,j));
}
fprintf(file, "%s", "\n");
}
fprintf(file, "%s", "\n");
fclose(file);
}
void Toolbox::writeMatD(string dir, string name, block_t<double> &mat, bool clear){
//write the data to a log file
FILE *file;
//ofstream file;
string path;
path.append(dir);
path.append("\\matrix_data_log.txt");
if( clear ) {
file =fopen(path.c_str(), "w");
}
else{
file =fopen(path.c_str(), "a");
}
int nr = (int)mat.nrows();
int nc = (int)mat.ncols();
int nl = (int)mat.nlayers();
fprintf(file, "%s\n", name.c_str());
for (int k=0; k<nl; k++){
fprintf(file, "%i%s", k, "--\n");
for (int i=0; i<nr; i++){
for (int j=0; j<nc; j++){
fprintf(file, "%e\t", mat.at(i,j,k));
}
fprintf(file, "%s", "\n");
}
}
fprintf(file, "%s", "\n");
fclose(file);
}
void Toolbox::swap(double &a, double &b){
//Swap the values in A and B
double xt = a;
a = b;
b = xt;
}
void Toolbox::swap(double *a, double *b){
double xt = *a;
*a = *b;
*b = xt;
}
double Toolbox::atan3(double &x, double &y){
double v = atan2(x,y);
return v < 0. ? v += 2.*PI : v;
}
void Toolbox::map_profiles(double *source, int nsource, double *dest, int ndest, double *weights){
/*
Take a source array 'source(nsource)' and map the values to 'dest(ndest)'.
This method creates an integral-conserved map of values in 'dest' that may have a
different number of elements than 'source'. The size of each node within 'source'
is optionally specified by the 'weights(nsource)' array. If all elements are of the
same size, set weights=(double*)NULL or omit the optional argument.
*/
double *wsize;
double wtot = 0.;
if(weights != (double*)NULL){
wsize = new double[nsource];
for(int i=0; i<nsource; i++){
wtot += weights[i]; //sum up weights
wsize[i] = weights[i];
}
}
else{
wsize = new double[nsource];
for(int i=0; i<nsource; i++)
wsize[i] = 1.;
wtot = (double)nsource;
}
double delta_D = wtot/(double)ndest;
int i=0;
double ix = 0.;
for(int j=0; j<ndest; j++){
dest[j] = 0.;
double
jx = (double)(j+1)*delta_D,
jx0 = (double)j*delta_D;
//From previous step
if(ix-jx0>0)
dest[j] += (ix-jx0)*source[i-1];
//internal steps
while(ix < jx ){
ix += wsize[i];
dest[j] += wsize[i] * source[i];
i++;
}
//subtract overage
if(ix > jx )
dest[j] += -(ix-jx)*source[i-1];
//Divide by length
dest[j] *= 1./delta_D;
}
//Memory cleanup
delete [] wsize;
}
/* Factorial of an integer x*/
int Toolbox::factorial(int x) {
//if (floor(3.2)!=x) { cout << "Factorial must be an integer!" };
int f = x;
for (int i=1; i<x; i++) {
int j=x-i;
f=f*j;
}
if(f<1) f=1; //Minimum of any factorial is 1
return f;
}
double Toolbox::factorial_d(int x) {
//returns the same as factorial, but with a doub value
return double(factorial(x));
}
bool Toolbox::pointInPolygon( const vector< sp_point > &poly, const sp_point &pt) {
/* This subroutine takes a polynomial array containing L_poly vertices (X,Y,Z) and a
single point (X,Y,Z) and determines whether the point lies within the polygon. If so,
the algorithm returns TRUE (otherwise FALSE) */
//if polywind returns a number between -1 and 1, the point is in the polygon
int wind = polywind(poly, pt);
if (wind == -1 || wind == 1) { return true;}
else {return false;}
}
vector<sp_point> Toolbox::projectPolygon(vector<sp_point> &poly, PointVect &plane) {
/* Take a polygon with points in three dimensions (X,Y,Z) and project all points onto a plane defined
by the point-vector {x,y,z,i,j,k}. The subroutine returns a new polygon with the adjusted points all
lying on the plane. The points are also assigned vector values corresponding to the normal vector
of the plane that they lie in.*/
//Declare variables
double dist, A, B, C, D;
sp_point pt;
//Declare a new polygon of type vector
int Lpoly = (int)poly.size();
vector< sp_point > FPoly(Lpoly);
//Determine the coefficients for the equation of the plane {A,B,C,D}
A=plane.i; B=plane.j; C=plane.k;
Vect uplane; uplane.Set(A,B,C); vectmag(uplane);
D = -A*plane.x - B*plane.y - C*plane.z;
for (int i=0; i<Lpoly; i++) {
//Determine the distance between the point and the plane
pt = poly.at(i);
dist = -(A*pt.x + B*pt.y + C*pt.z + D)/vectmag(*plane.vect());
//knowing the distance, now shift the point to the plane
FPoly.at(i).x = pt.x+dist*A;
FPoly.at(i).y = pt.y+dist*B;
FPoly.at(i).z = pt.z+dist*C;
}
return FPoly;
}
int Toolbox::polywind( const vector<sp_point> &vt, const sp_point &pt) {
/*
Determine the winding number of a polygon with respect to a point. This helps
calculate the inclusion/exclusion of the point inside the polygon. If the point is
inside the polygon, the winding number is equal to -1 or 1.
*/
//Declarations
int i, np, wind = 0, which_ign;
double
d0=0.,
d1=0.,
p0=0.,
p1=0.,
pt0=0.,
pt1=0.;
/*The 2D polywind function can be mapped to 3D polygons by choosing a single dimension to
ignore. The best ignored dimension corresponds to the largest magnitude component of the
normal vector to the plane containing the polygon.*/
//Get the cross product of the first three points in the polygon to determine the planar normal vector
Vect v1, v2;
v1.Set((vt.at(0).x-vt.at(1).x),(vt.at(0).y - vt.at(1).y),(vt.at(0).z - vt.at(1).z));
v2.Set((vt.at(2).x-vt.at(1).x),(vt.at(2).y - vt.at(1).y),(vt.at(2).z - vt.at(1).z));
Vect pn = crossprod( v1, v2 );
which_ign = 1;
if(fabs(pn.j) > fabs(pn.i)) {which_ign=1;}
if(fabs(pn.k) > fabs(pn.j)) {which_ign=2;}
if(fabs(pn.i) > fabs(pn.k)) {which_ign=0;}
/* Return the winding number of a polygon (specified by a vector of vertex points vt)
around an arbitrary point pt.*/
np = (int)vt.size();
switch (which_ign) {
case 0:
pt0 = pt.y; pt1 = pt.z;
p0 = vt[np-1].y; p1 = vt[np-1].z;
break;
case 1:
pt0 = pt.x; pt1 = pt.z;
p0 = vt[np-1].x; p1 = vt[np-1].z;
break;
case 2:
pt0 = pt.x; pt1 = pt.y;
p0 = vt[np-1].x; p1 = vt[np-1].y;
}
for (i=0; i<np; i++) {
switch (which_ign) {
case 0:
d0 = vt[i].y; d1 = vt[i].z;
break;
case 1:
d0 = vt[i].x; d1 = vt[i].z;
break;
case 2:
d0 = vt[i].x; d1 = vt[i].y;
}
if (p1 <= pt1) {
if (d1 > pt1 && (p0-pt0)*(d1-pt1)-(p1-pt1)*(d0-pt0) > 0) wind++;
}
else {
if (d1 <= pt1 && (p0-pt0)*(d1-pt1)-(p1-pt1)*(d0-pt0) < 0) wind--;
}
p0=d0;
p1=d1;
}
return wind;
}
Vect Toolbox::crossprod(const Vect &A, const Vect &B) {
/* Calculate the cross product of two vectors. The magnitude of the cross product
represents the area contained in a parallelogram bounded by the multipled vectors.*/
Vect res;
res.i = A.j*B.k - A.k*B.j;
res.j = A.k*B.i - A.i*B.k;
res.k = A.i*B.j - A.j*B.i;
return res;
};
double Toolbox::crossprod(const sp_point &O, const sp_point &A, const sp_point &B)
{
//2D cross-product of vectors OA and OB.
return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}
void Toolbox::unitvect(Vect &A) {
/*Take a vector that may or may not be in unit vector form and scale the magnitude to
make it a unit vector*/
double M = vectmag(A);
if(M==0.){A.i=0; A.j=0; A.k=0; return;}
A.i /= M; A.j /= M; A.k /= M; return;
}
double Toolbox::dotprod(const Vect &A, const Vect &B)
{
return (A.i * B.i + A.j * B.j + A.k * B.k);
}
double Toolbox::dotprod(const Vect &A, const sp_point &B)
{
return (A.i * B.x + A.j * B.y + A.k * B.z);
}
double Toolbox::vectmag(const Vect &A)
{
return sqrt(pow(A.i,2) + pow(A.j,2) + pow(A.k,2));
}
double Toolbox::vectmag(const sp_point &P){
return sqrt( pow(P.x,2) + pow(P.y,2) + pow(P.z,3) );
}
double Toolbox::vectmag(double i, double j, double k){
return sqrt( pow(i,2) + pow(j,2) + pow(k,2) );
}
double Toolbox::vectangle(const Vect &A, const Vect&B)
{
//Determine the angle between two vectors
return acos(dotprod(A,B)/(vectmag(A)*vectmag(B)));
}
void Toolbox::rotation(double theta, int axis, Vect &V){
sp_point p;
p.Set(V.i, V.j, V.k);
Toolbox::rotation(theta, axis, p);
V.Set(p.x, p.y, p.z);
}
void Toolbox::rotation(double theta, int axis, sp_point &P){
/*
This method takes a point, a rotation angle, and the axis of rotation and
rotates the point about the origin in the specified direction.
The inputs are:
theta | [rad] | Angle of rotation
axis | none | X=0, Y=1, Z=2 : Axis to rotate about
The method returns a modified point "P" that has been rotated according to the inputs.
Rotation is clockwise about each axis (left hand rule). In other words,
positive rotation for each axis is defined by the apparent motion when positive end
of the axis points toward the viewer.
*/
//the 3x3 rotation matrix
double MR0i, MR0j, MR0k, MR1i, MR1j, MR1k, MR2i, MR2j, MR2k;
double costheta = cos(theta);
double sintheta = sin(theta);
switch(axis)
{
/*
The rotation vectors are entered in as the transverse for convenience of multiplication.
The correct matrix form for each are:
X axis
[1, 0, 0,
0, cos(theta), -sin(theta),
0, sin(theta), cos(theta)]
Y axis
[cos(theta), 0, sin(theta),
0, 1, 0,
-sin(theta), 0, cos(theta)]
Z axis
[cos(theta), -sin(theta), 0,
sin(theta), cos(theta), 0,
0, 0, 1 ]
*/
case 0: //X axis
//Fill in the x-rotation matrix for this angle theta
MR0i = 1; MR0j = 0; MR0k = 0;
MR1i = 0; MR1j = costheta; MR1k = sintheta;
MR2i = 0; MR2j = -sintheta; MR2k = costheta;
break;
case 1: //Y axis
//Fill in the y-rotation matrix for this angle theta
MR0i = costheta; MR0j = 0; MR0k = -sintheta;
MR1i = 0; MR1j = 1; MR1k = 0;
MR2i = sintheta; MR2j = 0; MR2k = costheta;
break;
case 2: //Z axis
//Fill in the z-rotation matrix for this angle theta
MR0i = costheta; MR0j = sintheta; MR0k = 0;
MR1i = -sintheta; MR1j = costheta; MR1k = 0;
MR2i = 0; MR2j = 0; MR2k = 1;
break;
default:
throw spexception("Internal error: invalid axis number specified in rotation() method.");
}
//Create a copy of the point
double Pcx = P.x;
double Pcy = P.y;
double Pcz = P.z;
//Do the rotation. The A matrix is the rotation vector and the B matrix is the point vector
P.x = MR0i*Pcx + MR0j*Pcy + MR0k*Pcz; //dotprod(MR0, Pc); //do the dotprod's here to avoid function call
P.y = MR1i*Pcx + MR1j*Pcy + MR1k*Pcz; //dotprod(MR1, Pc);
P.z = MR2i*Pcx + MR2j*Pcy + MR2k*Pcz; //dotprod(MR2, Pc);
return;
}
bool Toolbox::plane_intersect(sp_point &P, Vect &N, sp_point &C, Vect &L, sp_point &Int){
/*
Determine the intersection point of a line and a plane. The plane is
defined by:
P | sp_point on the plane
N | Normal unit vector to the plane
The line/vector is defined by:
C | (x,y,z) coordinate of the beginning of the line
L | Unit vector pointing along the line
The distance 'd' along the unit vector is given by the equation:
d = ((P - C) dot N)/(L dot N)
The method fills in the values of a point "Int" that is the intersection.
In the case that the vector does not intersect with the plane, the method returns FALSE and
the point Int is not modified. If an intersection is found, the method will return TRUE.
*/
double PC[3], LdN, PCdN, d;
int i;
//Create a vector between P and C
for(i=0; i<3; i++){PC[i] = P[i]-C[i];}
//Calculate the dot product of L and N
LdN = 0.;
for(i=0; i<3; i++){
LdN += L[i]*N[i];
}
//Calculate the dot product of (P-C) and N
PCdN = 0.;
for(i=0; i<3; i++){
PCdN += PC[i]*N[i];
}
if(LdN == 0.) return false; //Line is parallel to the plane
d = PCdN / LdN; //Multiplier on unit vector that intersects the plane
//Calculate the coordinates of intersection
Int.x = C.x + d*L.i;
Int.y = C.y + d*L.j;
Int.z = C.z + d*L.k;
return true;
}
bool Toolbox::line_norm_intersect(sp_point &line_p0, sp_point &line_p1, sp_point &P, sp_point &I, double &rad){
/*
Note: 2D implementation (no Z component)
Given two points that form a line segment (line_p0 and line_p1) and an external point
NOT on the line (P), return the location of the intersection (I) between a second line
that is normal to the first and passes through P. Also return the corresponding radius 'rad'
||P I||.
(line_p0) (I) (line_p1)
O--------------X----------------------------O
|_|
|
|
O
(P)
If the normal to the line segment lies outside of the segment, the method returns
FALSE, otherwise its TRUE. In the first case, 'I' is equal to the segment point closest
to 'P', otherwise it is the intersection point.
Solve for 'I' using the derivative of the distance formula (r(x,y)) between I and P. I is the point
where dr(x,y)/dx = 0.
*/
//Check to see if the 'x' components of p0 and p1 are the same, which is undefined slope.
if(line_p0.x == line_p1.x){
//check for containment
double Iyr = (P.y - line_p0.y)/(line_p1.y - line_p0.y);
if(Iyr < 0.){ //out of bounds on the p0 side
I.Set(line_p0.x, line_p0.y, 0.);
rad = vectmag(I.x - P.x, I.y - P.y, 0.);
return false;
}
else if(Iyr > 1.){ //out of bounds on the p1 side
I.Set(line_p1.x, line_p1.y, 0.);
rad = vectmag(I.x - P.x, I.y - P.y, 0.);
return false;
}
I.Set(line_p0.x, P.y, 0.);
}
double
drdx = (line_p1.y - line_p0.y)/(line_p1.x - line_p0.x),
drdx_sq = pow(drdx,2);
I.x = (P.x + P.y * drdx - line_p0.y*drdx + line_p0.x*drdx_sq)/(1. + drdx_sq);
//check for containment
double Ixr = (I.x - line_p0.x)/(line_p1.x - line_p0.x);
if(Ixr < 0.){ //outside the bounds on the p0 side
I.x = line_p0.x;
I.y = line_p0.y;
rad = vectmag(I.x - P.x, I.y - P.y, 0.);
return false;
}
else if(Ixr > 1.){ //outside the bounds on the p1 side
I.x = line_p1.x;
I.y = line_p1.y;
rad = vectmag(I.x - P.x, I.y - P.y, 0.);
return false;
}
//in bounds
I.y = line_p0.y + (I.x - line_p0.x)*drdx;
rad = vectmag(I.x - P.x, I.y - P.y, 0.);
return true;
}
void Toolbox::ellipse_bounding_box(double &A, double &B, double &phi, double sides[4], double cx, double cy){
/*
This algorithm takes an ellipse in a plane at location {cx,cy} and with unrotated X axis
size A, unrotated Y axis size B, and with angle of rotation 'phi' [radians] and calculates
the bounding box edge locations in the coordinate system of the plane.
This method fills the 'sides' array with values for:
sides[0] | x-axis minimum
sides[1] | x-axis maximum
sides[2] | y-axis minimum
sides[3] | y-axis maximum
Reference:
http://stackoverflow.com/questions/87734/how-do-you-calculate-the-axis-aligned-bounding-box-of-an-ellipse
Governing equations are:
x = cx + A*cos(t)*cos(phi) - b*sin(t)*sin(phi)
y = cy + b*sin(t)*cos(phi) - a*cos(t)*sin(phi)
where 't' is an eigenvalue with repeating solutions of dy/dt=0
For X values:
0 = dx/dt = -A*sin(t)*cos(phi) - B*cos(t)*sin(phi)
--> tan(t) = -B*tan(phi)/A
--> t = atan( -B*tan(phi)/A )
for Y values:
0 = dy/dt = B*cos(t)*cos(phi) - A*sin(t)*sin(phi)
--> tan(t) = B*cot(phi)/A
--> t = aan( B*cot(phi)/A )
*/
//double pi = PI;
//X first
//double tx = atan( -B*tan(phi)/A );
double tx = atan2( -B*tan(phi), A);
//plug back into the gov. equation
double txx = A*cos(tx)*cos(phi) - B*sin(tx)*sin(phi);
sides[0] = cx + txx/2.;
sides[1] = cx - txx/2.;
//enforce orderedness
if(sides[1] < sides[0]) swap(&sides[0], &sides[1]);
//Y next
double ty = atan2( -B, tan(phi)*A );
double tyy = B*sin(ty)*cos(phi) - A*cos(ty)*sin(phi);
sides[2] = cy + tyy/2.;
sides[3] = cy - tyy/2.;
if(sides[3] < sides[2]) swap(&sides[3], &sides[2]);
}
void Toolbox::convex_hull(std::vector<sp_point> &points, std::vector<sp_point> &hull)
{
/*
Returns a list of points on the convex hull in counter-clockwise order.
Note: the last point in the returned list is the same as the first one.
Source: http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
*/
int n = (int)points.size(), k = 0;
vector<sp_point> H(2*n);
//copy points
vector<sp_point> pointscpy;
pointscpy.reserve( points.size() );
for(size_t i=0; i<points.size(); i++)
pointscpy.push_back( points.at(i) );
// Sort points lexicographically
sort(pointscpy.begin(), pointscpy.end());
// Build lower hull
for (int i = 0; i < n; ++i) {
while (k >= 2 && crossprod(H.at(k-2), H.at(k-1), pointscpy.at(i)) <= 0) k--;
H.at(k++) = pointscpy[i];
}
// Build upper hull
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && crossprod(H.at(k-2), H.at(k-1), pointscpy.at(i)) <= 0) k--;
H.at(k++) = pointscpy[i];
}
H.resize(k);
hull = H;
}
double Toolbox::area_polygon(std::vector<sp_point> &points){
/*
INPUT: vector<sp_point> a list of 'sp_point' objects.
OUTPUT: Return the total area
ASSUME: we care about the area projected into the Z plane, therefore only x,y coordinates are considered.
Calculate the area contained within a generic polygon. Use the projected segments method.
The polygon can be convex or non-convex and can be irregular.
The vector "points" is an ordered list of points composing the polygon in CLOCKWISE order.
The final point in "points" is assumed to be connected to the first point in "points".
*/
//add the first point to the end of the list
if( points.size() == 0 )
return 0.;
points.push_back(points.front());
int npt = (int)points.size();
double area = 0.;
for(int i=0; i<npt-1; i++){
double w = points.at(i).x - points.at(i+1).x;
double ybar = (points.at(i).y + points.at(i+1).y)*0.5;
area += w * ybar;
}
//restore the array
points.pop_back();
return area;
}
typedef vector<sp_point> Poly; //Local definitino of polygon, used only in polyclip
class polyclip
{
/*
A class dedicated to clipping polygons
This class must remain in Toolbox.cpp to compile!
*/
public:
Poly clip(Poly &subjectPolygon, Poly &clipPolygon)
{
/*
http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
*/
outputList = subjectPolygon;
cp1 = clipPolygon.back();
for(int i=0; i<(int)clipPolygon.size(); i++)
{
cp2 = clipPolygon.at(i);
inputList = outputList;
outputList.clear();
s = inputList.back();
for(int j=0; j<(int)inputList.size(); j++)
{
e = inputList.at(j);
if(inside(&e) ){
if(! inside(&s) )
outputList.push_back( computeIntersection() );
outputList.push_back(e);
}
else if( inside(&s) ){
outputList.push_back( computeIntersection() );
}
s = e;
}
cp1 = cp2;
}
return outputList;
}
private:
sp_point cp1, cp2;
Poly outputList, inputList;
sp_point s, e;
bool inside(sp_point *P){
return (cp2.x - cp1.x)*(P->y - cp1.y) > (cp2.y - cp1.y)*(P->x - cp1.x);
};
sp_point computeIntersection()
{
sp_point dc = cp1;
dc.Subtract(cp2);
sp_point dp = s;
dp.Subtract(e);
double n1 = cp1.x * cp2.y - cp1.y * cp2.x;
double n2 = s.x * e.y - s.y * e.x;
double n3 = 1./ (dc.x * dp.y - dc.y * dp.x);
sp_point ret;
ret.Set((n1*dp.x - n2*dc.x) * n3, (n1*dp.y - n2*dc.y)*n3, 0.);
return ret;
}
};
vector<sp_point> Toolbox::clipPolygon(std::vector<sp_point> &A, std::vector<sp_point> &B)
{
/*
Compute the polygon that forms the intersection of two polygons subjectPolygon
and clipPolygon. (clipPolygon clips subjectPolygon).
This only considers 2D polygons -- vertices X and Y in "sp_point" structure!
*/
polyclip P;
return P.clip(A,B);
}
void Toolbox::BezierQ(sp_point &start, sp_point &control, sp_point &end, double t, sp_point &result)
{
/*
Locate a point 'result' along a quadratic Bezier curve.
*/
double tc = 1. - t;
result.x = tc * tc * start.x + 2 * (1 - t) * t * control.x + t * t * end.x;
result.y = tc * tc * start.y + 2 * (1 - t) * t * control.y + t * t * end.y;
result.z = tc * tc * start.z + 2 * (1 - t) * t * control.z + t * t * end.z;
}
void Toolbox::BezierC(sp_point &start, sp_point &control1, sp_point &control2, sp_point &end, double t, sp_point &result)
{
/*
Locate a point 'result' along a cubic Bezier curve.
*/
double tc = 1. - t;
result.x = tc*tc*tc * start.x + 3. * tc *tc * t * control1.x + 3. * tc * t * t * control2.x + t * t * t * end.x;
result.y = tc*tc*tc * start.y + 3. * tc *tc * t * control1.y + 3. * tc * t * t * control2.y + t * t * t * end.y;
result.z = tc*tc*tc * start.z + 3. * tc *tc * t * control1.z + 3. * tc * t * t * control2.z + t * t * t * end.z;
}
void Toolbox::poly_from_svg(std::string &svg, std::vector< sp_point > &polygon, bool clear_poly) //construct a polygon from an SVG path
{
/*
The following commands are available for path data:
M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
C = curveto
Q = quadratic Bezier curve
Z = closepath
>> not yet supported
S = smooth curveto
T = smooth quadratic Bezier curveto
A = elliptical Arc
<<
Note: All of the commands above can also be expressed with lower letters. Capital letters means absolutely positioned, lower cases means relatively positioned.
*/
int move=-1; //initialize
std::string movedat;
bool process_now = false;
if( clear_poly )
polygon.clear();
polygon.reserve( svg.size()/5 );
double x0,y0;
x0=y0=0.; //last position for relative calcs
for(size_t i=0; i<svg.size(); i++)
{
int c = svg.at(i);
if( c > 64 && c < 123 ) //a new command
{
if( move > 0 )
process_now = true;
else
move = c;
}
else
{
movedat += svg.at(i);
}
if( process_now )
{
std::vector< std::string > points_s = split(movedat, " ");
std::vector< std::vector<double> > points;
for(size_t j=0; j<points_s.size(); j++)
{
std::vector< std::string > xy_s = split( points_s.at(j), "," );
points.push_back( std::vector<double>() );
for( size_t k=0; k<xy_s.size(); k++)
{
points.back().push_back( 0 );
to_double( xy_s.at(k), &points.back().at(k) );
}
}
int npt = (int)points.size();
switch (move)
{
case 'm':
//pick up and move cursor (reset last position)
x0 += points.front().at(0);
y0 += points.front().at(1);
polygon.push_back( sp_point(x0, -y0, 0.) );
if( npt > 1 ) //any subsequent points are assumed to be 'l'
{
for(int j=1; j<npt; j++)
{
x0 += points.at(j).at(0);
y0 += points.at(j).at(1);
polygon.push_back( sp_point(x0, -y0, 0.) );
}
}
break;
case 'M':
//pick up and move cursor (reset last position)
x0 = points.front().at(0);
y0 = points.front().at(1);
polygon.push_back( sp_point(x0, -y0, 0.) );
if( npt > 1 ) //any subsequent points are assumed to be 'l'
{
for(int j=1; j<npt; j++)
{
x0 += points.at(j).at(0);
y0 += points.at(j).at(1);
polygon.push_back( sp_point(x0, -y0, 0.) );
}
}
break;
case 'l':
//trace all points
for(int j=0; j<npt; j++)
{
x0 += points.at(j).at(0);
y0 += points.at(j).at(1);
polygon.push_back( sp_point(x0, -y0, 0.) );
}
break;
case 'L':
//trace all points - absolute
for(int j=0; j<npt; j++)
{
x0 = points.at(j).at(0);
y0 = points.at(j).at(1);
polygon.push_back( sp_point(x0, -y0, 0.) );
}
break;
case 'h':
//horizontal line relative
for(int j=0; j<npt; j++)
{
x0 += points.at(j).front();
polygon.push_back( sp_point(x0, -y0, 0.) );
}
break;
case 'H':
//horizontal line absolute
for(int j=0; j<npt; j++)
{
x0 = points.at(j).front();
polygon.push_back( sp_point(x0, -y0, 0.) );
}
break;
case 'v':
//vertical line relative
for(int j=0; j<npt; j++)
{
y0 += points.at(j).front();
polygon.push_back( sp_point(x0, -y0, 0.) );
}
break;
case 'V':
//vertical line absolute
for(int j=0; j<npt; j++)
{
y0 = points.at(j).front();
polygon.push_back( sp_point(x0, -y0, 0.) );
}
break;
case 'q':
case 'Q':
{
//bezier curve
double xcond=0.;
double ycond=0.;
//check to make sure there are an even number of points
if( npt % 2 != 0 )
return;
int nbz = 5; //number of internal bezier points
for(int j=0; j<npt; j+=2) //jump through in pairs
{
sp_point start(x0, y0, 0.);
if( move == 'q' ) //if relative, set the relative adder to the start point location
{
xcond = start.x;
ycond = start.y;
}
sp_point control( points.at(j).at(0) + xcond, points.at(j).at(1) + ycond, 0. );
sp_point end( points.at(j+1).at(0) + xcond, points.at(j+1).at(1) + ycond, 0. );
for(int k=0; k<nbz; k++)
{
double t = (k+1)/(double)(nbz+1);
sp_point result;
Toolbox::BezierQ(start, control, end, t, result);
result.y = -result.y;
polygon.push_back( result );
}
//update cursor position
x0 = end.x;
y0 = end.y;
//add the end point
end.y = -end.y;
polygon.push_back( end );
}
break;
}
case 'c':
case 'C':
{
//bezier curve
double xcond=0.;
double ycond=0.;
//check to make sure there are a divisible number of points
if( npt % 3 != 0 )
return;
int nbz = 7; //number of internal bezier points
for(int j=0; j<npt; j+=3) //jump through in pairs
{
sp_point start(x0, y0, 0.);
//sp_point start = polygon.back();
if( move == 'c' ) //if relative, set the relative adder to the start point location
{
xcond = start.x;
ycond = start.y;
}
sp_point control1( points.at(j).at(0) + xcond, points.at(j).at(1) + ycond, 0. );
sp_point control2( points.at(j+1).at(0) + xcond, points.at(j+1).at(1) + ycond, 0. );
sp_point end( points.at(j+2).at(0) + xcond, points.at(j+2).at(1) + ycond, 0. );
for(int k=0; k<nbz; k++)
{
double t = (k+1)/(double)(nbz+2);
sp_point result;
Toolbox::BezierC(start, control1, control2, end, t, result);
result.y = -result.y;
polygon.push_back( result );
}
//update cursor position
x0 = end.x;
y0 = end.y;
//add the end point
end.y = -end.y;
polygon.push_back( end );
}
break;
}
case 'z':
case 'Z':
break;
default: //c, t, s, a
break;
}
movedat.clear();
move = c; //next move
process_now = false;
}
}
return;
}
sp_point Toolbox::rotation_arbitrary(double theta, Vect &axis, sp_point &axloc, sp_point &pt){
/*
Rotation of a point 'pt' about an arbitrary axis with direction 'axis' centered at point 'axloc'.
The point is rotated through 'theta' radians.
http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/
Returns the rotated sp_point location
*/
double
a = axloc.x, //Point through which the axis passes
b = axloc.y,
c = axloc.z,
x = pt.x, //Point that we're rotating
y = pt.y,
z = pt.z,
u = axis.i, //Direction of the axis that we're rotating about
v = axis.j,
w = axis.k;
sp_point fin;
double
sinth = sin(theta),
costh = cos(theta);
fin.x = (a*(pow(v,2)+pow(w,2)) - u*(b*v + c*w - u*x - v*y - w*z))*(1.-costh) + x*costh + (-c*v + b*w - w*y + v*z)*sinth;
fin.y = (b*(pow(u,2)+pow(w,2)) - v*(a*u + c*w - u*x - v*y - w*z))*(1.-costh) + y*costh + (c*u - a*w + w*x - u*z)*sinth;
fin.z = (c*(pow(u,2)+pow(v,2)) - w*(a*u + b*v - u*x - v*y - w*z))*(1.-costh) + z*costh + (-b*u + a*v - v*x + u*y)*sinth;
return fin;
}
double Toolbox::ZRotationTransform(Vect &normal_vect){
/*
When a heliostat position is transformed using the SolTrace convention, the heliostat
ends up such that the horizontal (x) axis is not parallel with the ground XZ plane.
This is caused by a mismatch between conventional rotation about (1) the y axis and (2) the
rotated y axis, and azimuth-elevation rotation about (1) the x axis and (2) the original z axis.
This method calculates the angle of rotation about the modified z-axis in order to restore
the azimuth-elevation positioning.
Rotations are assumed to be:
(1) CCW about Y axis
(2) CW about X' axis
(3) CW about Z'' axis
*/
//double Pi = PI;
double az = atan3(normal_vect.i,normal_vect.j);
double el = asin(normal_vect.k);
//Calculate Euler angles
double alpha = atan2(normal_vect.i, normal_vect.k); //Rotation about the Y axis
double bsign = normal_vect.j > 0. ? 1. : -1.;
double beta = -bsign*acos( ( pow(normal_vect.i,2) + pow(normal_vect.k,2) )/ max(sqrt(pow(normal_vect.i,2) + pow(normal_vect.k,2)), 1.e-8) ); //Rotation about the modified X axis
//Calculate the modified axis vector
Vect modax;
modax.Set( cos(alpha), 0., -sin(alpha) );
//Rotation references - axis point
sp_point axpos;
axpos.Set(0.,0.,0.); //Set as origin
//sp_point to rotate
sp_point pbase;
pbase.Set(0., -1., 0.); //lower edge of heliostat
//Rotated point
sp_point prot = Toolbox::rotation_arbitrary(beta, modax, axpos, pbase);
//Azimuth/elevation reference vector (vector normal to where the base of the heliostat should be)
Vect azelref;
azelref.Set( sin(az)*sin(el), cos(az)*sin(el), -cos(el) );
//Calculate the angle between the rotated point and the azel ref vector
//double gamma = acos( Toolbox::dotprod(azelref, prot) );
/*
the sign of the rotation angle is determined by whether the 'k' component of the cross product
vector is positive or negative.
*/
Vect protv;
protv.Set(prot.x, prot.y, prot.z);
unitvect(protv);
Vect cp = crossprod(protv, azelref);
double gamma = asin( vectmag( cp ));
double gsign = (cp.k > 0. ? 1. : -1.) * (normal_vect.j > 0. ? 1. : -1.);
return gamma * gsign;
}
double Toolbox::ZRotationTransform(double Az, double Zen){
/*
Overload for az-zen specification
Notes:
The Azimuth angle should be [-180,180], zero is north, +east, -west.
Az and Zen are both in Radians.
*/
//Calculate the normal vector to the heliostat based on elevation and azimuth
double Pi = PI;
double el = Pi/2.-Zen;
double az = Az+Pi; //Transform to 0..360 (in radians)
Vect aim;
aim.Set( sin(az)*cos(el), cos(az)*cos(el), sin(el) );
return ZRotationTransform(aim);
}
double Toolbox::intersect_fuv(double U, double V){
/*
Helper function for intersect_ellipse_rect()
*/
double
u2 = sqrt(1.-pow(U,2)),
v2 = sqrt(1.-pow(V,2));
return asin(u2 * v2 - U*V) - U*u2 - V*v2 + 2.*U*V;
}
double Toolbox::intersect_ellipse_rect(double rect[4], double ellipse[2]){
/*
Calculate the area of intersection of a rectangle and an ellipse where the sides of the
rectangle area parallel with the axes of the ellipse.
{rect[0], rect[1]} = Point location of center of rectangle
{rect[2], rect[3]} = Rectangle width, Rectangle height
{ellipse[0], ellipse[1]} = Ellipse width and height
(A.D. Groves, 1963. Area of intersection of an ellipse and a rectangle. Ballistic Research Laboratories.)
*/
//Unpack
double
//a = rect[0] - rect[2]/2., //Lower left corner X location
//b = rect[1] - rect[3]/2., //Lower left corner Y location
c = rect[2], //Rect width
d = rect[3]; //Rect height
double
w = ellipse[0], //Ellipse width
h = ellipse[1]; //Ellipse height
//Construct 4 separate possible rectangles
double A[4], B[4], C[4], D[4];
for(int i=1; i<5; i++){
A[i-1] = max(0., pow(-1, (pow((double)i,2)-i)/2)*rect[0] - c/2.);
B[i-1] = max(0., pow(-1, (pow((double)i,2)+i-2)/2)*rect[1] - d/2.);
C[i-1] = max(0., pow(-1, (pow((double)i,2)-i)/2)*rect[0]+c/d-A[i-1]);
D[i-1] = max(0., pow(-1, (pow((double)i,2)+i-2)/2)*rect[1]+d/2.-B[i-1]);
}
double atot=0.;
for(int i=0; i<4; i++){
if(C[i] == 0. || D[i] == 0.) continue; //No area if width or height are 0
//Calculate vertex radii
double V[4];
V[0] = pow(A[i]/w,2) + pow(B[i]/h,2);
V[1] = pow(A[i]/w,2) + pow((B[i]+D[i])/h,2);
V[2] = pow((A[i]+C[i])/w,2) + pow((B[i]+D[i])/h,2);
V[3] = pow((A[i]+C[i])/w,2) + pow(B[i]/h,2);
//Seven cases
if(pow(A[i]/w,2) + pow(B[i]/h,2) >= 1.){
continue; //no area overlap
}
else if(V[0] < 1. && V[1] >= 1 && V[3] >= 1.){
//Lower left vertex is the only one in the ellipse
atot += w*h/2.*intersect_fuv(A[i]/w, B[i]/h);
}
else if(V[3] < 1. && V[1] >= 1.){
//Lower edge inside ellipse, upper edge outside
atot += w*h/2. * (intersect_fuv(A[i]/w, B[i]/h) - intersect_fuv((A[i]+C[i])/w, B[i]/h));
}
else if(V[1] < 1. && V[3] >= 1.){
//Left edge inside, right edge outside
atot += w*h/2. * (intersect_fuv(A[i]/w, B[i]/h) - intersect_fuv(A[i]/w, (B[i]+D[i])/h));
}
else if(V[1] < 1. && V[3] < 1. && V[2] > 1.){
//All vertices inside ellipse except upper right corner
atot += w*h/2.*(intersect_fuv(A[i]/w, B[i]/h) - intersect_fuv((A[i]+C[i])/w, B[i]/h) - intersect_fuv(A[i]/w, (B[i]+D[i])/h));
}
else if(V[2] < 1.){
//All vertices inside the ellipse
atot += w*h;
}
else{
continue; //Error
}
}
return atot;
}
string Toolbox::getDelimiter(std::string &text){
if (text.empty())
return ",";
//Find the type of delimiter
vector<string> delims;
delims.push_back(",");
delims.push_back(" ");
delims.push_back("\t");
delims.push_back(";");
string delim = "\t"; //initialize
int ns=0;
for(int i=0; i<4; i++){
vector<string> data = Toolbox::split(text, delims[i]);
if((int)data.size()>ns){ delim = delims[i]; ns = (int)data.size(); } //pick the delimiter that returns the most entries
}
return delim;
}
vector< string > Toolbox::split( const string &str, const string &delim, bool ret_empty, bool ret_delim )
{
//Take a string with a delimiter and return a vector of separated values
vector< string > list;
char cur_delim[2] = {0,0};
string::size_type m_pos = 0;
string token;
int dsize = (int)delim.size();
while (m_pos < str.length())
{
//string::size_type pos = str.find_first_of(delim, m_pos);
string::size_type pos = str.find(delim, m_pos);
if (pos == string::npos)
{
cur_delim[0] = 0;
token.assign(str, m_pos, string::npos);
m_pos = str.length();
}
else
{
cur_delim[0] = str[pos];
string::size_type len = pos - m_pos;
token.assign(str, m_pos, len);
//m_pos = pos + 1;
m_pos = pos + dsize;
}
if (token.empty() && !ret_empty)
continue;
list.push_back( token );
if ( ret_delim && cur_delim[0] != 0 && m_pos < str.length() )
list.push_back( string( cur_delim ) );
}
return list;
}
| 27.523759
| 178
| 0.585118
|
rchintala13
|
cce4c58fd7f2fe5c465f493d28169a189cb5e6b9
| 2,019
|
cpp
|
C++
|
cocos2dx_playground/Classes/cpg_input_BasicKeyCollector.cpp
|
R2Road/cocos2dx_playground
|
6e6f349b5c9fc702558fe8720ba9253a8ba00164
|
[
"Apache-2.0"
] | 9
|
2020-06-11T17:09:44.000Z
|
2021-12-25T00:34:33.000Z
|
cocos2dx_playground/Classes/cpg_input_BasicKeyCollector.cpp
|
R2Road/cocos2dx_playground
|
6e6f349b5c9fc702558fe8720ba9253a8ba00164
|
[
"Apache-2.0"
] | 9
|
2019-12-21T15:01:01.000Z
|
2020-12-05T15:42:43.000Z
|
cocos2dx_playground/Classes/cpg_input_BasicKeyCollector.cpp
|
R2Road/cocos2dx_playground
|
6e6f349b5c9fc702558fe8720ba9253a8ba00164
|
[
"Apache-2.0"
] | 1
|
2020-09-07T01:32:16.000Z
|
2020-09-07T01:32:16.000Z
|
#include "cpg_input_BasicKeyCollector.h"
#include "cpg_input_KeyMap.h"
#include "step_rain_of_chaos_input_KeyCodeCollector.h"
USING_NS_CC;
namespace cpg_input
{
BasicKeyCollector::BasicKeyCollector( const KeyMapSp& key_map_container ) : iKeyCollector( key_map_container )
, mKeyHistory()
, mCurrent_KeyStatus_Container()
, mLast_KeyStatus_Container()
{
mLast_KeyStatus_Container = mKeyHistory.begin();
mCurrent_KeyStatus_Container = mLast_KeyStatus_Container + 1;
}
KeyCollectorSp BasicKeyCollector::create( const KeyMapSp& key_map_container )
{
KeyCollectorSp ret( new ( std::nothrow ) BasicKeyCollector( key_map_container ) );
return ret;
}
void BasicKeyCollector::collect( const step_rain_of_chaos::input::KeyCodeCollector& key_code_collector )
{
for( const auto k : mKeyMapContainer->mContainer )
( *mCurrent_KeyStatus_Container )[k.idx] = key_code_collector.isActiveKey( k.keycode );
}
void BasicKeyCollector::update_forHistory()
{
if( mLast_KeyStatus_Container->to_ulong() != mCurrent_KeyStatus_Container->to_ulong() )
{
mLast_KeyStatus_Container = mCurrent_KeyStatus_Container;
++mCurrent_KeyStatus_Container;
if( mKeyHistory.end() == mCurrent_KeyStatus_Container )
mCurrent_KeyStatus_Container = mKeyHistory.begin();
*mCurrent_KeyStatus_Container = *mLast_KeyStatus_Container;
}
}
bool BasicKeyCollector::getKeyStatus( const cocos2d::EventKeyboard::KeyCode keycode ) const
{
for( auto& k : mKeyMapContainer->mContainer )
if( keycode == k.keycode )
return ( *mCurrent_KeyStatus_Container )[k.idx];
return false;
}
bool BasicKeyCollector::getKeyStatus( const int target_key_index ) const
{
if( 0 > target_key_index || static_cast<std::size_t>( target_key_index ) >= ( *mCurrent_KeyStatus_Container ).size() )
return false;
return ( *mCurrent_KeyStatus_Container )[target_key_index];
}
bool BasicKeyCollector::hasChanged() const
{
return mLast_KeyStatus_Container->to_ulong() != mCurrent_KeyStatus_Container->to_ulong();
}
}
| 33.098361
| 120
| 0.771174
|
R2Road
|
cce5501e3b418a4945627888a305392c92ee0906
| 1,763
|
inl
|
C++
|
libblk/info.inl
|
transpixel/tpqz
|
2d8400b1be03292d0c5ab74710b87e798ae6c52c
|
[
"MIT"
] | 1
|
2017-06-01T00:21:16.000Z
|
2017-06-01T00:21:16.000Z
|
libblk/info.inl
|
transpixel/tpqz
|
2d8400b1be03292d0c5ab74710b87e798ae6c52c
|
[
"MIT"
] | 3
|
2017-06-01T00:26:16.000Z
|
2020-05-09T21:06:27.000Z
|
libblk/info.inl
|
transpixel/tpqz
|
2d8400b1be03292d0c5ab74710b87e798ae6c52c
|
[
"MIT"
] | null | null | null |
//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
/*! \file
\brief Definitions for blk::info
*/
namespace blk
{
template <typename TypeKey>
std::string
infoString
( std::map<TypeKey, ga::Rigid> const & oriMap
, std::string const & title
)
{
std::ostringstream oss;
if (! title.empty())
{
oss << title << std::endl;
}
oss << "NumberNodes: " << oriMap.size();
for (typename std::map<TypeKey, ga::Rigid>::const_iterator
iter(oriMap.begin()) ; oriMap.end() != iter ; ++iter)
{
oss << std::endl;
oss
<< dat::infoString(iter->first)
<< " " << ":"
<< " " << iter->second.infoStringShort()
;
}
return oss.str();
}
} // blk
| 25.926471
| 72
| 0.695973
|
transpixel
|
cce6a75dd76da1b27efb082873e079f1c618091f
| 6,868
|
hpp
|
C++
|
src/Renderer.hpp
|
CobaltXII/Tempest
|
5963e21b98cd414b1b525b11a193512ec3e35f14
|
[
"MIT"
] | 4
|
2020-01-03T02:52:53.000Z
|
2021-09-16T23:03:06.000Z
|
src/Renderer.hpp
|
CobaltXII/Tempest
|
5963e21b98cd414b1b525b11a193512ec3e35f14
|
[
"MIT"
] | null | null | null |
src/Renderer.hpp
|
CobaltXII/Tempest
|
5963e21b98cd414b1b525b11a193512ec3e35f14
|
[
"MIT"
] | null | null | null |
// A renderer.
struct Renderer {
const float FOV = 60.0f;
const float NEAR_PLANE = 0.5f;
const float FAR_PLANE = 5000.0f;
Display display;
glm::mat4 projection;
int width;
int height;
Renderer() {
return;
}
Renderer(std::string title, int width, int height) {
display = Display(title, width, height);
SDL_GL_GetDrawableSize(display.window, &this->width, &this->height);
projection = glm::perspectiveFov(
glm::radians(FOV),
float(display.width),
float(display.height),
NEAR_PLANE,
FAR_PLANE
);
}
// Get the mouse ray.
glm::vec3 getMouseRay(Camera camera, int mouseX, int mouseY) {
float u = float(mouseX) * 2.0f / float(display.width) - 1.0f;
float v = 1.0f - float(mouseY) * 2.0f / float(display.height);
glm::vec4 b = glm::inverse(projection) * glm::vec4(u, v, -1.0f, 1.0f);
return normalize(glm::inverse(camera.getView()) * glm::vec4(b.x, b.y, -1.0f, 0.0f));
}
// Get the time in seconds.
float getTime() {
return float(SDL_GetTicks()) / 1000.0f;
}
// Bind the default framebuffer.
void bindDefaultFramebuffer() {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, width, height);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
// Unbind the default framebuffer.
void unbindDefaultFramebuffer() {
return;
}
// Prepare the frame.
void prepare() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
// Render a textured model.
template<typename T>
void renderTexturedModel(TexturedModel& model, T& shader) {
glBindVertexArray(model.model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, model.texture.textureID);
glDrawArrays(GL_TRIANGLES, 0, model.model.vertexCount);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
// Render a terrain object.
template<typename T>
void renderTerrainObject(TerrainObject& model, T& shader) {
glBindVertexArray(model.model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
shader.setUniformSampler2D(shader.uTexture1, GL_TEXTURE0, model.texture1.textureID);
shader.setUniformSampler2D(shader.uTexture2, GL_TEXTURE1, model.texture2.textureID);
shader.setUniformSampler2D(shader.uTexture3, GL_TEXTURE2, model.texture3.textureID);
shader.setUniformSampler2D(shader.uHeightmap, GL_TEXTURE3, model.heightmap.textureID);
glDrawArrays(GL_TRIANGLES, 0, model.model.vertexCount);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
// Render an entity.
template<typename T>
void renderEntity(Entity& entity, T& shader) {
glBindVertexArray(entity.model.model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, entity.model.texture.textureID);
glm::mat4 transformation = createTransformation(
entity.position,
entity.rotation,
entity.scale
);
shader.setModel(transformation);
glDrawArrays(GL_TRIANGLES, 0, entity.model.model.vertexCount);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
// Render entities.
template<typename T>
void renderEntities(std::vector<Entity> entities, T& shader) {
if (entities.empty()) {
return;
}
glBindVertexArray(entities[0].model.model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, entities[0].model.texture.textureID);
for (auto& entity: entities) {
glm::mat4 transformation = createTransformation(
entity.position,
entity.rotation,
entity.scale
);
shader.setModel(transformation);
glDrawArrays(GL_TRIANGLES, 0, entity.model.model.vertexCount);
}
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
// Render a cubemap.
template<typename T>
void renderCubemap(Cubemap& cubemap, T& shader) {
glDisable(GL_DEPTH_TEST);
glBindVertexArray(cubemap.modelID);
glEnableVertexAttribArray(0);
shader.setUniformSamplerCube(cubemap.cubemapID);
glDrawArrays(GL_TRIANGLES, 0, 36);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
glEnable(GL_DEPTH_TEST);
}
// Render a quad.
template<typename T>
void renderQuad(Model& model, GLuint textureID, T& shader) {
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glBindVertexArray(model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
shader.setUniformSampler2D(shader.uTexture, GL_TEXTURE0, textureID);
glDrawArrays(GL_TRIANGLES, 0, model.vertexCount);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
}
// Render an untextured quad.
void renderUntexturedQuad(Model& model) {
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glBindVertexArray(model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glDrawArrays(GL_TRIANGLES, 0, model.vertexCount);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
}
// Render water.
template<typename T>
void renderWaterObject(WaterObject& model, T& shader) {
glBindVertexArray(model.model.vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
shader.setUniformSampler2D(shader.uReflectionTexture, GL_TEXTURE0, model.reflectionTextureID);
shader.setUniformSampler2D(shader.uRefractionTexture, GL_TEXTURE1, model.refractionTextureID);
shader.setUniformSampler2D(shader.uDepthTexture, GL_TEXTURE2, model.refractionDepthTextureID);
shader.setUniformSampler2D(shader.uWaterDuDv, GL_TEXTURE3, model.waterDuDv.textureID);
shader.setUniformSampler2D(shader.uWaterNormal, GL_TEXTURE4, model.waterNormal.textureID);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_TRIANGLES, 0, model.model.vertexCount);
glDisable(GL_BLEND);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
// Prepare ImGui.
void prepareImGui() {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(display.window);
ImGui::NewFrame();
}
// Render ImGui.
void renderImGui() {
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
// Update the frame.
void update(int fps) {
display.update(fps);
}
// Destroy the renderer.
void destroy() {
display.destroy();
}
};
| 27.805668
| 96
| 0.755679
|
CobaltXII
|
cceaba2286593dc1fa55e6559cc1ece25b0bc55a
| 18,490
|
cpp
|
C++
|
src/QMCWaveFunctions/tests/test_einset_spinor.cpp
|
kayahans/qmcpack
|
c25d77702e36363ff7368ded783bf31c1b1c5f17
|
[
"NCSA"
] | null | null | null |
src/QMCWaveFunctions/tests/test_einset_spinor.cpp
|
kayahans/qmcpack
|
c25d77702e36363ff7368ded783bf31c1b1c5f17
|
[
"NCSA"
] | null | null | null |
src/QMCWaveFunctions/tests/test_einset_spinor.cpp
|
kayahans/qmcpack
|
c25d77702e36363ff7368ded783bf31c1b1c5f17
|
[
"NCSA"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2020 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Raymond Clay, rclay@sandia.gov, Sandia National Laboratories
//
// File created by: Raymond Clay, rclay@sandia.gov, Sandia National Laboratories
//////////////////////////////////////////////////////////////////////////////////////
#include "catch.hpp"
#include "OhmmsData/Libxml2Doc.h"
#include "OhmmsPETE/OhmmsMatrix.h"
#include "Particle/ParticleSet.h"
#include "Particle/ParticleSetPool.h"
#include "QMCWaveFunctions/WaveFunctionComponent.h"
#include "QMCWaveFunctions/EinsplineSetBuilder.h"
#include "QMCWaveFunctions/EinsplineSpinorSetBuilder.h"
#include <stdio.h>
#include <string>
#include <limits>
using std::string;
namespace qmcplusplus
{
//Now we test the spinor set with Einspline orbitals from HDF.
#ifdef QMC_COMPLEX
TEST_CASE("Einspline SpinorSet from HDF", "[wavefunction]")
{
app_log() << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
app_log() << "!!!!! Einspline SpinorSet from HDF !!!!!\n";
app_log() << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
using ValueType = SPOSet::ValueType;
using RealType = SPOSet::RealType;
Communicate* c;
c = OHMMS::Controller;
ParticleSet ions_;
ParticleSet elec_;
ions_.setName("ion");
ions_.create(2);
ions_.R[0][0] = 0.00000000;
ions_.R[0][1] = 0.00000000;
ions_.R[0][2] = 1.08659253;
ions_.R[1][0] = 0.00000000;
ions_.R[1][1] = 0.00000000;
ions_.R[1][2] = -1.08659253;
elec_.setName("elec");
elec_.create(3);
elec_.R[0][0] = 0.1;
elec_.R[0][1] = -0.3;
elec_.R[0][2] = 1.0;
elec_.R[1][0] = -0.1;
elec_.R[1][1] = 0.3;
elec_.R[1][2] = 1.0;
elec_.R[2][0] = 0.1;
elec_.R[2][1] = 0.2;
elec_.R[2][2] = 0.3;
elec_.spins[0] = 0.0;
elec_.spins[1] = 0.2;
elec_.spins[2] = 0.4;
// O2 test example from pwscf non-collinear calculation.
elec_.Lattice.R(0, 0) = 5.10509515;
elec_.Lattice.R(0, 1) = -3.23993545;
elec_.Lattice.R(0, 2) = 0.00000000;
elec_.Lattice.R(1, 0) = 5.10509515;
elec_.Lattice.R(1, 1) = 3.23993545;
elec_.Lattice.R(1, 2) = 0.00000000;
elec_.Lattice.R(2, 0) = -6.49690625;
elec_.Lattice.R(2, 1) = 0.00000000;
elec_.Lattice.R(2, 2) = 7.08268015;
SpeciesSet& tspecies = elec_.getSpeciesSet();
int upIdx = tspecies.addSpecies("u");
int chargeIdx = tspecies.addAttribute("charge");
tspecies(chargeIdx, upIdx) = -1;
ParticleSetPool ptcl = ParticleSetPool(c);
ptcl.addParticleSet(&elec_);
ptcl.addParticleSet(&ions_);
const char* particles = "<tmp> \
<sposet_builder name=\"A\" type=\"spinorbspline\" href=\"o2_45deg_spins.pwscf.h5\" tilematrix=\"1 0 0 0 1 0 0 0 1\" twistnum=\"0\" source=\"ion\" size=\"3\" precision=\"float\"> \
<sposet name=\"myspo\" size=\"3\"> \
<occupation mode=\"ground\"/> \
</sposet> \
</sposet_builder> \
</tmp> \
";
Libxml2Document doc;
bool okay = doc.parseFromString(particles);
REQUIRE(okay);
xmlNodePtr root = doc.getRoot();
xmlNodePtr ein1 = xmlFirstElementChild(root);
EinsplineSpinorSetBuilder einSet(elec_, ptcl.getPool(), c, ein1);
std::unique_ptr<SPOSet> spo(einSet.createSPOSetFromXML(ein1));
REQUIRE(spo);
SPOSet::ValueMatrix_t psiM(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::GradMatrix_t dpsiM(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t dspsiM(elec_.R.size(), spo->getOrbitalSetSize()); //spin gradient
SPOSet::ValueMatrix_t d2psiM(elec_.R.size(), spo->getOrbitalSetSize());
//These are the reference values computed from a spin-polarized calculation,
//with the assumption that the coefficients for phi^\uparrow
SPOSet::ValueMatrix_t psiM_up(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t psiM_down(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t psiM_ref(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t dspsiM_ref(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::GradMatrix_t dpsiM_up(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::GradMatrix_t dpsiM_down(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::GradMatrix_t dpsiM_ref(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t d2psiM_up(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t d2psiM_down(elec_.R.size(), spo->getOrbitalSetSize());
SPOSet::ValueMatrix_t d2psiM_ref(elec_.R.size(), spo->getOrbitalSetSize());
//These reference values were generated as follows:
// 1.) Non-Collinear O2 calculation in PBC's performed using Quantum Espresso.
// 2.) Spinor wavefunction converted to HDF5 using convertpw4qmc tool. Mainly, this places the up channel in the spin_0 slot, and spin down in spin_1.
// 3.) The HDF5 metadata was hacked by hand to correspond to a fictional but consistent spin-polarized set of orbitals.
// 4.) A spin polarized QMCPACK run was done using the electron and ion configuration specified in this block. Orbital values, gradients, and laplacians were calculated
// for both "spin up" and "spin down" orbitals. This is where the psiM_up(down), d2psiM_up(down) values come from.
// 5.) By hand, the reference values, gradients, and laplacians are calculated by using the formula for a spinor e^is phi_up + e^{-is} phi_down.
// 6.) These are compared against the integrated initialization/parsing/evaluation of the Einspline Spinor object.
//Reference values for spin up component.
psiM_up[0][0] = ValueType(2.8696985245e+00, -2.8696982861e+00);
psiM_up[0][1] = ValueType(1.1698637009e+00, -1.1698638201e+00);
psiM_up[0][2] = ValueType(-2.6149117947e+00, 2.6149117947e+00);
psiM_up[1][0] = ValueType(2.8670933247e+00, -2.8670933247e+00);
psiM_up[1][1] = ValueType(1.1687355042e+00, -1.1687356234e+00);
psiM_up[1][2] = ValueType(-2.6131081581e+00, 2.6131081581e+00);
psiM_up[2][0] = ValueType(4.4833350182e+00, -4.4833350182e+00);
psiM_up[2][1] = ValueType(1.8927993774e+00, -1.8927993774e+00);
psiM_up[2][2] = ValueType(-8.3977413177e-01, 8.3977431059e-01);
//Reference values for spin down component.
psiM_down[0][0] = ValueType(1.1886650324e+00, -1.1886655092e+00);
psiM_down[0][1] = ValueType(-2.8243079185e+00, 2.8243076801e+00);
psiM_down[0][2] = ValueType(-1.0831292868e+00, 1.0831292868e+00);
psiM_down[1][0] = ValueType(1.1875861883e+00, -1.1875866652e+00);
psiM_down[1][1] = ValueType(-2.8215842247e+00, 2.8215837479e+00);
psiM_down[1][2] = ValueType(-1.0823822021e+00, 1.0823823214e+00);
psiM_down[2][0] = ValueType(1.8570541143e+00, -1.8570543528e+00);
psiM_down[2][1] = ValueType(-4.5696320534e+00, 4.5696320534e+00);
psiM_down[2][2] = ValueType(-3.4784498811e-01, 3.4784474969e-01);
//And the laplacians...
d2psiM_up[0][0] = ValueType(-6.1587309837e+00, 6.1587429047e+00);
d2psiM_up[0][1] = ValueType(-2.4736759663e+00, 2.4736781120e+00);
d2psiM_up[0][2] = ValueType(2.1381640434e-01, -2.1381306648e-01);
d2psiM_up[1][0] = ValueType(-5.0561609268e+00, 5.0561575890e+00);
d2psiM_up[1][1] = ValueType(-2.0328726768e+00, 2.0328762531e+00);
d2psiM_up[1][2] = ValueType(-7.4090242386e-01, 7.4090546370e-01);
d2psiM_up[2][0] = ValueType(-1.8970542908e+01, 1.8970539093e+01);
d2psiM_up[2][1] = ValueType(-8.2134075165e+00, 8.2134037018e+00);
d2psiM_up[2][2] = ValueType(1.0161912441e+00, -1.0161914825e+00);
d2psiM_down[0][0] = ValueType(-2.5510206223e+00, 2.5510258675e+00);
d2psiM_down[0][1] = ValueType(5.9720201492e+00, -5.9720129967e+00);
d2psiM_down[0][2] = ValueType(8.8568925858e-02, -8.8571548462e-02);
d2psiM_down[1][0] = ValueType(-2.0943276882e+00, 2.0943336487e+00);
d2psiM_down[1][1] = ValueType(4.9078116417e+00, -4.9078197479e+00);
d2psiM_down[1][2] = ValueType(-3.0689623952e-01, 3.0689093471e-01);
d2psiM_down[2][0] = ValueType(-7.8578405380e+00, 7.8578381538e+00);
d2psiM_down[2][1] = ValueType(1.9828968048e+01, -1.9828992844e+01);
d2psiM_down[2][2] = ValueType(4.2092007399e-01, -4.2091816664e-01);
//And now a looooot of gradient info.
////////SPIN UP//////////
dpsiM_up[0][0][0] = ValueType(-1.7161563039e-01, 1.7161482573e-01);
dpsiM_up[0][0][1] = ValueType(5.6693041325e-01, -5.6692999601e-01);
dpsiM_up[0][0][2] = ValueType(-4.5538558960e+00, 4.5538554192e+00);
dpsiM_up[0][1][0] = ValueType(-7.4953302741e-02, 7.4952393770e-02);
dpsiM_up[0][1][1] = ValueType(2.4608184397e-01, -2.4608163536e-01);
dpsiM_up[0][1][2] = ValueType(-1.9720511436e+00, 1.9720509052e+00);
dpsiM_up[0][2][0] = ValueType(-4.2384520173e-02, 4.2384237051e-02);
dpsiM_up[0][2][1] = ValueType(1.1735939980e-01, -1.1735984683e-01);
dpsiM_up[0][2][2] = ValueType(-3.1189033985e+00, 3.1189031601e+00);
dpsiM_up[1][0][0] = ValueType(1.9333077967e-01, -1.9333113730e-01);
dpsiM_up[1][0][1] = ValueType(-5.7470333576e-01, 5.7470202446e-01);
dpsiM_up[1][0][2] = ValueType(-4.5568108559e+00, 4.5568113327e+00);
dpsiM_up[1][1][0] = ValueType(8.4540992975e-02, -8.4540143609e-02);
dpsiM_up[1][1][1] = ValueType(-2.4946013093e-01, 2.4946044385e-01);
dpsiM_up[1][1][2] = ValueType(-1.9727530479e+00, 1.9727528095e+00);
dpsiM_up[1][2][0] = ValueType(3.1103719026e-02, -3.1103719026e-02);
dpsiM_up[1][2][1] = ValueType(-1.2540178001e-01, 1.2540178001e-01);
dpsiM_up[1][2][2] = ValueType(-3.1043677330e+00, 3.1043677330e+00);
dpsiM_up[2][0][0] = ValueType(-8.8733488321e-01, 8.8733488321e-01);
dpsiM_up[2][0][1] = ValueType(-1.7726477385e+00, 1.7726477385e+00);
dpsiM_up[2][0][2] = ValueType(7.3728728294e-01, -7.3728692532e-01);
dpsiM_up[2][1][0] = ValueType(-3.8018247485e-01, 3.8018330932e-01);
dpsiM_up[2][1][1] = ValueType(-7.5880718231e-01, 7.5880759954e-01);
dpsiM_up[2][1][2] = ValueType(2.7537062764e-01, -2.7537041903e-01);
dpsiM_up[2][2][0] = ValueType(-9.5389984548e-02, 9.5390148461e-02);
dpsiM_up[2][2][1] = ValueType(-1.8467208743e-01, 1.8467210233e-01);
dpsiM_up[2][2][2] = ValueType(-2.4704084396e+00, 2.4704084396e+00);
////////SPIN DOWN//////////
dpsiM_down[0][0][0] = ValueType(-7.1084961295e-02, 7.1085616946e-02);
dpsiM_down[0][0][1] = ValueType(2.3483029008e-01, -2.3482969403e-01);
dpsiM_down[0][0][2] = ValueType(-1.8862648010e+00, 1.8862643242e+00);
dpsiM_down[0][1][0] = ValueType(1.8095153570e-01, -1.8095159531e-01);
dpsiM_down[0][1][1] = ValueType(-5.9409534931e-01, 5.9409546852e-01);
dpsiM_down[0][1][2] = ValueType(4.7609643936e+00, -4.7609624863e+00);
dpsiM_down[0][2][0] = ValueType(-1.7556600273e-02, 1.7556769773e-02);
dpsiM_down[0][2][1] = ValueType(4.8611730337e-02, -4.8612065613e-02);
dpsiM_down[0][2][2] = ValueType(-1.2918885946e+00, 1.2918891907e+00);
dpsiM_down[1][0][0] = ValueType(8.0079451203e-02, -8.0079004169e-02);
dpsiM_down[1][0][1] = ValueType(-2.3804906011e-01, 2.3804855347e-01);
dpsiM_down[1][0][2] = ValueType(-1.8874882460e+00, 1.8874886036e+00);
dpsiM_down[1][1][0] = ValueType(-2.0409825444e-01, 2.0409949124e-01);
dpsiM_down[1][1][1] = ValueType(6.0225284100e-01, -6.0225236416e-01);
dpsiM_down[1][1][2] = ValueType(4.7626581192e+00, -4.7626576424e+00);
dpsiM_down[1][2][0] = ValueType(1.2884057127e-02, -1.2884397991e-02);
dpsiM_down[1][2][1] = ValueType(-5.1943197846e-02, 5.1943652332e-02);
dpsiM_down[1][2][2] = ValueType(-1.2858681679e+00, 1.2858685255e+00);
dpsiM_down[2][0][0] = ValueType(-3.6754500866e-01, 3.6754477024e-01);
dpsiM_down[2][0][1] = ValueType(-7.3425340652e-01, 7.3425388336e-01);
dpsiM_down[2][0][2] = ValueType(3.0539327860e-01, -3.0539402366e-01);
dpsiM_down[2][1][0] = ValueType(9.1784656048e-01, -9.1784602404e-01);
dpsiM_down[2][1][1] = ValueType(1.8319253922e+00, -1.8319247961e+00);
dpsiM_down[2][1][2] = ValueType(-6.6480386257e-01, 6.6480308771e-01);
dpsiM_down[2][2][0] = ValueType(-3.9511863142e-02, 3.9511814713e-02);
dpsiM_down[2][2][1] = ValueType(-7.6493337750e-02, 7.6493576169e-02);
dpsiM_down[2][2][2] = ValueType(-1.0232743025e+00, 1.0232743025e+00);
for (unsigned int iat = 0; iat < 3; iat++)
{
RealType s = elec_.spins[iat];
RealType coss(0.0), sins(0.0);
coss = std::cos(s);
sins = std::sin(s);
ValueType eis(coss, sins);
ValueType emis(coss, -sins);
ValueType eye(0, 1.0);
//Using the reference values for the up and down channels invdividually, we build the total reference spinor value
//consistent with the current spin value of particle iat.
psiM_ref[iat][0] = eis * psiM_up[iat][0] + emis * psiM_down[iat][0];
psiM_ref[iat][1] = eis * psiM_up[iat][1] + emis * psiM_down[iat][1];
psiM_ref[iat][2] = eis * psiM_up[iat][2] + emis * psiM_down[iat][2];
dspsiM_ref[iat][0] = eye * (eis * psiM_up[iat][0] - emis * psiM_down[iat][0]);
dspsiM_ref[iat][1] = eye * (eis * psiM_up[iat][1] - emis * psiM_down[iat][1]);
dspsiM_ref[iat][2] = eye * (eis * psiM_up[iat][2] - emis * psiM_down[iat][2]);
dpsiM_ref[iat][0] = eis * dpsiM_up[iat][0] + emis * dpsiM_down[iat][0];
dpsiM_ref[iat][1] = eis * dpsiM_up[iat][1] + emis * dpsiM_down[iat][1];
dpsiM_ref[iat][2] = eis * dpsiM_up[iat][2] + emis * dpsiM_down[iat][2];
d2psiM_ref[iat][0] = eis * d2psiM_up[iat][0] + emis * d2psiM_down[iat][0];
d2psiM_ref[iat][1] = eis * d2psiM_up[iat][1] + emis * d2psiM_down[iat][1];
d2psiM_ref[iat][2] = eis * d2psiM_up[iat][2] + emis * d2psiM_down[iat][2];
}
//OK. Going to test evaluate_notranspose with spin.
spo->evaluate_notranspose(elec_, 0, elec_.R.size(), psiM, dpsiM, d2psiM);
for (unsigned int iat = 0; iat < 3; iat++)
{
REQUIRE(psiM[iat][0] == ComplexApprox(psiM_ref[iat][0]));
REQUIRE(psiM[iat][1] == ComplexApprox(psiM_ref[iat][1]));
REQUIRE(psiM[iat][2] == ComplexApprox(psiM_ref[iat][2]));
REQUIRE(dpsiM[iat][0][0] == ComplexApprox(dpsiM_ref[iat][0][0]));
REQUIRE(dpsiM[iat][0][1] == ComplexApprox(dpsiM_ref[iat][0][1]));
REQUIRE(dpsiM[iat][0][2] == ComplexApprox(dpsiM_ref[iat][0][2]));
REQUIRE(dpsiM[iat][1][0] == ComplexApprox(dpsiM_ref[iat][1][0]));
REQUIRE(dpsiM[iat][1][1] == ComplexApprox(dpsiM_ref[iat][1][1]));
REQUIRE(dpsiM[iat][1][2] == ComplexApprox(dpsiM_ref[iat][1][2]));
REQUIRE(dpsiM[iat][2][0] == ComplexApprox(dpsiM_ref[iat][2][0]));
REQUIRE(dpsiM[iat][2][1] == ComplexApprox(dpsiM_ref[iat][2][1]));
REQUIRE(dpsiM[iat][2][2] == ComplexApprox(dpsiM_ref[iat][2][2]));
REQUIRE(d2psiM[iat][0] == ComplexApprox(d2psiM_ref[iat][0]));
REQUIRE(d2psiM[iat][1] == ComplexApprox(d2psiM_ref[iat][1]));
REQUIRE(d2psiM[iat][2] == ComplexApprox(d2psiM_ref[iat][2]));
}
//Now we're going to test evaluateValue and evaluateVGL:
int OrbitalSetSize = spo->getOrbitalSetSize();
//temporary arrays for holding the values of the up and down channels respectively.
SPOSet::ValueVector_t psi_work;
//temporary arrays for holding the gradients of the up and down channels respectively.
SPOSet::GradVector_t dpsi_work;
//temporary arrays for holding the laplacians of the up and down channels respectively.
SPOSet::ValueVector_t d2psi_work;
psi_work.resize(OrbitalSetSize);
dpsi_work.resize(OrbitalSetSize);
d2psi_work.resize(OrbitalSetSize);
//We worked hard to generate nice reference data above. Let's generate a test for evaluateV
//and evaluateVGL by perturbing the electronic configuration by dR, and then make
//single particle moves that bring it back to our original R reference values.
//Our perturbation vector.
ParticleSet::ParticlePos_t dR;
dR.resize(3);
//Values chosen based on divine inspiration. Not important.
dR[0][0] = 0.1;
dR[0][1] = 0.2;
dR[0][2] = 0.1;
dR[1][0] = -0.1;
dR[1][1] = -0.05;
dR[1][2] = 0.05;
dR[2][0] = -0.1;
dR[2][1] = 0.0;
dR[2][2] = 0.0;
//The new R of our perturbed particle set.
ParticleSet::ParticlePos_t Rnew;
Rnew.resize(3);
Rnew = elec_.R + dR;
elec_.R = Rnew;
elec_.update();
//Now we test evaluateValue()
for (unsigned int iat = 0; iat < 3; iat++)
{
psi_work = 0.0;
elec_.makeMove(iat, -dR[iat], false);
spo->evaluateValue(elec_, iat, psi_work);
REQUIRE(psi_work[0] == ComplexApprox(psiM_ref[iat][0]));
REQUIRE(psi_work[1] == ComplexApprox(psiM_ref[iat][1]));
REQUIRE(psi_work[2] == ComplexApprox(psiM_ref[iat][2]));
elec_.rejectMove(iat);
}
//Now we test evaluateVGL()
for (unsigned int iat = 0; iat < 3; iat++)
{
psi_work = 0.0;
dpsi_work = 0.0;
d2psi_work = 0.0;
elec_.makeMove(iat, -dR[iat], false);
spo->evaluateVGL(elec_, iat, psi_work, dpsi_work, d2psi_work);
REQUIRE(psi_work[0] == ComplexApprox(psiM_ref[iat][0]));
REQUIRE(psi_work[1] == ComplexApprox(psiM_ref[iat][1]));
REQUIRE(psi_work[2] == ComplexApprox(psiM_ref[iat][2]));
REQUIRE(dpsi_work[0][0] == ComplexApprox(dpsiM_ref[iat][0][0]));
REQUIRE(dpsi_work[0][1] == ComplexApprox(dpsiM_ref[iat][0][1]));
REQUIRE(dpsi_work[0][2] == ComplexApprox(dpsiM_ref[iat][0][2]));
REQUIRE(dpsi_work[1][0] == ComplexApprox(dpsiM_ref[iat][1][0]));
REQUIRE(dpsi_work[1][1] == ComplexApprox(dpsiM_ref[iat][1][1]));
REQUIRE(dpsi_work[1][2] == ComplexApprox(dpsiM_ref[iat][1][2]));
REQUIRE(dpsi_work[2][0] == ComplexApprox(dpsiM_ref[iat][2][0]));
REQUIRE(dpsi_work[2][1] == ComplexApprox(dpsiM_ref[iat][2][1]));
REQUIRE(dpsi_work[2][2] == ComplexApprox(dpsiM_ref[iat][2][2]));
REQUIRE(d2psi_work[0] == ComplexApprox(d2psiM_ref[iat][0]));
REQUIRE(d2psi_work[1] == ComplexApprox(d2psiM_ref[iat][1]));
REQUIRE(d2psi_work[2] == ComplexApprox(d2psiM_ref[iat][2]));
elec_.rejectMove(iat);
}
//Now we test evaluateSpin:
SPOSet::ValueVector_t dspsi_work;
dspsi_work.resize(OrbitalSetSize);
for (unsigned int iat = 0; iat < 3; iat++)
{
psi_work = 0.0;
dspsi_work = 0.0;
elec_.makeMove(iat, -dR[iat], false);
spo->evaluate_spin(elec_, iat, psi_work, dspsi_work);
REQUIRE(psi_work[0] == ComplexApprox(psiM_ref[iat][0]));
REQUIRE(psi_work[1] == ComplexApprox(psiM_ref[iat][1]));
REQUIRE(psi_work[2] == ComplexApprox(psiM_ref[iat][2]));
REQUIRE(dspsi_work[0] == ComplexApprox(dspsiM_ref[iat][0]));
REQUIRE(dspsi_work[1] == ComplexApprox(dspsiM_ref[iat][1]));
REQUIRE(dspsi_work[2] == ComplexApprox(dspsiM_ref[iat][2]));
elec_.rejectMove(iat);
}
}
#endif //QMC_COMPLEX
} // namespace qmcplusplus
| 43.505882
| 182
| 0.669605
|
kayahans
|
ccedd60d98c2a361b0bdc6a2daf26844379be7bf
| 1,550
|
cpp
|
C++
|
gui/previewer/Previewer.cpp
|
ERPShuen/ICQ1
|
f319a72ad60aae4809eef0e4eb362f4d69292296
|
[
"Apache-2.0"
] | 1
|
2019-12-02T08:37:10.000Z
|
2019-12-02T08:37:10.000Z
|
gui/previewer/Previewer.cpp
|
ERPShuen/ICQ1
|
f319a72ad60aae4809eef0e4eb362f4d69292296
|
[
"Apache-2.0"
] | null | null | null |
gui/previewer/Previewer.cpp
|
ERPShuen/ICQ1
|
f319a72ad60aae4809eef0e4eb362f4d69292296
|
[
"Apache-2.0"
] | null | null | null |
#include "stdafx.h"
#include "Previewer.h"
#include "../main_window/MainWindow.h"
#include "../utils/InterConnector.h"
#include "../../corelib/enumerations.h"
#include "../../gui.shared/implayer.h"
#include "../utils/utils.h"
namespace
{
std::unique_ptr<QWidget> PreviewWidget_;
std::unique_ptr<QWidget> g_multimediaViewer;
}
const char* mplayer_exe = "mplayer.exe";
namespace Previewer
{
void ShowMedia(const core::file_sharing_content_type /*_contentType*/, const QString& _path)
{
if (platform::is_windows())
{
// const auto exePath = QCoreApplication::applicationFilePath();
//
// const auto forder = QFileInfo(exePath).path();
//
// const int scale = Utils::scale_value(100);
//
// const int screenNumber = Utils::InterConnector::instance().getMainWindow()->getScreen();
//
// const QString command = "\"" + forder + "/" + QString(mplayer_exe) + "\"" + QString(" /media \"") + _path + "\"" + " /scale " + QString::number(scale) + " /screen_number " + QString::number(screenNumber);
//
// QProcess::startDetached(command);
}
else
{
QUrl url = QUrl::fromLocalFile(_path);
if (!url.isLocalFile() || !platform::is_apple())
url = QUrl(QDir::fromNativeSeparators(_path));
QDesktopServices::openUrl(url);
}
}
void CloseMedia()
{
g_multimediaViewer.reset();
}
}
namespace
{
}
| 27.678571
| 220
| 0.574839
|
ERPShuen
|
ccee09a4cf7e1da94d802e73212aa239db62006d
| 151
|
cpp
|
C++
|
components/eam/src/physics/crm/samxx/diffuse_mom.cpp
|
Fa-Li/E3SM
|
a91995093ec6fc0dd6e50114f3c70b5fb64de0f0
|
[
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | 235
|
2018-04-23T16:30:06.000Z
|
2022-03-21T17:53:12.000Z
|
components/eam/src/physics/crm/samxx/diffuse_mom.cpp
|
Fa-Li/E3SM
|
a91995093ec6fc0dd6e50114f3c70b5fb64de0f0
|
[
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | 2,372
|
2018-04-20T18:12:34.000Z
|
2022-03-31T23:43:17.000Z
|
components/eam/src/physics/crm/samxx/diffuse_mom.cpp
|
Fa-Li/E3SM
|
a91995093ec6fc0dd6e50114f3c70b5fb64de0f0
|
[
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | 254
|
2018-04-20T20:43:32.000Z
|
2022-03-30T20:13:38.000Z
|
#include "diffuse_mom.h"
void diffuse_mom() {
if (RUN3D) {
diffuse_mom3D(sgs_field_diag);
} else {
diffuse_mom2D(sgs_field_diag);
}
}
| 12.583333
| 34
| 0.655629
|
Fa-Li
|
ccf059187eb3c8bccf715f1eae37d74469aa3c52
| 1,684
|
hpp
|
C++
|
include/memory/hadesmem/detail/force_initialize.hpp
|
CvX/hadesmem
|
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
|
[
"MIT"
] | 24
|
2018-08-18T18:05:37.000Z
|
2021-09-28T00:26:35.000Z
|
include/memory/hadesmem/detail/force_initialize.hpp
|
CvX/hadesmem
|
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
|
[
"MIT"
] | null | null | null |
include/memory/hadesmem/detail/force_initialize.hpp
|
CvX/hadesmem
|
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
|
[
"MIT"
] | 9
|
2018-04-16T09:53:09.000Z
|
2021-02-26T05:04:49.000Z
|
// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <array>
#include <windows.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/remote_thread.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/write.hpp>
namespace hadesmem
{
namespace detail
{
// This is used to generate a 'nullsub' function, which is called
// in the context of the remote process in order to 'force' a
// call to ntdll.dll!LdrInitializeThunk. This is necessary
// because module enumeration will fail if LdrInitializeThunk has
// not been called, and Injector::InjectDll (and the APIs it
// uses) depends on the module enumeration APIs.
inline void ForceLdrInitializeThunk(DWORD proc_id)
{
Process const process{proc_id};
#if defined(HADESMEM_DETAIL_ARCH_X64)
// RET
std::array<BYTE, 1> const return_instr = {{0xC3}};
#elif defined(HADESMEM_DETAIL_ARCH_X86)
// RET 4
std::array<BYTE, 3> const return_instr = {{0xC2, 0x04, 0x00}};
#else
#error "[HadesMem] Unsupported architecture."
#endif
HADESMEM_DETAIL_TRACE_A("Allocating memory for remote stub.");
Allocator const stub_remote{process, sizeof(return_instr)};
HADESMEM_DETAIL_TRACE_A("Writing remote stub.");
Write(process, stub_remote.GetBase(), return_instr);
auto const stub_remote_pfn = reinterpret_cast<LPTHREAD_START_ROUTINE>(
reinterpret_cast<DWORD_PTR>(stub_remote.GetBase()));
HADESMEM_DETAIL_TRACE_A("Starting remote thread.");
CreateRemoteThreadAndWait(process, stub_remote_pfn);
HADESMEM_DETAIL_TRACE_A("Remote thread complete.");
}
}
}
| 28.542373
| 73
| 0.736342
|
CvX
|
ccf1d89f4b4f212721515d1d3cc2aabfa14856a5
| 1,807
|
cpp
|
C++
|
1 term/2/3/A/A.cpp
|
alexkats/Discrete-Math
|
dd4edd9ff9322e319d162d56567b9d81a6636373
|
[
"Unlicense"
] | null | null | null |
1 term/2/3/A/A.cpp
|
alexkats/Discrete-Math
|
dd4edd9ff9322e319d162d56567b9d81a6636373
|
[
"Unlicense"
] | null | null | null |
1 term/2/3/A/A.cpp
|
alexkats/Discrete-Math
|
dd4edd9ff9322e319d162d56567b9d81a6636373
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <cassert>
#include <ctime>
#include <stack>
#include <queue>
#include <deque>
#include <utility>
#include <iterator>
#define NAME "nextvector"
#define INF 1000000000
#define EPS 0.000000001
#define sqr(a) a*a
#define mp make_pair
#define pb push_back
#define rep0(i, n) for (int i = 0; i < n; i++)
#define rep(i, l, r) for (int i = l; i < r; i++)
#define repd0(i, n) for (int i = (n - 1); i > -1; i--)
#define repd(i, l, r) for (int i = (r - 1); i > (l - 1); i--)
typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;
using namespace std;
string s;
string solve1 (string s)
{
int n = s.length ();
rep0(i, n)
if (s [i] == '0')
s [i] = '1';
else
{
s [i] = '0';
break;
}
rep0(i, n / 2)
swap (s [i], s [n - i - 1]);
return s;
}
string solve2 (string s)
{
int n = s.length ();
rep0(i, n)
if (s [i] == '1')
s [i] = '0';
else
{
s [i] = '1';
break;
}
rep0(i, n / 2)
swap (s [i], s [n - i - 1]);
return s;
}
int main ()
{
freopen (NAME".in", "r", stdin);
freopen (NAME".out", "w", stdout);
cin >> s;
int n = s.length ();
rep0(i, n / 2)
swap (s [i], s [n - i - 1]);
bool z0 = false;
bool z1 = false;
string ans1 = "";
string ans2 = "";
rep0(i, n)
{
if (s [i] != '0')
z0 = true;
if (s [i] != '1')
z1 = true;
}
if (!z0)
ans1 = "-";
else
ans1 = solve1 (s);
if (!z1)
ans2 = "-";
else
ans2 = solve2 (s);
cout << ans1 << endl;
cout << ans2 << endl;
return 0;
}
| 15.444444
| 62
| 0.50249
|
alexkats
|
ccf5f771d0469f00cb4cc1d90ea48201f516bf7e
| 1,277
|
cpp
|
C++
|
src/ScorePeg.cpp
|
DarkMaguz/mastermind-gtkmm
|
4abfd70c81e4fb7688898cb4d55610216d75eeb8
|
[
"MIT"
] | null | null | null |
src/ScorePeg.cpp
|
DarkMaguz/mastermind-gtkmm
|
4abfd70c81e4fb7688898cb4d55610216d75eeb8
|
[
"MIT"
] | null | null | null |
src/ScorePeg.cpp
|
DarkMaguz/mastermind-gtkmm
|
4abfd70c81e4fb7688898cb4d55610216d75eeb8
|
[
"MIT"
] | null | null | null |
/*
* ScorePeg.cpp
*
* Created on: Nov 18, 2021
* Author: magnus
*/
#include "ScorePeg.h"
ScorePeg::ScorePeg() :
m_score(MasterMind::NONE)
{
set_size_request(20, 20);
//show_all_children();
}
ScorePeg::~ScorePeg()
{
}
void ScorePeg::setScore(const MasterMind::score& score)
{
m_score = score;
// Request redrawing of widget.
queue_draw();
}
bool ScorePeg::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
rgbColor color;
if (m_score == MasterMind::HIT)
color = {0., 0., 0.};
else if (m_score == MasterMind::MISS)
color = {1., 1., 1.};
else
{
reset_style();
return false;
}
// This is where we draw on the window
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
const int lesser = MIN(width, height);
// coordinates for the center of the window
int xc, yc;
xc = width / 2;
yc = height / 2;
// outline thickness changes with window size
cr->set_line_width(lesser * 0.02);
// now draw a circle
cr->save();
cr->arc(xc, yc, lesser / 4.0, 0.0, 2.0 * M_PI); // full circle
cr->set_source_rgb(color.red, color.green, color.blue);
cr->fill_preserve();
cr->restore(); // back to opaque black
cr->stroke();
return false;
}
| 19.348485
| 64
| 0.648395
|
DarkMaguz
|
ccf7ec1dcc93d8a545e8911fc4acaa7925ef9731
| 888
|
cpp
|
C++
|
src/13merge.cpp
|
baseoursteps/faang
|
8508b3bd66a607fa4ff5a71efd9e2a25a2a263d5
|
[
"MIT"
] | 1
|
2021-07-13T19:47:57.000Z
|
2021-07-13T19:47:57.000Z
|
src/13merge.cpp
|
baseoursteps/faang
|
8508b3bd66a607fa4ff5a71efd9e2a25a2a263d5
|
[
"MIT"
] | 1
|
2021-05-07T15:02:27.000Z
|
2021-05-09T08:44:05.000Z
|
src/13merge.cpp
|
baseoursteps/faang
|
8508b3bd66a607fa4ff5a71efd9e2a25a2a263d5
|
[
"MIT"
] | 1
|
2021-05-07T13:18:01.000Z
|
2021-05-07T13:18:01.000Z
|
#include <algorithm>
#include <iostream>
#include <vector>
struct interval
{
int start { -1 }, end { -1 };
interval(int a, int b) : start(a), end(b) {}
bool
operator<(const interval &o) const
{
return start < o.start;
}
};
int
main()
{
using namespace std;
vector<interval> vals { { 11, 15 }, { 1, 3 }, { 0, 2 }, { 3, 5 },
{ 6, 8 }, { 9, 10 }, { 16, 20 } };
for (auto &&i : vals)
cout << i.start << "->" << i.end << "\n";
sort(vals.begin(), vals.end());
for (int i = 0; i < vals.size() - 1;) {
if (vals[i].end >= vals[i + 1].start) {
vals[i].end = vals[i + 1].end;
vals.erase(vals.begin() + i + 1);
} else
++i;
}
cout << "\nMerged:\n";
for (auto &&i : vals)
cout << i.start << "->" << i.end << "\n";
return 0;
}
| 20.651163
| 71
| 0.427928
|
baseoursteps
|
ccf943e42d13ae924ebf1fc082f4bd04a5a594c6
| 2,532
|
cxx
|
C++
|
src/Filtering/BinaryMathematicalMorphology/ThinImage/Code.cxx
|
kian-weimer/ITKSphinxExamples
|
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
|
[
"Apache-2.0"
] | 34
|
2015-01-26T19:38:36.000Z
|
2021-02-04T02:15:41.000Z
|
src/Filtering/BinaryMathematicalMorphology/ThinImage/Code.cxx
|
kian-weimer/ITKSphinxExamples
|
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
|
[
"Apache-2.0"
] | 142
|
2016-01-22T15:59:25.000Z
|
2021-03-17T15:11:19.000Z
|
src/Filtering/BinaryMathematicalMorphology/ThinImage/Code.cxx
|
kian-weimer/ITKSphinxExamples
|
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
|
[
"Apache-2.0"
] | 32
|
2015-01-26T19:38:41.000Z
|
2021-03-17T15:28:14.000Z
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkBinaryThinningImageFilter.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
using ImageType = itk::Image<unsigned char, 2>;
static void
CreateImage(ImageType::Pointer image);
int
main(int argc, char * argv[])
{
ImageType::Pointer image = ImageType::New();
if (argc == 2)
{
image = itk::ReadImage<ImageType>(argv[1]);
}
else
{
CreateImage(image);
itk::WriteImage(image, "Input.png");
}
using BinaryThinningImageFilterType = itk::BinaryThinningImageFilter<ImageType, ImageType>;
BinaryThinningImageFilterType::Pointer binaryThinningImageFilter = BinaryThinningImageFilterType::New();
binaryThinningImageFilter->SetInput(image);
binaryThinningImageFilter->Update();
// Rescale the image so that it can be seen (the output is 0 and 1, we want 0 and 255)
using RescaleType = itk::RescaleIntensityImageFilter<ImageType, ImageType>;
RescaleType::Pointer rescaler = RescaleType::New();
rescaler->SetInput(binaryThinningImageFilter->GetOutput());
rescaler->SetOutputMinimum(0);
rescaler->SetOutputMaximum(255);
rescaler->Update();
itk::WriteImage(rescaler->GetOutput(), "Output.png");
return EXIT_SUCCESS;
}
void
CreateImage(ImageType::Pointer image)
{
// Create an image
ImageType::IndexType start;
start.Fill(0);
ImageType::SizeType size;
size.Fill(100);
ImageType::RegionType region(start, size);
image->SetRegions(region);
image->Allocate();
image->FillBuffer(0);
// Draw a 5 pixel wide line
for (unsigned int i = 20; i < 80; ++i)
{
for (unsigned int j = 50; j < 55; ++j)
{
itk::Index<2> index;
index[0] = i;
index[1] = j;
image->SetPixel(index, 255);
}
}
}
| 28.449438
| 106
| 0.664297
|
kian-weimer
|
ccfd8be8e8655529c7f77980743cf67f842fc07f
| 1,759
|
cpp
|
C++
|
Graph Theory/Union-Find (Disjoint-Sets) and MST/prim.cpp
|
hoanghai1803/DataStructures_Algorithms
|
b5e8ccb3deba7566b915b21c6b7e9435cfe55301
|
[
"MIT"
] | 1
|
2021-03-06T00:36:08.000Z
|
2021-03-06T00:36:08.000Z
|
Graph Theory/Union-Find (Disjoint-Sets) and MST/prim.cpp
|
hoanghai1803/DataStructures_Algorithms
|
b5e8ccb3deba7566b915b21c6b7e9435cfe55301
|
[
"MIT"
] | null | null | null |
Graph Theory/Union-Find (Disjoint-Sets) and MST/prim.cpp
|
hoanghai1803/DataStructures_Algorithms
|
b5e8ccb3deba7566b915b21c6b7e9435cfe55301
|
[
"MIT"
] | null | null | null |
/* ========== PRIM'S ALGORITHM IMPLEMENTATION ========== */
// This implementation of Prim's algorithm calculates the minimum
// weight spanning tree of the weighted undirected graph with non-negative
// edge weights. We assume that the graph is connected.
// Time complexity:
// Using adjacency matrix: O(V^2)
// Using adjacency list (+ binary heap): O(max(V, E) * log_2(V)) - Implemented bellow
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#define INF INT_MAX
#define N 100005
typedef std::pair<int, int> Edge;
int n, m; // The number of vertices and edges
std::vector<Edge> adj[N]; // Adjacency List
int cost[N]; // cost[u] - cost of vertex u
void Prim() {
// Initialize minCost = 0 (minimum cost of spanning tree).
int minCost = 0;
int u, v, costU;
// Initialize cost of all vertices = +oo, except cost[1] = 0.
for (int u = 2; u <= n; u++) cost[u] = +INF;
cost[1] = 0;
std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge> > Heap; // Min Heap
Heap.push(Edge(cost[1], 1)); // Push vertex 1 and its cost into Min Heap
while (Heap.size()) {
u = Heap.top().second, costU = Heap.top().first;
Heap.pop();
if (costU != cost[u]) continue;
minCost += cost[u];
cost[u] = 0;
for (Edge e: adj[u]) {
if (cost[v = e.first] > e.second) {
cost[v] = e.second;
Heap.push(Edge(cost[v], v));
}
}
}
std::cout << minCost << "\n";
}
// Driver code
int main() {
std::cin >> n >> m;
while (m--) {
int u, v, w;
std::cin >> u >> v >> w;
adj[u].push_back(Edge(v, w));
adj[v].push_back(Edge(u, w));
}
Prim();
}
| 25.492754
| 87
| 0.554292
|
hoanghai1803
|
ccff98407b71a41ddc6d1cfe4c03e22bb036ff48
| 738
|
cpp
|
C++
|
Curso/PILHA.cpp
|
Pedro-H-Castoldi/c-
|
a01cec85559efec8c84bef142119d83dad12bb1e
|
[
"Apache-2.0"
] | null | null | null |
Curso/PILHA.cpp
|
Pedro-H-Castoldi/c-
|
a01cec85559efec8c84bef142119d83dad12bb1e
|
[
"Apache-2.0"
] | null | null | null |
Curso/PILHA.cpp
|
Pedro-H-Castoldi/c-
|
a01cec85559efec8c84bef142119d83dad12bb1e
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack <string> cartas;
cartas.push("Carta 1");
cartas.push("Carta 2");
cartas.push("Carta 3");
cartas.push("carta 4");
/*while (!cartas.empty()){ // Maneira de excluir elementos da Pilha
cartas.pop();
}*/
if(cartas.empty()){
cout << "Pilha vazia\n\n";
return 0;
}
else{
cout << "Pilha com cartas\n\n";
}
/* cout << "Quantidade de cartas: " << cartas.size() << "\n";
cartas.pop();
cout << "Quantidade de cartas: " << cartas.size() << "\n";
cout << "Carta do topo: "<< cartas.top();*/
for (int i=0; i<4; i++){
cout << "Carta do topo: " << cartas.top() << "\n\n"; // Mostrar os valores da Pilha.
cartas.pop();
}
return 0;
}
| 18.923077
| 86
| 0.574526
|
Pedro-H-Castoldi
|
6905dfe09a3904ce69ca6b5d0687257e919975aa
| 1,427
|
cpp
|
C++
|
PIXEL2D/Utilities/StringExtensions.cpp
|
Maxchii/PIXEL2D
|
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
|
[
"Apache-2.0"
] | 1
|
2015-05-18T15:20:19.000Z
|
2015-05-18T15:20:19.000Z
|
PIXEL2D/Utilities/StringExtensions.cpp
|
Ossadtchii/PIXEL2D
|
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
|
[
"Apache-2.0"
] | 5
|
2015-05-18T15:21:28.000Z
|
2015-06-28T12:43:52.000Z
|
PIXEL2D/Utilities/StringExtensions.cpp
|
Maxchii/PIXEL2D
|
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
|
[
"Apache-2.0"
] | null | null | null |
#include "StringExtensions.h"
#include <sstream>
namespace PIXL { namespace utilities {
void GetWords(std::string s, std::vector<std::string>& words)
{
UInt32 end = 0;
while (s.size() > 0)
{
for (unsigned int i = 0; i < s.size(); i++)
{
if (s[i] == ' ')
{
end = i;
string word = s.substr(0, end);
s.erase(s.begin(), s.begin() + end + 1);
words.push_back(word);
break;
}
else if (i == s.size() - 1)
{
end = i;
string word = s.substr(0, end + 1);
s.clear();
words.push_back(word);
break;
}
}
}
}
std::vector<std::string> SplitString(const std::string &s, char delimeter)
{
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delimeter))
{
elems.push_back(item);
}
return elems;
}
std::string F2S(Float32 val)
{
std::stringstream stream;
stream << val;
std::string sValue = stream.str();
val = S2F(sValue);
if (val == (int)val)
{
sValue.append(".0");
}
return sValue;
}
std::string I2S(SInt32 val)
{
std::stringstream stream;
stream << val;
return stream.str();
}
Float32 S2F(const std::string& s)
{
std::stringstream stream(s);
float value = 0.0f;
stream >> value;
return value;
}
SInt32 S2I(const std::string& s)
{
std::stringstream stream(s);
SInt32 value = 0;
stream >> value;
return value;
}
} }
| 17.192771
| 75
| 0.576034
|
Maxchii
|
690c1ea3a04477e1258114150bfd6cd416334903
| 4,644
|
cpp
|
C++
|
xcore/smart_analyzer.cpp
|
zongwave/libxcam
|
2c0cc6839ddd3ef2b6ad22d2580f7878314daf14
|
[
"Apache-2.0"
] | 400
|
2018-01-26T05:33:23.000Z
|
2022-03-31T06:36:47.000Z
|
xcore/smart_analyzer.cpp
|
zihengchang/libxcam
|
53e2b415f9f20ab315de149afdfee97574aeaad0
|
[
"Apache-2.0"
] | 77
|
2018-01-25T06:16:15.000Z
|
2022-02-23T02:50:49.000Z
|
xcore/smart_analyzer.cpp
|
zihengchang/libxcam
|
53e2b415f9f20ab315de149afdfee97574aeaad0
|
[
"Apache-2.0"
] | 161
|
2018-03-05T01:03:42.000Z
|
2022-03-29T17:14:20.000Z
|
/*
* smart_analyzer.cpp - smart analyzer
*
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Zong Wei <wei.zong@intel.com>
*/
#include "smart_analyzer_loader.h"
#include "smart_analyzer.h"
#include "smart_analysis_handler.h"
#include "xcam_obj_debug.h"
namespace XCam {
SmartAnalyzer::SmartAnalyzer (const char *name)
: XAnalyzer (name)
{
XCAM_OBJ_PROFILING_INIT;
}
SmartAnalyzer::~SmartAnalyzer ()
{
}
XCamReturn
SmartAnalyzer::add_handler (SmartPtr<SmartAnalysisHandler> handler)
{
XCamReturn ret = XCAM_RETURN_NO_ERROR;
if (!handler.ptr ()) {
return XCAM_RETURN_ERROR_PARAM;
}
_handlers.push_back (handler);
handler->set_analyzer (this);
return ret;
}
XCamReturn
SmartAnalyzer::create_handlers ()
{
XCamReturn ret = XCAM_RETURN_NO_ERROR;
if (_handlers.empty ()) {
ret = XCAM_RETURN_ERROR_PARAM;
}
return ret;
}
XCamReturn
SmartAnalyzer::release_handlers ()
{
XCamReturn ret = XCAM_RETURN_NO_ERROR;
return ret;
}
XCamReturn
SmartAnalyzer::internal_init (uint32_t width, uint32_t height, double framerate)
{
XCAM_UNUSED (width);
XCAM_UNUSED (height);
XCAM_UNUSED (framerate);
SmartHandlerList::iterator i_handler = _handlers.begin ();
for (; i_handler != _handlers.end (); ++i_handler)
{
SmartPtr<SmartAnalysisHandler> handler = *i_handler;
XCamReturn ret = handler->create_context (handler);
if (ret != XCAM_RETURN_NO_ERROR) {
XCAM_LOG_WARNING ("smart analyzer initialize handler(%s) context failed", XCAM_STR(handler->get_name()));
}
}
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
SmartAnalyzer::internal_deinit ()
{
SmartHandlerList::iterator i_handler = _handlers.begin ();
for (; i_handler != _handlers.end (); ++i_handler)
{
SmartPtr<SmartAnalysisHandler> handler = *i_handler;
if (handler->is_valid ())
handler->destroy_context ();
}
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
SmartAnalyzer::configure ()
{
XCamReturn ret = XCAM_RETURN_NO_ERROR;
return ret;
}
XCamReturn
SmartAnalyzer::update_params (XCamSmartAnalysisParam ¶ms)
{
XCamReturn ret = XCAM_RETURN_NO_ERROR;
SmartHandlerList::iterator i_handler = _handlers.begin ();
for (; i_handler != _handlers.end (); ++i_handler)
{
SmartPtr<SmartAnalysisHandler> handler = *i_handler;
if (!handler->is_valid ())
continue;
ret = handler->update_params (params);
if (ret != XCAM_RETURN_NO_ERROR) {
XCAM_LOG_WARNING ("smart analyzer update handler(%s) context failed", XCAM_STR(handler->get_name()));
handler->destroy_context ();
}
}
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
SmartAnalyzer::analyze (const SmartPtr<VideoBuffer> &buffer)
{
XCAM_OBJ_PROFILING_START;
XCamReturn ret = XCAM_RETURN_NO_ERROR;
X3aResultList results;
if (!buffer.ptr ()) {
XCAM_LOG_DEBUG ("SmartAnalyzer::analyze got NULL buffer!");
return XCAM_RETURN_ERROR_PARAM;
}
SmartHandlerList::iterator i_handler = _handlers.begin ();
for (; i_handler != _handlers.end (); ++i_handler)
{
SmartPtr<SmartAnalysisHandler> handler = *i_handler;
if (!handler->is_valid ())
continue;
ret = handler->analyze (buffer, results);
if (ret != XCAM_RETURN_NO_ERROR && ret != XCAM_RETURN_BYPASS) {
XCAM_LOG_WARNING ("smart analyzer analyze handler(%s) context failed", XCAM_STR(handler->get_name()));
handler->destroy_context ();
}
}
if (!results.empty ()) {
set_results_timestamp (results, buffer->get_timestamp ());
notify_calculation_done (results);
}
XCAM_OBJ_PROFILING_END ("smart analysis", XCAM_OBJ_DUR_FRAME_NUM);
return XCAM_RETURN_NO_ERROR;
}
void
SmartAnalyzer::post_smart_results (X3aResultList &results, int64_t timestamp)
{
if (!results.empty ()) {
set_results_timestamp (results, timestamp);
notify_calculation_done (results);
}
}
}
| 25.944134
| 117
| 0.680233
|
zongwave
|
690eddb5ac828cb5061e5482d514dd2ee0d81b27
| 1,531
|
cpp
|
C++
|
acwing/winter/1113. 红与黑.cpp
|
xmmmmmovo/MyAlgorithmSolutions
|
f5198d438f36f41cc4f72d53bb71d474365fa80d
|
[
"MIT"
] | 1
|
2020-03-26T13:40:52.000Z
|
2020-03-26T13:40:52.000Z
|
acwing/winter/1113. 红与黑.cpp
|
xmmmmmovo/MyAlgorithmSolutions
|
f5198d438f36f41cc4f72d53bb71d474365fa80d
|
[
"MIT"
] | null | null | null |
acwing/winter/1113. 红与黑.cpp
|
xmmmmmovo/MyAlgorithmSolutions
|
f5198d438f36f41cc4f72d53bb71d474365fa80d
|
[
"MIT"
] | null | null | null |
/**
* author: xmmmmmovo
* generation time: 2021/01/12
* filename: red_and_black.cpp
* language & build version : C 11 & C++ 17
*/
#include <algorithm>
#include <iostream>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
char g[25][25];
int n, m;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
// 宽度优先搜索
int dfs(int i, int j) {
int res = 1;
g[i][j] = '#';
for (int k = 0; k < 4; k++) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == '.')
res += dfs(x, y);
}
return res;
}
// 广度优先搜索
int bfs(int i, int j) {
queue<PII> q;
q.push({i, j});
g[i][j] = '#';
int res = 0;
while (q.size()) {
auto tmp = q.front();
q.pop();
res++;
for (int i = 0; i < 4; i++) {
int x = tmp.x + dx[i], y = tmp.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] != '.') continue;
g[x][y] = '#';
q.push({x, y});
}
}
return res;
}
int main() {
out: while (scanf("%d %d", &m, &n), n || m) {
for (int i = 0; i < n; i++) {
scanf("%s", &g[i]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '@') {
// printf("%d\n", bfs(i, j));
printf("%d\n", dfs(i, j));
goto out;
}
}
}
}
return 0;
}
| 20.413333
| 79
| 0.367734
|
xmmmmmovo
|
691328ec21e9bae7dd92209d732428dfda11a04d
| 2,656
|
hpp
|
C++
|
sdk/attestation/azure-security-attestation/src/private/crypto/openssl/openssl_helpers.hpp
|
JinmingHu-MSFT/azure-sdk-for-cpp
|
933486385a54a5a09a7444dbd823425f145ad75a
|
[
"MIT"
] | 1
|
2022-01-19T22:54:41.000Z
|
2022-01-19T22:54:41.000Z
|
sdk/attestation/azure-security-attestation/src/private/crypto/openssl/openssl_helpers.hpp
|
LarryOsterman/azure-sdk-for-cpp
|
d96216f50909a2bd39b555c9088f685bf0f7d6e6
|
[
"MIT"
] | null | null | null |
sdk/attestation/azure-security-attestation/src/private/crypto/openssl/openssl_helpers.hpp
|
LarryOsterman/azure-sdk-for-cpp
|
d96216f50909a2bd39b555c9088f685bf0f7d6e6
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#pragma once
#include <memory>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace Azure { namespace Security { namespace Attestation { namespace _detail {
// Helpers to provide RAII wrappers for OpenSSL types.
template <typename T, void (&Deleter)(T*)> struct openssl_deleter
{
void operator()(T* obj) { Deleter(obj); }
};
template <typename T, void (&FreeFunc)(T*)>
using basic_openssl_unique_ptr = std::unique_ptr<T, openssl_deleter<T, FreeFunc>>;
// *** Given just T, map it to the corresponding FreeFunc:
template <typename T> struct type_map_helper;
template <> struct type_map_helper<EVP_PKEY>
{
using type = basic_openssl_unique_ptr<EVP_PKEY, EVP_PKEY_free>;
};
template <> struct type_map_helper<BIO>
{
using type = basic_openssl_unique_ptr<BIO, BIO_free_all>;
};
// *** Now users can say openssl_unique_ptr<T> if they want:
template <typename T> using openssl_unique_ptr = typename type_map_helper<T>::type;
// *** Or the current solution's convenience aliases:
using openssl_evp_pkey = openssl_unique_ptr<EVP_PKEY>;
using openssl_bio = openssl_unique_ptr<BIO>;
#ifdef __cpp_nontype_template_parameter_auto
// *** Wrapper function that calls a given OpensslApi, and returns the corresponding
// openssl_unique_ptr<T>:
template <auto OpensslApi, typename... Args> auto make_openssl_unique(Args&&... args)
{
auto raw = OpensslApi(
forward<Args>(args)...); // forwarding is probably unnecessary, could use const Args&...
// check raw
using T = remove_pointer_t<decltype(raw)>; // no need to request T when we can see
// what OpensslApi returned
return openssl_unique_ptr<T>{raw};
}
#else // ^^^ C++17 ^^^ / vvv C++14 vvv
template <typename Api, typename... Args>
auto make_openssl_unique(Api& OpensslApi, Args&&... args)
{
auto raw = OpensslApi(std::forward<Args>(
args)...); // forwarding is probably unnecessary, could use const Args&...
// check raw
using T = std::remove_pointer_t<decltype(raw)>; // no need to request T when we can see
// what OpensslApi returned
return openssl_unique_ptr<T>{raw};
}
#endif // ^^^ C++14 ^^^
extern std::string GetOpenSSLError(std::string const& what);
struct OpenSSLException : public std::runtime_error
{
OpenSSLException(std::string const& what);
};
}}}} // namespace Azure::Security::Attestation::_detail
| 35.891892
| 96
| 0.67997
|
JinmingHu-MSFT
|
6913324610ba42002ca621321552d927c8186c93
| 1,341
|
cpp
|
C++
|
src/CLR/Core/StringTable.cpp
|
TIPConsulting/nf-interpreter
|
d5407872f4705d6177e1ee5a2e966bd02fd476e4
|
[
"MIT"
] | null | null | null |
src/CLR/Core/StringTable.cpp
|
TIPConsulting/nf-interpreter
|
d5407872f4705d6177e1ee5a2e966bd02fd476e4
|
[
"MIT"
] | 1
|
2021-02-22T07:54:30.000Z
|
2021-02-22T07:54:30.000Z
|
src/CLR/Core/StringTable.cpp
|
TIPConsulting/nf-interpreter
|
d5407872f4705d6177e1ee5a2e966bd02fd476e4
|
[
"MIT"
] | null | null | null |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "stdafx.h"
#include "Core.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "StringTableData.cpp"
////////////////////////////////////////////////////////////////////////////////////////////////////
void CLR_RT_Assembly::InitString()
{
NATIVE_PROFILE_CLR_CORE();
}
const char* CLR_RT_Assembly::GetString( CLR_STRING i )
{
NATIVE_PROFILE_CLR_CORE();
static const CLR_STRING iMax = 0xFFFF - c_CLR_StringTable_Size;
if(i >= iMax)
{
return &c_CLR_StringTable_Data[ c_CLR_StringTable_Lookup[ (CLR_STRING)0xFFFF - i ] ];
}
return &(((const char*)GetTable( TBL_Strings ))[ i ]);
}
#if defined(_WIN32)
void CLR_RT_Assembly::InitString( std::map<std::string,CLR_OFFSET>& map )
{
NATIVE_PROFILE_CLR_CORE();
const CLR_STRING* array = c_CLR_StringTable_Lookup;
size_t len = c_CLR_StringTable_Size;
CLR_STRING idx = 0xFFFF;
map.clear();
while(len-- > 0)
{
map[ &c_CLR_StringTable_Data[ *array++ ] ] = idx--;
}
}
#endif
| 24.833333
| 101
| 0.541387
|
TIPConsulting
|
6917d70520912ba9c78126e9e2359c219333c51c
| 1,184
|
hh
|
C++
|
src/faodel-services/MPISyncStart.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-01-25T21:21:07.000Z
|
2021-04-29T17:24:00.000Z
|
src/faodel-services/MPISyncStart.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 8
|
2018-10-09T14:35:30.000Z
|
2020-09-30T20:09:42.000Z
|
src/faodel-services/MPISyncStart.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-04-23T19:01:36.000Z
|
2021-05-11T07:44:55.000Z
|
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#ifndef FAODEL_MPISYNCHSTART_HH
#define FAODEL_MPISYNCHSTART_HH
#include <string>
#include "faodel-common/BootstrapInterface.hh"
#include "faodel-common/LoggingInterface.hh"
namespace faodel {
namespace mpisyncstart {
std::string bootstrap();
class MPISyncStart
: public faodel::bootstrap::BootstrapInterface,
public faodel::LoggingInterface {
public:
MPISyncStart();
~MPISyncStart() override;
//Bootstrap API
void Init(const faodel::Configuration &config) override {}
void InitAndModifyConfiguration(faodel::Configuration *config) override;
void Start() override;
void Finish() override {};
void GetBootstrapDependencies(std::string &name,
std::vector<std::string> &requires,
std::vector<std::string> &optional) const override;
private:
bool needs_patch; //True when detected a change in config
};
} // namespace mpisyncstart
} // namespace faodel
#endif //FAODEL_MPISYNCHSTART_HH
| 25.73913
| 76
| 0.727196
|
faodel
|
691a7ea5b06c5bdcd19fb807d06fcd2fa90ae730
| 1,241
|
cpp
|
C++
|
tests/expected/loop.cpp
|
div72/py2many
|
60277bc13597bd32d078b88a7390715568115fc6
|
[
"MIT"
] | 345
|
2021-01-28T17:33:08.000Z
|
2022-03-25T16:07:56.000Z
|
tests/expected/loop.cpp
|
mkos11/py2many
|
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
|
[
"MIT"
] | 291
|
2021-01-31T13:15:06.000Z
|
2022-03-23T21:28:49.000Z
|
tests/expected/loop.cpp
|
mkos11/py2many
|
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
|
[
"MIT"
] | 23
|
2021-02-09T17:15:03.000Z
|
2022-02-03T05:57:44.000Z
|
#include <iostream> // NOLINT(build/include_order)
#include "pycpp/runtime/builtins.h" // NOLINT(build/include_order)
#include "pycpp/runtime/range.hpp" // NOLINT(build/include_order)
#include "pycpp/runtime/sys.h" // NOLINT(build/include_order)
inline void for_with_break() {
for (auto i : rangepp::xrange(4)) {
if (i == 2) {
break;
}
std::cout << i;
std::cout << std::endl;
}
}
inline void for_with_continue() {
for (auto i : rangepp::xrange(4)) {
if (i == 2) {
continue;
}
std::cout << i;
std::cout << std::endl;
}
}
inline void for_with_else() {
for (auto i : rangepp::xrange(4)) {
std::cout << i;
std::cout << std::endl;
}
}
inline void while_with_break() {
int i = 0;
while (true) {
if (i == 2) {
break;
}
std::cout << i;
std::cout << std::endl;
i += 1;
}
}
inline void while_with_continue() {
int i = 0;
while (i < 5) {
i += 1;
if (i == 2) {
continue;
}
std::cout << i;
std::cout << std::endl;
}
}
int main(int argc, char** argv) {
pycpp::sys::argv = std::vector<std::string>(argv, argv + argc);
for_with_break();
for_with_continue();
while_with_break();
while_with_continue();
}
| 19.390625
| 67
| 0.560838
|
div72
|
6925bfa6d418c2725a6e7538337347caf2d38bbb
| 977
|
cpp
|
C++
|
Sources/libosp/test/array_bench.cpp
|
nihospr01/OpenSpeechPlatform
|
799fb5baa5b8cdfad0f5387dd48b394adc583ede
|
[
"BSD-2-Clause"
] | null | null | null |
Sources/libosp/test/array_bench.cpp
|
nihospr01/OpenSpeechPlatform
|
799fb5baa5b8cdfad0f5387dd48b394adc583ede
|
[
"BSD-2-Clause"
] | null | null | null |
Sources/libosp/test/array_bench.cpp
|
nihospr01/OpenSpeechPlatform
|
799fb5baa5b8cdfad0f5387dd48b394adc583ede
|
[
"BSD-2-Clause"
] | null | null | null |
#include <benchmark/benchmark.h>
#include <OSP/array_utilities/array_utilities.hpp>
#include <cassert>
#include <iostream>
#include <string>
using namespace std;
void array_sum_bench(benchmark::State &state) {
int num = state.range(0);
float *arr1 = new float[num];
float total;
for (auto i = 0; i < num; i++)
arr1[i] = (float)i;
for (auto _ : state) {
benchmark::DoNotOptimize(total = array_sum(arr1, num));
benchmark::ClobberMemory();
}
delete[] arr1;
}
void array_multiply_const_bench(benchmark::State &state) {
unsigned num = (unsigned)state.range(0);
float *arr1 = new float[num];
for (unsigned i = 0; i < num; i++)
arr1[i] = (float)i;
for (auto _ : state) {
array_multiply_const(arr1, 2.0, num);
benchmark::ClobberMemory();
}
delete[] arr1;
}
BENCHMARK(array_sum_bench)->Arg(32)->Arg(48);
BENCHMARK(array_multiply_const_bench)->Arg(32)->Arg(48);
BENCHMARK_MAIN();
| 24.425
| 63
| 0.635619
|
nihospr01
|