blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 122
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd72938528701a16c9143e960f5b68ffd7076d1a
|
0e3cf2d88620e4311a9d0fda2bee2d93b6607119
|
/Scripts/Legion/EyeOfAzshara/boss_lady_hatecoil.cpp
|
dae1ed2560a33474a056ec59a845bffa5d08eb81
|
[] |
no_license
|
SquallSpiegel/Project-Darkspear
|
67b1d895cf31a6796ffc0322c9e0a9b78f298245
|
b93487efb808e0421e1551d1fb951f406c521f26
|
refs/heads/master
| 2023-03-16T00:43:51.943898
| 2019-01-05T10:21:38
| 2019-01-05T10:21:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,440
|
cpp
|
/*
* Copyright (C) 2017-2019 Project Darkspear <https://github.com/Hymn-WoW/Project-Darkspear>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "AreaTrigger.h"
#include "AreaTriggerAI.h"
#include "ScriptMgr.h"
#include "eye_of_azshara.h"
enum Spells
{
SPELL_STATIC_NOVA = 193597,
SPELL_FOCUSED_LIGHTING = 193611,
SPELL_BECKON_STORM = 193682,
SPELL_BECKON_STORM_SUMMON = 193683,
SPELL_CURSE_OF_THE_WITCH_DEBUFF = 193698,
SPELL_CURSE_OF_THE_WITCH_1_TARGET = 193712,
SPELL_CURSE_OF_THE_WITCH_3_TARGETS = 193716,
SPELL_CURSE_OF_THE_WITCH_KNOCK_BACK = 193700,
SPELL_CURSE_OF_THE_WITCH_KILL = 193720,
SPELL_ARCANE_SHIELDING = 197868,
SPELL_SAND_DUNE_GOB = 193061,
SPELL_CRACKLING_THUNDER_CHECK = 197324,
SPELL_CRACKLING_THUNDER_DAMAGE = 197326,
// Heroic & Mythic
SPELL_MONSOON_DAMAGE = 196610,
SPELL_MONSOON_VISUAL = 196609,
SPELL_MONSOON_TARGET = 196624,
SPELL_MONSOON_MISSILE = 196630 // Triggers the spawn of the Monsoon NPC
};
// 91784
struct boss_lady_hatecoil : public BossAI
{
boss_lady_hatecoil(Creature* creature) : BossAI(creature, DATA_LADY_HATECOIL) { }
void Reset() override
{
BossAI::Reset();
if (!_arcanistsDead)
DoCastSelf(SPELL_ARCANE_SHIELDING, true);
me->GetInstanceScript()->SetData(DATA_RESPAWN_DUNES, 0);
}
void JustDied(Unit* killer) override
{
BossAI::JustDied(killer);
me->GetInstanceScript()->SetData(DATA_BOSS_DIED, 0);
}
void ScheduleTasks() override
{
events.ScheduleEvent(SPELL_BECKON_STORM, 20s);
events.ScheduleEvent(SPELL_CURSE_OF_THE_WITCH_DEBUFF, 40s);
events.ScheduleEvent(SPELL_STATIC_NOVA, 14s);
events.ScheduleEvent(SPELL_FOCUSED_LIGHTING, 29s);
events.ScheduleEvent(SPELL_CRACKLING_THUNDER_CHECK, 1s);
if (IsHeroic())
events.ScheduleEvent(SPELL_MONSOON_TARGET, 15s);
}
void DoAction(int32 param) override
{
if (param == 1)
{
_arcanistsDead = true;
me->RemoveAurasDueToSpell(SPELL_ARCANE_SHIELDING);
me->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
}
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case SPELL_BECKON_STORM:
{
Talk(3);
DoCastSelf(SPELL_BECKON_STORM, false);
events.Repeat(45s);
break;
}
case SPELL_CURSE_OF_THE_WITCH_DEBUFF:
{
uint32 spellId = urand(0, 1) ? SPELL_CURSE_OF_THE_WITCH_1_TARGET : SPELL_CURSE_OF_THE_WITCH_3_TARGETS;
DoCastSelf(spellId, false);
events.Repeat(40s);
break;
}
case SPELL_STATIC_NOVA:
{
Talk(2);
DoCastSelf(SPELL_STATIC_NOVA, false);
events.Repeat(35s);
break;
}
case SPELL_FOCUSED_LIGHTING:
{
DoCastSelf(SPELL_FOCUSED_LIGHTING, false);
events.Repeat(35s);
break;
}
case SPELL_CRACKLING_THUNDER_CHECK:
{
DoCastSelf(SPELL_CRACKLING_THUNDER_CHECK, true);
events.Repeat(1s);
break;
}
case SPELL_MONSOON_TARGET:
{
Talk(6);
DoCastSelf(SPELL_MONSOON_TARGET, true);
events.Repeat(25s, 35s);
break;
}
}
}
private:
bool _arcanistsDead = false;
};
// 193597
class spell_lady_hatecoil_static_nova : public SpellScript
{
PrepareSpellScript(spell_lady_hatecoil_static_nova);
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if([](WorldObject* object)
{
if (Unit* target = object->ToUnit())
if (target->FindNearestCreature(NPC_SAND_DUNE, 5.0f, true))
return true;
return false;
});
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_lady_hatecoil_static_nova::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_lady_hatecoil_static_nova::FilterTargets, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY);
}
};
// 193611
class spell_lady_hatecoil_focused_lightning : public SpellScript
{
PrepareSpellScript(spell_lady_hatecoil_focused_lightning);
void HandleDamage(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
if (target && target->ToPlayer())
{
if (Creature* sandDune = target->FindNearestCreature(NPC_SAND_DUNE, 5.0f, true))
{
if (GameObject* dune = target->FindNearestGameObject(GOB_SAND_DUNE, 5.0f))
{
sandDune->RemoveGameObject(dune, true);
sandDune->DisappearAndDie();
}
}
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_lady_hatecoil_focused_lightning::HandleDamage, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);
}
};
// 193682
class spell_lady_hatecoil_beckon_storm : public SpellScript
{
PrepareSpellScript(spell_lady_hatecoil_beckon_storm);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
target->CastSpell(target, SPELL_BECKON_STORM_SUMMON, true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_lady_hatecoil_beckon_storm::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
// 193712 && 193716
class spell_lady_hatecoil_curse_of_the_witch : public SpellScript
{
PrepareSpellScript(spell_lady_hatecoil_curse_of_the_witch);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
if (Unit* caster = GetCaster())
caster->CastSpell(target, SPELL_CURSE_OF_THE_WITCH_DEBUFF, true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_lady_hatecoil_curse_of_the_witch::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
// 193698
class aura_lady_hatecoil_curse_of_the_witch : public AuraScript
{
PrepareAuraScript(aura_lady_hatecoil_curse_of_the_witch);
void OnRemove(AuraEffect const* /*auraEff*/, AuraEffectHandleModes /*mode*/)
{
Unit* target = GetTarget();
target->CastSpell(target, SPELL_CURSE_OF_THE_WITCH_KNOCK_BACK, true);
target->CastSpell(target, SPELL_CURSE_OF_THE_WITCH_KILL, true);
}
void Register() override
{
OnEffectRemove += AuraEffectRemoveFn(aura_lady_hatecoil_curse_of_the_witch::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
// 197324
class spell_lady_hatecoil_crackling_thunder : public SpellScript
{
PrepareSpellScript(spell_lady_hatecoil_crackling_thunder);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
Unit* caster = GetCaster();
if (caster && target && target->GetDistance(Position(-3434.230469f, 4592.095703f, -0.437837f)) > 42.0f)
caster->CastSpell(target, SPELL_CRACKLING_THUNDER_DAMAGE, true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_lady_hatecoil_crackling_thunder::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
// 196624
class spell_lady_hatecoil_monsoon_target : public SpellScript
{
PrepareSpellScript(spell_lady_hatecoil_monsoon_target);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
Unit* caster = GetCaster();
if (caster && target)
caster->CastSpell(target, SPELL_MONSOON_MISSILE, true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_lady_hatecoil_monsoon_target::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
// 99852
struct npc_lady_hatecoil_monsoon : public ScriptedAI
{
npc_lady_hatecoil_monsoon(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
DoCastSelf(SPELL_MONSOON_VISUAL, true);
me->setFaction(16); // Same faction as Lady Hatecoil
me->SetSpeed(MOVE_RUN, 2.0f);
if (Unit* victim = me->SelectNearestPlayer(100.0f))
me->GetMotionMaster()->MoveFollow(victim, 0.0f, 0.0f);
}
};
// Spell: 196610
// AT: 100101 (custom)
struct at_lady_hatecoil_monsoon : AreaTriggerAI
{
at_lady_hatecoil_monsoon(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) { }
void OnUnitEnter(Unit* unit) override
{
Unit* caster = at->GetCaster();
if (caster)
{
if (Player* player = unit->ToPlayer())
caster->CastSpell(player, SPELL_MONSOON_DAMAGE, true);
else if (Creature* creature = unit->ToCreature())
{
if (creature->GetEntry() == NPC_SAND_DUNE)
{
if (GameObject* dune = creature->FindNearestGameObject(GOB_SAND_DUNE, 5.0f))
{
creature->RemoveGameObject(dune, true);
creature->DisappearAndDie();
at->Remove();
if (Creature* casterCre = caster->ToCreature())
casterCre->DisappearAndDie();
}
}
}
}
}
};
// Criteria ID: 29404
class achievement_stay_salty : public AchievementCriteriaScript
{
public:
achievement_stay_salty() : AchievementCriteriaScript("achievement_stay_salty") { }
bool OnCheck(Player* /*player*/, Unit* /*target*/) override
{
// TODO
return false;
}
};
void AddSC_boss_lady_hatecoil()
{
RegisterCreatureAI(boss_lady_hatecoil);
RegisterCreatureAI(npc_lady_hatecoil_monsoon);
RegisterSpellScript(spell_lady_hatecoil_static_nova);
RegisterSpellScript(spell_lady_hatecoil_focused_lightning);
RegisterSpellScript(spell_lady_hatecoil_beckon_storm);
RegisterSpellScript(spell_lady_hatecoil_curse_of_the_witch);
RegisterSpellScript(spell_lady_hatecoil_crackling_thunder);
RegisterSpellScript(spell_lady_hatecoil_monsoon_target);
RegisterAuraScript(aura_lady_hatecoil_curse_of_the_witch);
RegisterAreaTriggerAI(at_lady_hatecoil_monsoon);
new achievement_stay_salty();
}
|
[
"lordn00dle2@gmail.com"
] |
lordn00dle2@gmail.com
|
9df6791be9a643e601ab61a8202ee2eb068278b7
|
5069f2992e1e3594295819b832032a5395e8e99c
|
/Actions/SaveAction.h
|
8b12086bdd6af40aa97de8177f15547b94af8265
|
[] |
no_license
|
AhmedHisham552/Paint-for-kids
|
36e8ec9bffeb9be9451a601d49a9c07a3f41d6b7
|
503da2c694417017221914091fa6f9576c23a916
|
refs/heads/master
| 2020-04-12T19:27:52.804002
| 2018-12-22T09:04:46
| 2018-12-22T09:04:46
| 162,709,486
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 241
|
h
|
#pragma once
#include "Action.h"
#include"../ApplicationManager.h"
class SaveAction :
public Action
{
private:
string name;
public:
SaveAction(ApplicationManager* pApp);
void ReadActionParameters();
void Execute();
~SaveAction();
};
|
[
"40614397+AhmedHisham552@users.noreply.github.com"
] |
40614397+AhmedHisham552@users.noreply.github.com
|
06182957a588c3a14dd0bbf0a64bffadc0ecf125
|
84a7f7ff628a3bb6d318795a4c801df6ad2a9048
|
/Galactic_cluster/celestialbody.h
|
a86d9c48b2a0c7dffc2edba27e66dc3787630a6d
|
[] |
no_license
|
emilblix/FYS-4150
|
8190d435d830452c30d6f5a3bc3ae547aa4b479e
|
5f9ee79426f6d034ead0d4d7283ccf6ec544bb23
|
refs/heads/master
| 2021-01-20T12:38:10.590619
| 2014-12-08T07:32:02
| 2014-12-08T07:32:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 600
|
h
|
#ifndef CELESTIAL_BODY_H
#define CELESTIAL_BODY_H
#include <vec3.h>
class CelestialBody
{
public:
double mass; // Relative mass of body compared to the Sun
vec3 position; // Coordinates of body
vec3 velocity; // Velocity of body
vec3 acceleration; // Acceleration of body
CelestialBody(double mass_, double x, double y, double z, double vx, double vy, double vz);
CelestialBody(vec3 pos, vec3 vel, double mass_);
void resetAcceleration();
};
#endif // CELESTIAL_BODY_H
|
[
"emilblix@gmail.com"
] |
emilblix@gmail.com
|
bb17da301f9b90dee19e48afdb0465cffda47723
|
ef349c7e735019da95b4b39ad6141027e519647f
|
/helper.h
|
8494ca28e0a38f83ffcb75b30dc9f11664fa6cba
|
[] |
no_license
|
eas/Graphics-core
|
63fec1a0e67b9f3f99013571911d9d1bd2759556
|
65c378d606ca07982c5a89ab74f06bdb05383fb8
|
refs/heads/master
| 2021-01-19T06:05:33.261243
| 2009-10-21T18:33:09
| 2009-10-21T18:36:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,712
|
h
|
#pragma once
#include "exception"
#include "windows.h"
#include "d3dx9.h"
namespace Helper
{
class WinApiError
:public std::exception
{
public:
WinApiError( DWORD errorCode )
: errorCode_(errorCode)
{
}
public:
DWORD errorCode_;
};
struct WindowPostion
{
int height;
int width;
int left;
int top;
};
const WindowPostion defaultWindowPostion = { 500, 500, 350, 120 };
typedef LRESULT (CALLBACK *WndProcType)(HWND, UINT, WPARAM, LPARAM);
class Window
{
public:
Window( HINSTANCE hInstance, int nCmdShow, WndProcType wndProc,
TCHAR* szTitle, TCHAR* szWindowClass, unsigned nExtraLong,
WindowPostion windowPosition = defaultWindowPostion );
~Window();
HWND GetHWND()
{
return hWnd_;
}
private:
Window(const Window&);
Window& operator=(const Window&);
HWND hWnd_;
};
class SpectatorCoords
{
public:
SpectatorCoords(float r, float theta, float phi)
:r_(r), theta_(theta), phi_(phi)
{
}
const D3DXVECTOR3 GetCartesianCoords() const
{
return D3DXVECTOR3( r_*sinf(theta_)*cosf(phi_),
r_*cosf(theta_),
r_*sinf(theta_)*sinf(phi_) );
}
void IncTheta() { if((theta_+=deltaTheta) > thetaMax){ theta_= thetaMax; } }
void DecTheta() { if((theta_-=deltaTheta) < thetaMin){ theta_= thetaMin; } }
void IncPhi() { phi_ += deltaPhi; }
void DecPhi() { phi_ -= deltaPhi; }
void IncR() { r_ += deltaR; }
void DecR() { if((r_-=deltaR) < rMin){ r_ = rMin; } }
private:
float r_, theta_, phi_;
public:
static const float deltaPhi;
static const float deltaTheta;
static const float deltaR;
static const float thetaMin;
static const float thetaMax;
static const float rMin;
};
} // namespace Helper
|
[
"a.elovikov@gmail.com"
] |
a.elovikov@gmail.com
|
0001f23c76099556ce15784cbd97b222475d2d11
|
0aa91508c25477a70e78156d8e85763e7b37bec6
|
/UnitFrameDetailCount.cpp
|
f09d16484fcca74614975870598b8ce1605b8cb1
|
[] |
no_license
|
Zummer/calculate1c
|
55969cbb2926ff9adcd5a04bbf05bf84038109c8
|
b3ca83bd3eeb49294680fc570bca1e525dd84520
|
refs/heads/master
| 2016-09-06T15:40:23.818475
| 2014-12-12T12:01:20
| 2014-12-12T12:01:20
| null | 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 3,690
|
cpp
|
// ---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "UnitFrameDetailCount.h"
#include "UnitFramePlaceOperation.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "AdvSpin"
#pragma resource "*.dfm"
#include "SquareDetail.h"
TFrameDetailCount *FrameDetailCount;
// ---------------------------------------------------------------------------
__fastcall TFrameDetailCount::TFrameDetailCount(TComponent* Owner, double w,
double h, int copyCount) : TFrame(Owner) {
ToggleSP(0);
spW->FloatValue = w;
spH->FloatValue = h;
spCount->Value = copyCount;
ToggleSP(1);
Minimize();
}
// ---------------------------------------------------------------------------
__fastcall TFrameDetailCount::~TFrameDetailCount() {
if (Parent) {
Parent->Tag -= 1;
}
}
// ---------------------------------------------------------------------------
void __fastcall TFrameDetailCount::spChange(TObject *Sender) {
TAdvSpinEdit *e = dynamic_cast<TAdvSpinEdit*>(Sender);
if (e->Value < 1) {
return;
}
if (dynamic_cast<TSquareDetail*>(Owner)) {
TSquareDetail *detail = dynamic_cast<TSquareDetail*>(Owner);
TShapeDetail *last = dynamic_cast<TShapeDetail*>
(FormPlace->lastMovedShape);
if (last && last->detail != detail) {
FormPlace->lastMovedShape->Pen->Color = clBlack;
FormPlace->lastMovedShape = (TShape*)detail->listOfShapes->First();
FormPlace->lastMovedShape->Pen->Color = clBlue;
}
detail->SetW(spW->FloatValue);
detail->SetH(spH->FloatValue);
detail->SetCount(spCount->Value);
// выделим операцию
TfrPlaceOperation *detailOperation =
(TfrPlaceOperation*)detail->operation;
if (!detailOperation->Selected) {
detailOperation->Select();
}
// поднимем деталь
detail->ShowOn(FormPlace->sbForPlace);
// поднимем направляющую
FormPlace->GuidLine->BringToFront();
// надо бы посчитать
fSbornyZakaz->Sum();
}
}
// ---------------------------------------------------------------------------
void TFrameDetailCount::ToggleSP(int onoff) {
switch (onoff) {
case 0:
// отключим на время реакцию на события
spCount->OnChange = NULL;
spW->OnChange = NULL;
spH->OnChange = NULL;
break;
case 1:
// снова включим
spCount->OnChange = spChange;
spW->OnChange = spChange;
spH->OnChange = spChange;
break;
default: ;
// }
}
}
// ---------------------------------------------------------------------------
void __fastcall TFrameDetailCount::spKeyPress(TObject *Sender, wchar_t &Key) {
TAdvSpinEdit *sp = dynamic_cast<TAdvSpinEdit*>(Sender);
if (Key == VK_RETURN) {
sp->Brush->Color = clWindow;
sp->Repaint();
sp->OnChange = spChange;
spChange(Sender);
}
else {
sp->OnChange = NULL;
sp->Brush->Color = RGB(255, 125, 125);
}
}
// ---------------------------------------------------------------------------
void __fastcall TFrameDetailCount::Button1Click(TObject *Sender) {
if (!minimize)
Minimize();
else
Maximize();
}
// ---------------------------------------------------------------------------
void __fastcall TFrameDetailCount::Minimize() {
Height = 27;
minimize = true;
if (Parent && Parent->Parent) {
Parent->Parent->Height -= 27;
}
}
// ---------------------------------------------------------------------------
void __fastcall TFrameDetailCount::Maximize() {
Height = 54;
minimize = false;
if (Parent && Parent->Parent) {
Parent->Parent->Height += 27;
}
}
// ---------------------------------------------------------------------------
|
[
"afanasev@comefoto.ru"
] |
afanasev@comefoto.ru
|
ddd58805cac26ddf828b61912252c038885ecbea
|
83bfbbe8a3d8c6d6972bfff7edc84458d4cf17fd
|
/Maze/Stack.cpp
|
6dafa4d5795b7572cc6d51e6b5090e6a7510276d
|
[] |
no_license
|
afrojuju1/metaMouse2.0
|
f4ab7c9e0131fbc6199ecd9b18e7b7b3a7a3b6a0
|
ccfd6ac43817febecd62cbe1867bab62373ed370
|
refs/heads/master
| 2021-06-12T20:43:43.021474
| 2017-03-20T05:58:54
| 2017-03-20T05:58:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 146
|
cpp
|
#include "Stack.h"
Block pop()
{
Block b = stack[stackPos];
stackPos--;
return b;
}
void push(Block b)
{
stackPos++;
stack[stackPos] = b;
}
|
[
"adeoa.bello.262@my.csun.edu"
] |
adeoa.bello.262@my.csun.edu
|
8d32b96da13101ab1c0443b1d93d483558408227
|
73e7c20803be5d8ae467af1feba8a4a7fe219f4b
|
/Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.h
|
c05128fc2563e28354e2bf3460046e0f7356a8aa
|
[
"LicenseRef-scancode-other-permissive",
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-free-unknown",
"BSD-4.3TAHOE",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"IJG",
"Zlib",
"Spencer-86",
"libtiff",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-public-domain",
"NTP",
"BSD-2-Clause",
"GPL-1.0-or-later",
"FSFUL",
"Libpng"
] |
permissive
|
CIBC-Internal/itk
|
deaa8aabe3995f3465ec70a46805bd333967ed5b
|
6f7b1014a73857115d6da738583492008bea8205
|
refs/heads/master
| 2021-01-10T18:48:58.502855
| 2018-01-26T21:25:51
| 2018-01-26T21:25:51
| 31,582,564
| 0
| 2
|
Apache-2.0
| 2018-05-21T07:59:53
| 2015-03-03T06:12:12
|
C++
|
UTF-8
|
C++
| false
| false
| 7,261
|
h
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#ifndef itkReflectiveImageRegionConstIterator_h
#define itkReflectiveImageRegionConstIterator_h
#include "itkImageConstIteratorWithIndex.h"
namespace itk
{
/** \class ReflectiveImageRegionConstIterator
* \brief Multi-dimensional image iterator which only walks a region.
*
* ReflectiveImageRegionConstIterator is a templated class to represent a
* multi-dimensional iterator. ReflectiveImageRegionConstIterator is templated
* over the image type. ReflectiveImageRegionConstIterator is constrained to
* walk only within the specified region.
*
* ReflectiveImageRegionConstIterator will perform two passes over the image
* along each dimension. It is useful for algorithms that require to
* go back and forth (once) over the data.
*
* By setting the BeginOffset and EndOffset parameters, you can arrange for
* the starting point, when going forwards, to be different from the ending
* point, when going backwards. Along dimension d, when going forwards the
* iterator traverses the interval [BeginIndex[d]+BeginOffset[d], EndIndex[d]).
* When going back, it traverses the interval (EndIndex[d]-EndOffset[d],
* BeginIndex[d]]. Setting both offsets to (1, ..., 1) enables the
* DanielssonDistanceMapImageFilter to process the entire image,
* without encountering boundary conditions, rather
* than removing a one-pixel border.
*
* \sa DanielssonDistanceMapImageFilter
*
* \ingroup Iterators
* \ingroup ITKDistanceMap
*/
template< typename TImage >
class ReflectiveImageRegionConstIterator:public ImageConstIteratorWithIndex< TImage >
{
public:
/** Standard class typedefs. */
typedef ReflectiveImageRegionConstIterator Self;
typedef ImageConstIteratorWithIndex< TImage > Superclass;
/** Index typedef support. While this was already typdef'ed in the superclass
* it needs to be redone here for this subclass to compile properly with gcc.
* Note that we have to rescope Index back to itk::Index to that is it not
* confused with ImageIterator::Index. */
typedef typename TImage::IndexType IndexType;
/** Image typedef support. While this was already typdef'ed in the superclass
* it needs to be redone here for this subclass to compile properly with gcc.
* Note that we have to rescope Image back to itk::Image to that is it not
* confused with ImageIterator::Image. */
typedef TImage ImageType;
/** PixelContainer typedef support. Used to refer to the container for
* the pixel data. While this was already typdef'ed in the superclass
* it needs to be redone here for this subclass to compile properly
* with gcc. */
typedef typename TImage::PixelContainer PixelContainer;
typedef typename PixelContainer::Pointer PixelContainerPointer;
/** Region typedef support. While this was already typdef'ed in the
* superclass it needs to be redone here for this subclass to compile
* properly with gcc. Note that we have to rescope Region back to
* itk::ImageRegion so that is it not confused with
* ImageIterator::Index. */
typedef typename TImage::RegionType RegionType;
typedef typename TImage::SizeType SizeType;
typedef typename TImage::SizeValueType SizeValueType;
/** Type of the Offset taken from the image. These typedefs are
* duplicated from the superclass for gcc support. */
typedef typename TImage::OffsetType OffsetType;
typedef typename OffsetType::OffsetValueType OffsetValueType;
/** Default constructor. Needed since we provide a cast constructor. */
ReflectiveImageRegionConstIterator();
/** Default destructor. */
~ReflectiveImageRegionConstIterator() {}
/** Constructor establishes an iterator to walk a particular image and a
* particular region of that image. */
ReflectiveImageRegionConstIterator(TImage *ptr, const RegionType & region);
/** Copy Constructor. The copy constructor is provided to make sure the
* handle to the image is properly reference counted. */
ReflectiveImageRegionConstIterator(const Self & it);
/** Constructor that can be used to cast from an ImageIterator to an
* ReflectiveImageRegionConstIterator. Many routines return an
* ImageIterator but for a particular task, you may want an
* ReflectiveImageRegionConstIterator. Rather than provide
* overloaded APIs that return different types of Iterators, itk
* returns ImageIterators and uses constructors to cast from * an
* ImageIterator to a ReflectiveImageRegionConstIterator. */
ReflectiveImageRegionConstIterator(const ImageConstIteratorWithIndex< TImage > & it);
/** operator= is provided to make sure the handle to the image is properly
* reference counted. */
Self & operator=(const Self & it);
bool IsReflected(unsigned int) const;
/** Increment (prefix) the fastest moving dimension of the iterator's index.
* This operator will constrain the iterator within the region (i.e. the
* iterator will automatically wrap from the end of the row of the region
* to the beginning of the next row of the region) up until the iterator
* tries to moves past the last pixel of the region. Here, the iterator
* will be set to be one pixel past the end of the region.
* \sa operator++(int) */
Self & operator++();
/** Move an iterator to the beginning of the region. */
void GoToBegin();
/** Is the iterator at the beginning of the region? */
bool IsAtBegin(void) const
{
return !this->m_Remaining;
}
/** Set the begin offset. Forward iteration starts at this offset
* from the current region. */
void SetBeginOffset(const OffsetType & offset)
{ m_BeginOffset = offset; }
/** Set the end offset. Reverse iteration starts at this offset
* from the current region. */
void SetEndOffset(const OffsetType & offset)
{ m_EndOffset = offset; }
/** Get the begin offset. Forward iteration starts at this offset
* from the current region. */
OffsetType GetBeginOffset(const OffsetType & )
{ return m_BeginOffset; }
/** Get the end offset. Reverse iteration starts at this offset
* from the current region. */
OffsetType GetEndOffset(const OffsetType & )
{ return m_EndOffset; }
/** Fill both offsets with a single value. */
void FillOffsets(const OffsetValueType & value);
private:
bool m_IsFirstPass[TImage::ImageDimension];
OffsetType m_BeginOffset;
OffsetType m_EndOffset;
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkReflectiveImageRegionConstIterator.hxx"
#endif
#endif
|
[
"ayla@sci.utah.edu"
] |
ayla@sci.utah.edu
|
b65144c6eafe9bd6df4ef28d7bf523ce31ecd92c
|
bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7
|
/rdr2/0x18714953CCED17D3.cpp
|
46b1fab23d280c0f7fc6a4bb2b1b5f3e782e83ee
|
[] |
no_license
|
DeepWolf413/additional-native-data
|
aded47e042f0feb30057e753910e0884c44121a0
|
e015b2500b52065252ffbe3c53865fe3cdd3e06c
|
refs/heads/main
| 2023-07-10T00:19:54.416083
| 2021-08-12T16:00:12
| 2021-08-12T16:00:12
| 395,340,507
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 424
|
cpp
|
// braithwaites2.ysc @ L52175
bool func_1247(var uParam0)
{
if (func_33(uParam0) <= iLocal_92)
{
if (ENTITY::DOES_ENTITY_EXIST(Local_14.f_19[0]) && !CAM::_0x139EFB0A71DD9011())
{
if (!VEHICLE::IS_VEHICLE_DRIVEABLE(Local_14.f_19[0], false, false))
{
return true;
}
if (VEHICLE::_0x18714953CCED17D3(Local_14.f_19[0]))
{
return true;
}
}
}
return false;
}
|
[
"jesper15fuji@live.dk"
] |
jesper15fuji@live.dk
|
2f2d0e429507f30a32767296f98c5cad1bdcb45a
|
4fc9d5d49b9d0c9a8aec35e02418230c4a439bf7
|
/Samples/Physics/FreeTopFixedTip/PhysicsModule.cpp
|
c8b7b281179ee254c2a2c113d9b486aa2955d66a
|
[] |
no_license
|
zhouxs1023/GTEngine
|
07d8a299522a8b33b6960dca06a4ca6cb459622c
|
16c1af003106798dd2d91800085818b40adfad1a
|
refs/heads/master
| 2020-03-27T18:03:37.798691
| 2019-12-30T13:49:17
| 2019-12-30T13:49:17
| 146,895,580
| 9
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,296
|
cpp
|
// David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2019
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.1.2 (2018/10/05)
#include "PhysicsModule.h"
PhysicsModule::PhysicsModule()
:
gravity(0.0f),
mass(0.0f),
length(0.0f),
inertia1(0.0f),
inertia3(0.0f),
mTime(0.0f),
mState(Vector3<float>::Zero())
{
for (int i = 0; i < 5; ++i)
{
mAux[i] = 0.0f;
}
}
void PhysicsModule::Initialize(float time, float deltaTime, float theta,
float phi, float psi, float angVel1, float angVel2, float angVel3)
{
mTime = time;
float cosPhi = std::cos(phi), sinPhi = std::sin(phi);
float cosPsi = std::cos(psi), sinPsi = std::sin(psi);
// State variables.
mState[0] = theta;
mState[1] = phi;
mState[2] = psi;
// Auxiliary variables.
mAux[0] = mass * gravity * length / inertia1; // alpha
mAux[1] = angVel1 * angVel1 + angVel2 * angVel2 + 2.0f * cosPhi * mAux[0]; // beta
mAux[2] = angVel3 * inertia3 / inertia1; // epsilon
mAux[3] = sinPhi * (angVel1 * sinPsi + angVel2 * cosPsi) + cosPhi * mAux[2]; // delta
mAux[4] = angVel3;
// RK4 differential equation solver.
std::function<Vector3<float>(float, Vector3<float> const&)> odeFunction
=
[this](float, Vector3<float> const& input) -> Vector3<float>
{
float cs = std::cos(input[1]);
float invSin = 1.0f / std::sin(input[1]);
float numer = mAux[3] - mAux[2] * cs;
float fraction = numer * invSin;
float arg = mAux[1] - 2.0f * mAux[0] * cs - fraction * fraction;
float thetaDotFunction = fraction * invSin;
float phiDotFunction = std::sqrt(std::abs(arg));
float psiDotFunction = mAux[4] - cs * thetaDotFunction;
return Vector3<float>{thetaDotFunction, phiDotFunction, psiDotFunction};
};
mSolver = std::make_unique<Solver>(deltaTime, odeFunction);
}
Matrix4x4<float> PhysicsModule::GetBodyAxes() const
{
float cosTheta = std::cos(mState[0]);
float sinTheta = std::sin(mState[0]);
float cosPhi = std::cos(mState[1]);
float sinPhi = std::sin(mState[1]);
float cosPsi = std::cos(mState[2]);
float sinPsi = std::sin(mState[2]);
Vector3<float> N{ cosTheta, sinTheta, 0.0f };
Vector3<float> axis3{ sinTheta * sinPhi, -cosTheta * sinPhi, cosPhi };
Vector3<float> axis3xN = Cross(axis3, N);
Vector3<float> axis1 = cosPsi * N + sinPsi * axis3xN;
Vector3<float> axis2 = cosPsi * axis3xN - sinPsi * N;
Matrix4x4<float> rotate;
#if defined(GTE_USE_MAT_VEC)
rotate.SetCol(0, HLift(axis1, 0.0f));
rotate.SetCol(1, HLift(axis2, 0.0f));
rotate.SetCol(2, HLift(axis3, 0.0f));
rotate.SetCol(3, Vector4<float>::Unit(3));
#else
rotate.SetRow(0, HLift(axis1, 0.0f));
rotate.SetRow(1, HLift(axis2, 0.0f));
rotate.SetRow(2, HLift(axis3, 0.0f));
rotate.SetRow(3, Vector4<float>::Unit(3));
#endif
return rotate;
}
void PhysicsModule::Update()
{
// Apply a single step to the ODE solver.
if (mSolver)
{
mSolver->Update(mTime, mState, mTime, mState);
}
}
|
[
"zhouxs1023@163.com"
] |
zhouxs1023@163.com
|
40277902a733bbb5558743e2359166f19382f339
|
dab17edba4d031ef4892bd373892b3ea39eac992
|
/KleptoEngine/Renderer.h
|
7e47ce5e6e88256007943feb7f4dd78178405170
|
[] |
no_license
|
McMasterGameDesignAssociation/current-version
|
fc13f74693d5ef3e2da76a27d4ee99d972e496c4
|
df89d6d7a3abafd3333d9115d1cbc370d88f34b7
|
refs/heads/master
| 2020-12-24T14:02:00.284263
| 2015-02-25T16:53:39
| 2015-02-25T16:53:39
| 26,332,614
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,330
|
h
|
/*
COPYRIGHT BENJAMIN ISHERWOOD 23/10/2014
THIS SOFTWARE IS INTENDED FOR OPEN SOURCE USE, REDISTRIBUTION
IS ENCOURAGE
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 SOFTWARsE.
*/
#ifndef RENDERER_H
#define RENDERER_H
#include "engineStdafx.h"
#include "Image.h"
#include "World2D.h"
class Renderer
{
private:
Timer frameLimiter = Timer(45);
//Dimensions are the size of the screen
Pos2D dimensions;
//View port position is the current location
//That the viewport is located in the scene
Pos2D viewPortPosition;
//The view port size is the current area that the
//player can be situated in i.e. is the view port
//is 50% the size of the dimension than the player
//can move the screen position by pushing against
//the first or third quarter of the screen from
//the center
Pos2D viewPortSize;
/*
basicBuffer and working buffers work as follows
basicBuffer is the total size of the screen buffer
this is what will be passed into the draw functions
next the working buffer will be initiated to the
basic buffer = color
pixel buffer = shape
each texture requires it own location, color, and texture
coordinate buffer
*/
vector<FV3*> basicBuffer;
vector<IV2*> pixels;
//The maxTriangles gives the total number
//of triangles in the render pipeline
vector<ULong> maxNodes;
vector<Image> imageFiles;
/*
The way that texture coords will works as follows:
Each image index will match the textureCoords index
in the populate sequence the renderer will subdivide
all objects by into lists based on the textureIds
each set of textureCoords will require a call to the
render pipeline
*/
vector<FV2*> textureCoords;
vector<ULong> currentPointer;
//These texture Ids are used solely
//for tracking the other objects relations
//to images
vector<ULong *> textureIds;
void addImage(Image image);
static void display(void);
static Image * currentImage;
void linkTextureId(ULong *baseId);
//Verify lists is used ot make sure that
//all of the lists are the same length, i.e.
//all of them have been processed
bool verifyLists(void);
//This function will be used to move the current
//position of the view port so that it is centered
//over the current player, and returns true if the
//view port needs to be updated, and false if it doesn't
bool updateViewPort(Pos2D newCenter);
WindowType typeOfWindow = Windowed;
protected:
friend World2D;
//Tiles don't move around in the world
//Therefore they don't need to be linked
//by address to the object that will be
//moving around
void addTileToDraw(Pos2D position, Pos2D size, bool canPass, ULong id);
void setNewMax(ULong nodes, ULong id);
//Actors and players move around in the
//world and therefore they need to be
//linked to the memory addresses of the
//object so that a repopulate does
//not need to occur in the draw cycles
void linkSprite(Sprite * sprite);
void linkTextureCoords(FV2 * linkage, ULong textureId, Uint tileNumber);
bool loadImage(string imageName, string desc, Pos2D chunkSize, ULong * linkId, ImageType imageType);
/*
getImageDivisions, returns the image divisions at a specific
position in the image set
*/
Pos2D getImageDivisions(Uint index) const;
/*
getImageSize, returns the size of a texture map at a specific
place in the image set
*/
Pos2D getImageSize(Uint index) const;
public:
Renderer(void);
void initWindow(int argc, char *argv[]);
void render(void);
//rebuild window resizes the window so that the
//user can tell the renderer how to handle the
//current window. The window can be restored,
//minimized or restored
void rebuildWindow(void);
void setToFullScreen(void);
void setToWindowed(void);
void setToMinimized(void);
WindowType getWindowState(void) const;
void populateArrays(World2D * world);
};
#endif
|
[
"isherwb@mcmaster.ca"
] |
isherwb@mcmaster.ca
|
07d25173ae7f0659749c2a92131694733553d9d5
|
54d88765e22d3ce7ce4ff3538ea5205b9913cc4e
|
/practice_java/exam.c++
|
2d5b23da4224e06bad71de6dc7bf642ca0f3e742
|
[] |
no_license
|
KindLoad/pracserver
|
2bcb343f4c6e5b51218a14620cc12a5a4fa19dfa
|
312aa0c1b0d8a2c80ac91dfc7189991633cd33d2
|
refs/heads/Soongil_branch
| 2022-12-16T20:47:42.955817
| 2020-07-06T01:28:45
| 2020-07-06T01:28:45
| 275,346,771
| 0
| 0
| null | 2022-12-13T04:21:28
| 2020-06-27T10:15:27
|
Java
|
UTF-8
|
C++
| false
| false
| 189
|
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
cout << "so sleep" << endl;
return 0;
}
|
[
"kdge248@gmail.com"
] |
kdge248@gmail.com
|
|
7ecefd58185018499d6e3f74e6507f5bd8c65a52
|
01ac52f86f7e7c7d8efab9c66796b107a4198731
|
/base.h
|
582716769f5fe39ff77adde3eefe1f3bd6a7f6da
|
[] |
no_license
|
BCnick943204/RNA2DModelGen
|
1547aba15bec7a85c45c43255828fe974ee31bd2
|
1e370687792545715e1adab458c5eae6ea44fe4b
|
refs/heads/master
| 2021-01-02T12:27:59.094168
| 2020-05-27T04:44:34
| 2020-05-27T04:44:34
| 239,623,812
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 260
|
h
|
#ifndef BASE_H
#define BASE_H
#include <QGraphicsPixmapItem>
#include <QPixmap>
#include <QSize>
#include <stdio.h>
class Base: public QGraphicsPixmapItem
{
public:
Base(char);
int setBasePic(char);
private:
QSize base_size;
};
#endif // BASE_H
|
[
"nicholas.passantino@bellevuecollege.edu"
] |
nicholas.passantino@bellevuecollege.edu
|
5a5730d186a551d8411cea24c395a8829543b543
|
31ac07ecd9225639bee0d08d00f037bd511e9552
|
/externals/OCCTLib/inc/IGESGraph_ToolColor.hxx
|
a93a5f73079485404611a3bc2227ab4dcbe56987
|
[] |
no_license
|
litao1009/SimpleRoom
|
4520e0034e4f90b81b922657b27f201842e68e8e
|
287de738c10b86ff8f61b15e3b8afdfedbcb2211
|
refs/heads/master
| 2021-01-20T19:56:39.507899
| 2016-07-29T08:01:57
| 2016-07-29T08:01:57
| 64,462,604
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,117
|
hxx
|
// This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _IGESGraph_ToolColor_HeaderFile
#define _IGESGraph_ToolColor_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineAlloc_HeaderFile
#include <Standard_DefineAlloc.hxx>
#endif
#ifndef _Standard_Macro_HeaderFile
#include <Standard_Macro.hxx>
#endif
#ifndef _Handle_IGESGraph_Color_HeaderFile
#include <Handle_IGESGraph_Color.hxx>
#endif
#ifndef _Handle_IGESData_IGESReaderData_HeaderFile
#include <Handle_IGESData_IGESReaderData.hxx>
#endif
#ifndef _Handle_Interface_Check_HeaderFile
#include <Handle_Interface_Check.hxx>
#endif
#ifndef _Handle_Message_Messenger_HeaderFile
#include <Handle_Message_Messenger.hxx>
#endif
#ifndef _Standard_Integer_HeaderFile
#include <Standard_Integer.hxx>
#endif
class Standard_DomainError;
class IGESGraph_Color;
class IGESData_IGESReaderData;
class IGESData_ParamReader;
class IGESData_IGESWriter;
class Interface_EntityIterator;
class IGESData_DirChecker;
class Interface_ShareTool;
class Interface_Check;
class Interface_CopyTool;
class IGESData_IGESDumper;
class Message_Messenger;
//! Tool to work on a Color. Called by various Modules <br>
//! (ReadWriteModule, GeneralModule, SpecificModule) <br>
class IGESGraph_ToolColor {
public:
DEFINE_STANDARD_ALLOC
//! Returns a ToolColor, ready to work <br>
Standard_EXPORT IGESGraph_ToolColor();
//! Reads own parameters from file. <PR> gives access to them, <br>
//! <IR> detains parameter types and values <br>
Standard_EXPORT void ReadOwnParams(const Handle(IGESGraph_Color)& ent,const Handle(IGESData_IGESReaderData)& IR,IGESData_ParamReader& PR) const;
//! Writes own parameters to IGESWriter <br>
Standard_EXPORT void WriteOwnParams(const Handle(IGESGraph_Color)& ent,IGESData_IGESWriter& IW) const;
//! Lists the Entities shared by a Color <ent>, from <br>
//! its specific (own) parameters <br>
Standard_EXPORT void OwnShared(const Handle(IGESGraph_Color)& ent,Interface_EntityIterator& iter) const;
//! Returns specific DirChecker <br>
Standard_EXPORT IGESData_DirChecker DirChecker(const Handle(IGESGraph_Color)& ent) const;
//! Performs Specific Semantic Check <br>
Standard_EXPORT void OwnCheck(const Handle(IGESGraph_Color)& ent,const Interface_ShareTool& shares,Handle(Interface_Check)& ach) const;
//! Copies Specific Parameters <br>
Standard_EXPORT void OwnCopy(const Handle(IGESGraph_Color)& entfrom,const Handle(IGESGraph_Color)& entto,Interface_CopyTool& TC) const;
//! Dump of Specific Parameters <br>
Standard_EXPORT void OwnDump(const Handle(IGESGraph_Color)& ent,const IGESData_IGESDumper& dumper,const Handle(Message_Messenger)& S,const Standard_Integer own) const;
protected:
private:
};
// other Inline functions and methods (like "C++: function call" methods)
#endif
|
[
"litao1009@gmail.com"
] |
litao1009@gmail.com
|
8a5228ee31bac3a8a008aa5cef8dc0a16f9a02a0
|
d5785b4a1abf832fb6fed4ff4cfe06a0e44e0fe6
|
/toj373.cpp
|
eaee3a2ac8eccc134ce93a3c0f9e21258d44bbea
|
[] |
no_license
|
arasHi87/OnlineJudgeExercise
|
7caaf58f43c675488a712279cb310c55729957d4
|
90afc36d25bd2a015c7fde604c78d82591d2113a
|
refs/heads/master
| 2022-02-21T19:06:39.260348
| 2019-09-22T09:17:13
| 2019-09-22T09:17:13
| 197,958,223
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 415
|
cpp
|
#include <cstdio>
using namespace std;
int x1, x2, y1, y2, x, y, W, H;
double tmp;
int main() {
#ifdef local
freopen("in", "r", stdin);
#endif
scanf("%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &x, &y);
W=x2-x1, H=y2-y1;
if (x<x1) tmp+=(x1-x)*H/2.0;
if (x>x2) tmp+=(x-x2)*H/2.0;
if (y<y1) tmp+=(y1-y)*W/2.0;
if (y>y2) tmp+=(y-y2)*W/2.0;
printf("%.1f\n", W*H+tmp);
}
|
[
"arasi27676271@gmail.com"
] |
arasi27676271@gmail.com
|
2d0f3f46e819d631a4fc59ecf1352ef65da660ac
|
68aa47b6de663a691a45604987d05f52b47e8073
|
/src/kflio_node.cpp
|
06a6e8bc0b8dd8d1988a3209610254515ac24062
|
[] |
no_license
|
liuxinren456852/test
|
993337fbee1ae6ad8845c9bd37d5fa8015ea7c44
|
5ad8bae3389c344dc0f4e8156e17abec1b176355
|
refs/heads/master
| 2022-04-08T11:13:28.351385
| 2020-02-27T19:34:51
| 2020-02-27T19:34:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 550
|
cpp
|
#include <ros/ros.h>
#include <parameters.h>
#include <Estimator.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "liom_fusion_node");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
ROS_INFO("\033[1;32m---->\033[0m Feature IMU Association Started.");
parameter::readParameters(pnh);
fusion::Liom liom(nh, pnh);
liom.run();
/*
ros::Rate rate(200);
while (ros::ok())
{
ros::spinOnce();
liom.process();
rate.sleep();
}*/
ros::spin();
return 0;
}
|
[
"qinchaom4a1@163.com"
] |
qinchaom4a1@163.com
|
2b3951b075345a7f29e0aafab13de1fbe63499d1
|
58475d1b39384a6a016227c93e2ab69521a26d4c
|
/AVR_tools/Owi.cpp
|
9b8b34ebb7c59a547af945af1ffff5cf2b48aeb6
|
[
"Beerware"
] |
permissive
|
uncle-Zoid/AVR
|
32cc457e29673d55c179256fdceaa4ad58f83bb7
|
143e51ccab5e7286f40a2f8ce4e4200a359c0bca
|
refs/heads/master
| 2022-12-10T22:52:35.772523
| 2020-08-27T12:04:58
| 2020-08-27T12:04:58
| 283,755,019
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,023
|
cpp
|
/*
* Owi.cpp
*
* Created: 18.06.2020 10:05:41
* Author: pappd
*/
#include "Owi.h"
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
Owi::Owi(const AvrPort &port, uint8_t pin)
: port_ (port)
, pin_ (pin)
{ }
byte_t Owi::reset()
{
cli();
setbit (*port_.ddr, pin_); // nastav pin jako vystupni
setbit (*port_.port, pin_); // nahod sbernici
_delay_us(5);
resbit (*port_.port, pin_); // stahni sbernici
_delay_us(H);
setbit (*port_.port, pin_); // uvolni sbernici
_delay_us(I);
resbit (*port_.ddr, pin_); // nastavit pin jako vstupni
byte_t presence = !testbit (*port_.pin, pin_); // precti hodnotu
_delay_us (J);
sei();
return presence;
}
void Owi::writeBit(byte_t bit)
{
cli ();
setbit (*port_.ddr, pin_);
resbit (*port_.port, pin_);
if (bit)
{
_delay_us(A);
setbit (*port_.port, pin_);
_delay_us(B);
}
else
{
_delay_us(C);
setbit (*port_.port, pin_);
_delay_us(D);
}
sei ();
}
void Owi::writeByte(byte_t byte)
{
for (uint8_t i = 0; i < 8; ++i)
{
writeBit(byte & 0x01);
byte >>= 1;
}
}
byte_t Owi::readBit()
{
byte_t res = 0;
cli ();
setbit (*port_.ddr, pin_);
resbit (*port_.port, pin_);
_delay_us (A);
setbit (*port_.port, pin_);
_delay_us (E);
resbit (*port_.ddr, pin_); // nastav jako vstupni
res = testbit (*port_.pin, pin_);
_delay_us (F);
sei ();
return res;
}
byte_t Owi::readByte()
{
byte_t result = 0x00;
for (uint8_t i = 0; i < 8; ++i)
{
result >>= 1;
result |= 0x80 * readBit();
}
return result;
}
void Owi::readROM(byte_t *rom, byte_t size)
{
reset();
writeByte(OWI_READ_ROM);
for (uint8_t i = 0; i < size; ++i)
{
rom[i] = readByte();
}
}
void Owi::skipRom()
{
reset();
writeByte(OWI_SKIP_ROM);
}
void Owi::matchROM(byte_t *ROM_64bit)
{
reset();
writeByte(OWI_MATCH_ROM);
for(uint8_t i = 0; i < 8; ++i)
{
writeByte(ROM_64bit[i]);
}
}
|
[
"dominik.papp@tcz.cz"
] |
dominik.papp@tcz.cz
|
7a5ac76848e1eb05658b9463968878209af26d51
|
0ed1b441759ef92872821a07f6c6cff04094e390
|
/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp
|
eca774ead93531ec6b4f94b5909439396f89f62e
|
[
"NCSA"
] |
permissive
|
sslab-gatech/caver
|
651dd1e404c03a9568ef512164c98e918821c9e8
|
81363a7d0581d99fe216c4394294b0a2372f08eb
|
refs/heads/master
| 2021-01-10T03:43:56.533854
| 2015-10-13T18:23:15
| 2015-10-13T18:23:15
| 44,137,365
| 30
| 10
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 37,374
|
cpp
|
//===-- PPCRegisterInfo.cpp - PowerPC Register Information ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC implementation of the TargetRegisterInfo
// class.
//
//===----------------------------------------------------------------------===//
#include "PPCRegisterInfo.h"
#include "PPC.h"
#include "PPCFrameLowering.h"
#include "PPCInstrBuilder.h"
#include "PPCMachineFunctionInfo.h"
#include "PPCSubtarget.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <cstdlib>
using namespace llvm;
#define DEBUG_TYPE "reginfo"
#define GET_REGINFO_TARGET_DESC
#include "PPCGenRegisterInfo.inc"
static cl::opt<bool>
EnableBasePointer("ppc-use-base-pointer", cl::Hidden, cl::init(true),
cl::desc("Enable use of a base pointer for complex stack frames"));
static cl::opt<bool>
AlwaysBasePointer("ppc-always-use-base-pointer", cl::Hidden, cl::init(false),
cl::desc("Force the use of a base pointer in every function"));
PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST)
: PPCGenRegisterInfo(ST.isPPC64() ? PPC::LR8 : PPC::LR,
ST.isPPC64() ? 0 : 1,
ST.isPPC64() ? 0 : 1),
Subtarget(ST) {
ImmToIdxMap[PPC::LD] = PPC::LDX; ImmToIdxMap[PPC::STD] = PPC::STDX;
ImmToIdxMap[PPC::LBZ] = PPC::LBZX; ImmToIdxMap[PPC::STB] = PPC::STBX;
ImmToIdxMap[PPC::LHZ] = PPC::LHZX; ImmToIdxMap[PPC::LHA] = PPC::LHAX;
ImmToIdxMap[PPC::LWZ] = PPC::LWZX; ImmToIdxMap[PPC::LWA] = PPC::LWAX;
ImmToIdxMap[PPC::LFS] = PPC::LFSX; ImmToIdxMap[PPC::LFD] = PPC::LFDX;
ImmToIdxMap[PPC::STH] = PPC::STHX; ImmToIdxMap[PPC::STW] = PPC::STWX;
ImmToIdxMap[PPC::STFS] = PPC::STFSX; ImmToIdxMap[PPC::STFD] = PPC::STFDX;
ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
ImmToIdxMap[PPC::LWA_32] = PPC::LWAX_32;
// 64-bit
ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
}
/// getPointerRegClass - Return the register class to use to hold pointers.
/// This is used for addressing modes.
const TargetRegisterClass *
PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
const {
// Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
// when it checks for ZERO folding.
if (Kind == 1) {
if (Subtarget.isPPC64())
return &PPC::G8RC_NOX0RegClass;
return &PPC::GPRC_NOR0RegClass;
}
if (Subtarget.isPPC64())
return &PPC::G8RCRegClass;
return &PPC::GPRCRegClass;
}
const MCPhysReg*
PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
if (Subtarget.isDarwinABI())
return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
CSR_Darwin64_Altivec_SaveList :
CSR_Darwin64_SaveList) :
(Subtarget.hasAltivec() ?
CSR_Darwin32_Altivec_SaveList :
CSR_Darwin32_SaveList);
return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
CSR_SVR464_Altivec_SaveList :
CSR_SVR464_SaveList) :
(Subtarget.hasAltivec() ?
CSR_SVR432_Altivec_SaveList :
CSR_SVR432_SaveList);
}
const uint32_t*
PPCRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
if (Subtarget.isDarwinABI())
return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
CSR_Darwin64_Altivec_RegMask :
CSR_Darwin64_RegMask) :
(Subtarget.hasAltivec() ?
CSR_Darwin32_Altivec_RegMask :
CSR_Darwin32_RegMask);
return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
CSR_SVR464_Altivec_RegMask :
CSR_SVR464_RegMask) :
(Subtarget.hasAltivec() ?
CSR_SVR432_Altivec_RegMask :
CSR_SVR432_RegMask);
}
const uint32_t*
PPCRegisterInfo::getNoPreservedMask() const {
return CSR_NoRegs_RegMask;
}
BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
BitVector Reserved(getNumRegs());
const PPCFrameLowering *PPCFI =
static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
// The ZERO register is not really a register, but the representation of r0
// when used in instructions that treat r0 as the constant 0.
Reserved.set(PPC::ZERO);
Reserved.set(PPC::ZERO8);
// The FP register is also not really a register, but is the representation
// of the frame pointer register used by ISD::FRAMEADDR.
Reserved.set(PPC::FP);
Reserved.set(PPC::FP8);
// The BP register is also not really a register, but is the representation
// of the base pointer register used by setjmp.
Reserved.set(PPC::BP);
Reserved.set(PPC::BP8);
// The counter registers must be reserved so that counter-based loops can
// be correctly formed (and the mtctr instructions are not DCE'd).
Reserved.set(PPC::CTR);
Reserved.set(PPC::CTR8);
Reserved.set(PPC::R1);
Reserved.set(PPC::LR);
Reserved.set(PPC::LR8);
Reserved.set(PPC::RM);
if (!Subtarget.isDarwinABI() || !Subtarget.hasAltivec())
Reserved.set(PPC::VRSAVE);
// The SVR4 ABI reserves r2 and r13
if (Subtarget.isSVR4ABI()) {
Reserved.set(PPC::R2); // System-reserved register
Reserved.set(PPC::R13); // Small Data Area pointer register
}
// On PPC64, r13 is the thread pointer. Never allocate this register.
if (Subtarget.isPPC64()) {
Reserved.set(PPC::R13);
Reserved.set(PPC::X1);
Reserved.set(PPC::X13);
if (PPCFI->needsFP(MF))
Reserved.set(PPC::X31);
if (hasBasePointer(MF))
Reserved.set(PPC::X30);
// The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
if (Subtarget.isSVR4ABI()) {
Reserved.set(PPC::X2);
}
}
if (PPCFI->needsFP(MF))
Reserved.set(PPC::R31);
if (hasBasePointer(MF))
Reserved.set(PPC::R30);
// Reserve Altivec registers when Altivec is unavailable.
if (!Subtarget.hasAltivec())
for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
IE = PPC::VRRCRegClass.end(); I != IE; ++I)
Reserved.set(*I);
return Reserved;
}
unsigned
PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
const unsigned DefaultSafety = 1;
switch (RC->getID()) {
default:
return 0;
case PPC::G8RC_NOX0RegClassID:
case PPC::GPRC_NOR0RegClassID:
case PPC::G8RCRegClassID:
case PPC::GPRCRegClassID: {
unsigned FP = TFI->hasFP(MF) ? 1 : 0;
return 32 - FP - DefaultSafety;
}
case PPC::F8RCRegClassID:
case PPC::F4RCRegClassID:
case PPC::VRRCRegClassID:
case PPC::VFRCRegClassID:
case PPC::VSLRCRegClassID:
case PPC::VSHRCRegClassID:
return 32 - DefaultSafety;
case PPC::VSRCRegClassID:
case PPC::VSFRCRegClassID:
return 64 - DefaultSafety;
case PPC::CRRCRegClassID:
return 8 - DefaultSafety;
}
}
const TargetRegisterClass*
PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)const {
if (Subtarget.hasVSX()) {
// With VSX, we can inflate various sub-register classes to the full VSX
// register set.
if (RC == &PPC::F8RCRegClass)
return &PPC::VSFRCRegClass;
else if (RC == &PPC::VRRCRegClass)
return &PPC::VSRCRegClass;
}
return TargetRegisterInfo::getLargestLegalSuperClass(RC);
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
/// lowerDynamicAlloc - Generate the code for allocating an object in the
/// current frame. The sequence of code with be in the general form
///
/// addi R0, SP, \#frameSize ; get the address of the previous frame
/// stwxu R0, SP, Rnegsize ; add and update the SP with the negated size
/// addi Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
///
void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
// Get the instruction.
MachineInstr &MI = *II;
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
// Get the basic block's function.
MachineFunction &MF = *MBB.getParent();
// Get the frame info.
MachineFrameInfo *MFI = MF.getFrameInfo();
// Get the instruction info.
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
// Determine whether 64-bit pointers are used.
bool LP64 = Subtarget.isPPC64();
DebugLoc dl = MI.getDebugLoc();
// Get the maximum call stack size.
unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
// Get the total frame size.
unsigned FrameSize = MFI->getStackSize();
// Get stack alignments.
unsigned TargetAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
unsigned MaxAlign = MFI->getMaxAlignment();
assert((maxCallFrameSize & (MaxAlign-1)) == 0 &&
"Maximum call-frame size not sufficiently aligned");
// Determine the previous frame's address. If FrameSize can't be
// represented as 16 bits or we need special alignment, then we load the
// previous frame's address from 0(SP). Why not do an addis of the hi?
// Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
// Constructing the constant and adding would take 3 instructions.
// Fortunately, a frame greater than 32K is rare.
const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
.addReg(PPC::R31)
.addImm(FrameSize);
} else if (LP64) {
BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
.addImm(0)
.addReg(PPC::X1);
} else {
BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
.addImm(0)
.addReg(PPC::R1);
}
bool KillNegSizeReg = MI.getOperand(1).isKill();
unsigned NegSizeReg = MI.getOperand(1).getReg();
// Grow the stack and update the stack pointer link, then determine the
// address of new allocated space.
if (LP64) {
if (MaxAlign > TargetAlign) {
unsigned UnalNegSizeReg = NegSizeReg;
NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
// Unfortunately, there is no andi, only andi., and we can't insert that
// here because we might clobber cr0 while it is live.
BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
.addImm(~(MaxAlign-1));
unsigned NegSizeReg1 = NegSizeReg;
NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
.addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
.addReg(NegSizeReg1, RegState::Kill);
KillNegSizeReg = true;
}
BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
.addReg(Reg, RegState::Kill)
.addReg(PPC::X1)
.addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
.addReg(PPC::X1)
.addImm(maxCallFrameSize);
} else {
if (MaxAlign > TargetAlign) {
unsigned UnalNegSizeReg = NegSizeReg;
NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
// Unfortunately, there is no andi, only andi., and we can't insert that
// here because we might clobber cr0 while it is live.
BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
.addImm(~(MaxAlign-1));
unsigned NegSizeReg1 = NegSizeReg;
NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
.addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
.addReg(NegSizeReg1, RegState::Kill);
KillNegSizeReg = true;
}
BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
.addReg(Reg, RegState::Kill)
.addReg(PPC::R1)
.addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
.addReg(PPC::R1)
.addImm(maxCallFrameSize);
}
// Discard the DYNALLOC instruction.
MBB.erase(II);
}
/// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
/// reserving a whole register (R0), we scrounge for one here. This generates
/// code like this:
///
/// mfcr rA ; Move the conditional register into GPR rA.
/// rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
/// stw rA, FI ; Store rA to the frame.
///
void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
unsigned FrameIndex) const {
// Get the instruction.
MachineInstr &MI = *II; // ; SPILL_CR <SrcReg>, <offset>
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc dl = MI.getDebugLoc();
bool LP64 = Subtarget.isPPC64();
const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
unsigned SrcReg = MI.getOperand(0).getReg();
// We need to store the CR in the low 4-bits of the saved value. First, issue
// an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
.addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
// If the saved register wasn't CR0, shift the bits left so that they are in
// CR0's slot.
if (SrcReg != PPC::CR0) {
unsigned Reg1 = Reg;
Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
// rlwinm rA, rA, ShiftBits, 0, 31.
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
.addReg(Reg1, RegState::Kill)
.addImm(getEncodingValue(SrcReg) * 4)
.addImm(0)
.addImm(31);
}
addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
.addReg(Reg, RegState::Kill),
FrameIndex);
// Discard the pseudo instruction.
MBB.erase(II);
}
void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
unsigned FrameIndex) const {
// Get the instruction.
MachineInstr &MI = *II; // ; <DestReg> = RESTORE_CR <offset>
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc dl = MI.getDebugLoc();
bool LP64 = Subtarget.isPPC64();
const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
unsigned DestReg = MI.getOperand(0).getReg();
assert(MI.definesRegister(DestReg) &&
"RESTORE_CR does not define its destination");
addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
Reg), FrameIndex);
// If the reloaded register isn't CR0, shift the bits right so that they are
// in the right CR's slot.
if (DestReg != PPC::CR0) {
unsigned Reg1 = Reg;
Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
unsigned ShiftBits = getEncodingValue(DestReg)*4;
// rlwinm r11, r11, 32-ShiftBits, 0, 31.
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
.addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
.addImm(31);
}
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
.addReg(Reg, RegState::Kill);
// Discard the pseudo instruction.
MBB.erase(II);
}
static unsigned getCRFromCRBit(unsigned SrcReg) {
unsigned Reg = 0;
if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR0GT ||
SrcReg == PPC::CR0EQ || SrcReg == PPC::CR0UN)
Reg = PPC::CR0;
else if (SrcReg == PPC::CR1LT || SrcReg == PPC::CR1GT ||
SrcReg == PPC::CR1EQ || SrcReg == PPC::CR1UN)
Reg = PPC::CR1;
else if (SrcReg == PPC::CR2LT || SrcReg == PPC::CR2GT ||
SrcReg == PPC::CR2EQ || SrcReg == PPC::CR2UN)
Reg = PPC::CR2;
else if (SrcReg == PPC::CR3LT || SrcReg == PPC::CR3GT ||
SrcReg == PPC::CR3EQ || SrcReg == PPC::CR3UN)
Reg = PPC::CR3;
else if (SrcReg == PPC::CR4LT || SrcReg == PPC::CR4GT ||
SrcReg == PPC::CR4EQ || SrcReg == PPC::CR4UN)
Reg = PPC::CR4;
else if (SrcReg == PPC::CR5LT || SrcReg == PPC::CR5GT ||
SrcReg == PPC::CR5EQ || SrcReg == PPC::CR5UN)
Reg = PPC::CR5;
else if (SrcReg == PPC::CR6LT || SrcReg == PPC::CR6GT ||
SrcReg == PPC::CR6EQ || SrcReg == PPC::CR6UN)
Reg = PPC::CR6;
else if (SrcReg == PPC::CR7LT || SrcReg == PPC::CR7GT ||
SrcReg == PPC::CR7EQ || SrcReg == PPC::CR7UN)
Reg = PPC::CR7;
assert(Reg != 0 && "Invalid CR bit register");
return Reg;
}
void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
unsigned FrameIndex) const {
// Get the instruction.
MachineInstr &MI = *II; // ; SPILL_CRBIT <SrcReg>, <offset>
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc dl = MI.getDebugLoc();
bool LP64 = Subtarget.isPPC64();
const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
unsigned SrcReg = MI.getOperand(0).getReg();
BuildMI(MBB, II, dl, TII.get(TargetOpcode::KILL),
getCRFromCRBit(SrcReg))
.addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
.addReg(getCRFromCRBit(SrcReg));
// If the saved register wasn't CR0LT, shift the bits left so that the bit to
// store is the first one. Mask all but that bit.
unsigned Reg1 = Reg;
Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
// rlwinm rA, rA, ShiftBits, 0, 0.
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
.addReg(Reg1, RegState::Kill)
.addImm(getEncodingValue(SrcReg))
.addImm(0).addImm(0);
addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
.addReg(Reg, RegState::Kill),
FrameIndex);
// Discard the pseudo instruction.
MBB.erase(II);
}
void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
unsigned FrameIndex) const {
// Get the instruction.
MachineInstr &MI = *II; // ; <DestReg> = RESTORE_CRBIT <offset>
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc dl = MI.getDebugLoc();
bool LP64 = Subtarget.isPPC64();
const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
unsigned DestReg = MI.getOperand(0).getReg();
assert(MI.definesRegister(DestReg) &&
"RESTORE_CRBIT does not define its destination");
addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
Reg), FrameIndex);
BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
unsigned RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
.addReg(getCRFromCRBit(DestReg));
unsigned ShiftBits = getEncodingValue(DestReg);
// rlwimi r11, r10, 32-ShiftBits, ..., ...
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
.addReg(RegO, RegState::Kill).addReg(Reg, RegState::Kill)
.addImm(ShiftBits ? 32-ShiftBits : 0)
.addImm(ShiftBits).addImm(ShiftBits);
BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
getCRFromCRBit(DestReg))
.addReg(RegO, RegState::Kill)
// Make sure we have a use dependency all the way through this
// sequence of instructions. We can't have the other bits in the CR
// modified in between the mfocrf and the mtocrf.
.addReg(getCRFromCRBit(DestReg), RegState::Implicit);
// Discard the pseudo instruction.
MBB.erase(II);
}
void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
unsigned FrameIndex) const {
// Get the instruction.
MachineInstr &MI = *II; // ; SPILL_VRSAVE <SrcReg>, <offset>
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc dl = MI.getDebugLoc();
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
unsigned SrcReg = MI.getOperand(0).getReg();
BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
.addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
.addReg(Reg, RegState::Kill),
FrameIndex);
// Discard the pseudo instruction.
MBB.erase(II);
}
void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
unsigned FrameIndex) const {
// Get the instruction.
MachineInstr &MI = *II; // ; <DestReg> = RESTORE_VRSAVE <offset>
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc dl = MI.getDebugLoc();
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
unsigned DestReg = MI.getOperand(0).getReg();
assert(MI.definesRegister(DestReg) &&
"RESTORE_VRSAVE does not define its destination");
addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
Reg), FrameIndex);
BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
.addReg(Reg, RegState::Kill);
// Discard the pseudo instruction.
MBB.erase(II);
}
bool
PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
unsigned Reg, int &FrameIdx) const {
// For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
// ABI, return true to prevent allocating an additional frame slot.
// For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
// is arbitrary and will be subsequently ignored. For 32-bit, we have
// previously created the stack slot if needed, so return its FrameIdx.
if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
if (Subtarget.isPPC64())
FrameIdx = 0;
else {
const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
FrameIdx = FI->getCRSpillFrameIndex();
}
return true;
}
return false;
}
// Figure out if the offset in the instruction must be a multiple of 4.
// This is true for instructions like "STD".
static bool usesIXAddr(const MachineInstr &MI) {
unsigned OpC = MI.getOpcode();
switch (OpC) {
default:
return false;
case PPC::LWA:
case PPC::LWA_32:
case PPC::LD:
case PPC::STD:
return true;
}
}
// Return the OffsetOperandNo given the FIOperandNum (and the instruction).
static unsigned getOffsetONFromFION(const MachineInstr &MI,
unsigned FIOperandNum) {
// Take into account whether it's an add or mem instruction
unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
if (MI.isInlineAsm())
OffsetOperandNo = FIOperandNum-1;
return OffsetOperandNo;
}
void
PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOperandNum,
RegScavenger *RS) const {
assert(SPAdj == 0 && "Unexpected");
// Get the instruction.
MachineInstr &MI = *II;
// Get the instruction's basic block.
MachineBasicBlock &MBB = *MI.getParent();
// Get the basic block's function.
MachineFunction &MF = *MBB.getParent();
// Get the instruction info.
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
// Get the frame info.
MachineFrameInfo *MFI = MF.getFrameInfo();
DebugLoc dl = MI.getDebugLoc();
unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
// Get the frame index.
int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
// Get the frame pointer save index. Users of this index are primarily
// DYNALLOC instructions.
PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
int FPSI = FI->getFramePointerSaveIndex();
// Get the instruction opcode.
unsigned OpC = MI.getOpcode();
// Special case for dynamic alloca.
if (FPSI && FrameIndex == FPSI &&
(OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
lowerDynamicAlloc(II);
return;
}
// Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
if (OpC == PPC::SPILL_CR) {
lowerCRSpilling(II, FrameIndex);
return;
} else if (OpC == PPC::RESTORE_CR) {
lowerCRRestore(II, FrameIndex);
return;
} else if (OpC == PPC::SPILL_CRBIT) {
lowerCRBitSpilling(II, FrameIndex);
return;
} else if (OpC == PPC::RESTORE_CRBIT) {
lowerCRBitRestore(II, FrameIndex);
return;
} else if (OpC == PPC::SPILL_VRSAVE) {
lowerVRSAVESpilling(II, FrameIndex);
return;
} else if (OpC == PPC::RESTORE_VRSAVE) {
lowerVRSAVERestore(II, FrameIndex);
return;
}
// Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
MI.getOperand(FIOperandNum).ChangeToRegister(
FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
// Figure out if the offset in the instruction is shifted right two bits.
bool isIXAddr = usesIXAddr(MI);
// If the instruction is not present in ImmToIdxMap, then it has no immediate
// form (and must be r+r).
bool noImmForm = !MI.isInlineAsm() && !ImmToIdxMap.count(OpC);
// Now add the frame object offset to the offset from r1.
int Offset = MFI->getObjectOffset(FrameIndex);
Offset += MI.getOperand(OffsetOperandNo).getImm();
// If we're not using a Frame Pointer that has been set to the value of the
// SP before having the stack size subtracted from it, then add the stack size
// to Offset to get the correct offset.
// Naked functions have stack size 0, although getStackSize may not reflect that
// because we didn't call all the pieces that compute it for naked functions.
if (!MF.getFunction()->getAttributes().
hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked)) {
if (!(hasBasePointer(MF) && FrameIndex < 0))
Offset += MFI->getStackSize();
}
// If we can, encode the offset directly into the instruction. If this is a
// normal PPC "ri" instruction, any 16-bit value can be safely encoded. If
// this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
// clear can be encoded. This is extremely uncommon, because normally you
// only "std" to a stack slot that is at least 4-byte aligned, but it can
// happen in invalid code.
assert(OpC != PPC::DBG_VALUE &&
"This should be handle in a target independent way");
if (!noImmForm && isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
return;
}
// The offset doesn't fit into a single register, scavenge one to build the
// offset in.
bool is64Bit = Subtarget.isPPC64();
const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
SReg = MF.getRegInfo().createVirtualRegister(RC);
// Insert a set of rA with the full offset value before the ld, st, or add
BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
.addImm(Offset >> 16);
BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
.addReg(SRegHi, RegState::Kill)
.addImm(Offset);
// Convert into indexed form of the instruction:
//
// sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
// addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
unsigned OperandBase;
if (noImmForm)
OperandBase = 1;
else if (OpC != TargetOpcode::INLINEASM) {
assert(ImmToIdxMap.count(OpC) &&
"No indexed form of load or store available!");
unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
MI.setDesc(TII.get(NewOpcode));
OperandBase = 1;
} else {
OperandBase = OffsetOperandNo;
}
unsigned StackReg = MI.getOperand(FIOperandNum).getReg();
MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
}
unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
if (!Subtarget.isPPC64())
return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
else
return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
}
unsigned PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
if (!hasBasePointer(MF))
return getFrameRegister(MF);
return Subtarget.isPPC64() ? PPC::X30 : PPC::R30;
}
bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
if (!EnableBasePointer)
return false;
if (AlwaysBasePointer)
return true;
// If we need to realign the stack, then the stack pointer can no longer
// serve as an offset into the caller's stack space. As a result, we need a
// base pointer.
return needsStackRealignment(MF);
}
bool PPCRegisterInfo::canRealignStack(const MachineFunction &MF) const {
if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
return false;
return true;
}
bool PPCRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
const Function *F = MF.getFunction();
unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
bool requiresRealignment =
((MFI->getMaxAlignment() > StackAlign) ||
F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::StackAlignment));
return requiresRealignment && canRealignStack(MF);
}
/// Returns true if the instruction's frame index
/// reference would be better served by a base register other than FP
/// or SP. Used by LocalStackFrameAllocation to determine which frame index
/// references it should create new base registers for.
bool PPCRegisterInfo::
needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
assert(Offset < 0 && "Local offset must be negative");
unsigned FIOperandNum = 0;
while (!MI->getOperand(FIOperandNum).isFI()) {
++FIOperandNum;
assert(FIOperandNum < MI->getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
Offset += MI->getOperand(OffsetOperandNo).getImm();
// It's the load/store FI references that cause issues, as it can be difficult
// to materialize the offset if it won't fit in the literal field. Estimate
// based on the size of the local frame and some conservative assumptions
// about the rest of the stack frame (note, this is pre-regalloc, so
// we don't know everything for certain yet) whether this offset is likely
// to be out of range of the immediate. Return true if so.
// We only generate virtual base registers for loads and stores that have
// an r+i form. Return false for everything else.
unsigned OpC = MI->getOpcode();
if (!ImmToIdxMap.count(OpC))
return false;
// Don't generate a new virtual base register just to add zero to it.
if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
MI->getOperand(2).getImm() == 0)
return false;
MachineBasicBlock &MBB = *MI->getParent();
MachineFunction &MF = *MBB.getParent();
const PPCFrameLowering *PPCFI =
static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
unsigned StackEst =
PPCFI->determineFrameLayout(MF, false, true);
// If we likely don't need a stack frame, then we probably don't need a
// virtual base register either.
if (!StackEst)
return false;
// Estimate an offset from the stack pointer.
// The incoming offset is relating to the SP at the start of the function,
// but when we access the local it'll be relative to the SP after local
// allocation, so adjust our SP-relative offset by that allocation size.
Offset += StackEst;
// The frame pointer will point to the end of the stack, so estimate the
// offset as the difference between the object offset and the FP location.
return !isFrameOffsetLegal(MI, Offset);
}
/// Insert defining instruction(s) for BaseReg to
/// be a pointer to FrameIdx at the beginning of the basic block.
void PPCRegisterInfo::
materializeFrameBaseRegister(MachineBasicBlock *MBB,
unsigned BaseReg, int FrameIdx,
int64_t Offset) const {
unsigned ADDriOpc = Subtarget.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
MachineBasicBlock::iterator Ins = MBB->begin();
DebugLoc DL; // Defaults to "unknown"
if (Ins != MBB->end())
DL = Ins->getDebugLoc();
const MachineFunction &MF = *MBB->getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
const MCInstrDesc &MCID = TII.get(ADDriOpc);
MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
BuildMI(*MBB, Ins, DL, MCID, BaseReg)
.addFrameIndex(FrameIdx).addImm(Offset);
}
void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
int64_t Offset) const {
unsigned FIOperandNum = 0;
while (!MI.getOperand(FIOperandNum).isFI()) {
++FIOperandNum;
assert(FIOperandNum < MI.getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
}
MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
Offset += MI.getOperand(OffsetOperandNo).getImm();
MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
const MCInstrDesc &MCID = MI.getDesc();
MachineRegisterInfo &MRI = MF.getRegInfo();
MRI.constrainRegClass(BaseReg,
TII.getRegClass(MCID, FIOperandNum, this, MF));
}
bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
int64_t Offset) const {
return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
(isInt<16>(Offset) && (!usesIXAddr(*MI) || (Offset & 3) == 0));
}
|
[
"lifeasageek@gmail.com"
] |
lifeasageek@gmail.com
|
4fdddc4be907ae141cb823ca6a68e9de844c41db
|
e76ea38dbe5774fccaf14e1a0090d9275cdaee08
|
/src/ash/test/test_launcher_item_delegate.cc
|
7ac8b727f64a66f34499abcc879493d0089b5c74
|
[
"BSD-3-Clause"
] |
permissive
|
eurogiciel-oss/Tizen_Crosswalk
|
efc424807a5434df1d5c9e8ed51364974643707d
|
a68aed6e29bd157c95564e7af2e3a26191813e51
|
refs/heads/master
| 2021-01-18T19:19:04.527505
| 2014-02-06T13:43:21
| 2014-02-06T13:43:21
| 16,070,101
| 1
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,253
|
cc
|
// Copyright 2013 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 "ash/test/test_launcher_item_delegate.h"
#include "ash/wm/window_util.h"
#include "ui/aura/window.h"
namespace ash {
namespace test {
TestLauncherItemDelegate::TestLauncherItemDelegate(aura::Window* window)
: window_(window) {
}
TestLauncherItemDelegate::~TestLauncherItemDelegate() {
}
void TestLauncherItemDelegate::ItemSelected(const ui::Event& event) {
if (window_) {
if (window_->type() == aura::client::WINDOW_TYPE_PANEL)
ash::wm::MoveWindowToEventRoot(window_, event);
window_->Show();
ash::wm::ActivateWindow(window_);
}
}
base::string16 TestLauncherItemDelegate::GetTitle() {
return window_ ? window_->title() : base::string16();
}
ui::MenuModel* TestLauncherItemDelegate::CreateContextMenu(
aura::Window* root_window) {
return NULL;
}
ash::LauncherMenuModel* TestLauncherItemDelegate::CreateApplicationMenu(
int event_flags) {
return NULL;
}
bool TestLauncherItemDelegate::IsDraggable() {
return true;
}
bool TestLauncherItemDelegate::ShouldShowTooltip() {
return true;
}
} // namespace test
} // namespace ash
|
[
"ronan@fridu.net"
] |
ronan@fridu.net
|
fefe116c87467822bc7a5606dbf092fa45c69b79
|
16d488cb25d6dd784e13c288cfc7c1ac5fb1d23a
|
/triangle/triangle.hpp
|
b1b8614be33c2b00320066a3bc9981a10cdbe5f2
|
[] |
no_license
|
sufuf3/ST2017-hw4-Symbolic_and_Fuzz
|
59ca97d5437ef2efdb0df93a068a7f7f044e64b7
|
d148795b7ffafa556d10f7ee657add0cc6ea1d84
|
refs/heads/master
| 2020-12-25T18:52:18.145022
| 2017-06-12T07:45:58
| 2017-06-12T07:47:34
| 94,000,815
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 262
|
hpp
|
#ifndef __TRIANGLE_H__
#define __TRIANGLE_H__
#define MIN 1
#define MAX 200
#define TYPE_INVALID_INPUT 0
#define TYPE_NOTTRIANGLE 1
#define TYPE_EQUILATERAL 2
#define TYPE_ISOSCELES 3
#define TYPE_SCALENE 4
int triangle_type( int a, int b, int c );
#endif
|
[
"sufuf3@gmail.com"
] |
sufuf3@gmail.com
|
d3deba0f0cd312054f5cbc40f7db7a5f2957f537
|
85e419bed080da37dd13d2dd4276a486ae6fbe07
|
/MusicPlayer/MyForm.h
|
3ac03825701d876c2cd6961a32d5f57a5f474ceb
|
[] |
no_license
|
mvrtn/mvrtn
|
afefded1bbfd48be73e3aea98b60106b04dad95b
|
fc03aa545c65fb20228968f5d091b3f129aa6b7d
|
refs/heads/master
| 2020-03-12T11:33:51.726893
| 2018-04-22T20:30:14
| 2018-04-22T20:30:14
| 130,599,549
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 11,817
|
h
|
#pragma once
#include "Player.h"
namespace MusicPlayer {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
using namespace WMPLib;
/// <summary>
/// Podsumowanie informacji o MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: W tym miejscu dodaj kod konstruktora
//
}
protected:
/// <summary>
/// Wyczyść wszystkie używane zasoby.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
System::Windows::Forms::ListViewItem^ listViewItem;
private: System::Windows::Forms::Button^ button1;
protected:
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Button^ button3;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::Button^ button5;
private: System::Windows::Forms::Button^ button6;
private: System::Windows::Forms::MenuStrip^ menuStrip1;
private: System::Windows::Forms::ToolStripMenuItem^ fileToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ openFileToolStripMenuItem;
private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator1;
private: System::Windows::Forms::ToolStripMenuItem^ quitToolStripMenuItem;
private: System::Windows::Forms::ListView^ listView1;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::ColumnHeader^ columnHeader1;
private: AxWMPLib::AxWindowsMediaPlayer^ axWindowsMediaPlayer1;
private:
/// <summary>
/// Wymagana zmienna projektanta.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Wymagana metoda obsługi projektanta — nie należy modyfikować
/// zawartość tej metody z edytorem kodu.
/// </summary>
OpenFileDialog^ OpenFileDialog1 = gcnew OpenFileDialog();
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MyForm::typeid));
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->button3 = (gcnew System::Windows::Forms::Button());
this->button4 = (gcnew System::Windows::Forms::Button());
this->button5 = (gcnew System::Windows::Forms::Button());
this->button6 = (gcnew System::Windows::Forms::Button());
this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());
this->fileToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->openFileToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->toolStripSeparator1 = (gcnew System::Windows::Forms::ToolStripSeparator());
this->quitToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->listView1 = (gcnew System::Windows::Forms::ListView());
this->columnHeader1 = (gcnew System::Windows::Forms::ColumnHeader());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->axWindowsMediaPlayer1 = (gcnew AxWMPLib::AxWindowsMediaPlayer());
this->menuStrip1->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->axWindowsMediaPlayer1))->BeginInit();
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(3, 46);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"Play";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// button2
//
this->button2->Location = System::Drawing::Point(84, 46);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 1;
this->button2->Text = L"Pause";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
//
// button3
//
this->button3->Location = System::Drawing::Point(246, 46);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(75, 23);
this->button3->TabIndex = 2;
this->button3->Text = L"Next";
this->button3->UseVisualStyleBackColor = true;
//
// button4
//
this->button4->Location = System::Drawing::Point(165, 46);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(75, 23);
this->button4->TabIndex = 3;
this->button4->Text = L"Stop";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &MyForm::button4_Click);
//
// button5
//
this->button5->Location = System::Drawing::Point(327, 46);
this->button5->Name = L"button5";
this->button5->Size = System::Drawing::Size(75, 23);
this->button5->TabIndex = 4;
this->button5->Text = L"Previous";
this->button5->UseVisualStyleBackColor = true;
//
// button6
//
this->button6->Location = System::Drawing::Point(408, 46);
this->button6->Name = L"button6";
this->button6->Size = System::Drawing::Size(75, 23);
this->button6->TabIndex = 5;
this->button6->Text = L"Random";
this->button6->UseVisualStyleBackColor = true;
//
// menuStrip1
//
this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->fileToolStripMenuItem });
this->menuStrip1->Location = System::Drawing::Point(0, 0);
this->menuStrip1->Name = L"menuStrip1";
this->menuStrip1->Size = System::Drawing::Size(507, 24);
this->menuStrip1->TabIndex = 7;
this->menuStrip1->Text = L"menuStrip1";
//
// fileToolStripMenuItem
//
this->fileToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) {
this->openFileToolStripMenuItem,
this->toolStripSeparator1, this->quitToolStripMenuItem
});
this->fileToolStripMenuItem->Name = L"fileToolStripMenuItem";
this->fileToolStripMenuItem->Size = System::Drawing::Size(37, 20);
this->fileToolStripMenuItem->Text = L"File";
//
// openFileToolStripMenuItem
//
this->openFileToolStripMenuItem->Name = L"openFileToolStripMenuItem";
this->openFileToolStripMenuItem->Size = System::Drawing::Size(180, 22);
this->openFileToolStripMenuItem->Text = L"Open File";
this->openFileToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::openFileToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this->toolStripSeparator1->Name = L"toolStripSeparator1";
this->toolStripSeparator1->Size = System::Drawing::Size(177, 6);
//
// quitToolStripMenuItem
//
this->quitToolStripMenuItem->Name = L"quitToolStripMenuItem";
this->quitToolStripMenuItem->Size = System::Drawing::Size(180, 22);
this->quitToolStripMenuItem->Text = L"Quit";
this->quitToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::quitToolStripMenuItem_Click);
//
// listView1
//
this->listView1->Columns->AddRange(gcnew cli::array< System::Windows::Forms::ColumnHeader^ >(1) { this->columnHeader1 });
this->listView1->Location = System::Drawing::Point(12, 214);
this->listView1->MultiSelect = false;
this->listView1->Name = L"listView1";
this->listView1->Size = System::Drawing::Size(483, 189);
this->listView1->TabIndex = 8;
this->listView1->UseCompatibleStateImageBehavior = false;
this->listView1->View = System::Windows::Forms::View::Details;
this->listView1->SelectedIndexChanged += gcnew System::EventHandler(this, &MyForm::listView1_SelectedIndexChanged);
//
// columnHeader1
//
this->columnHeader1->Text = L"Ścieżka";
this->columnHeader1->Width = 363;
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(12, 145);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(205, 20);
this->textBox1->TabIndex = 9;
this->textBox1->TextChanged += gcnew System::EventHandler(this, &MyForm::textBox1_TextChanged);
//
// axWindowsMediaPlayer1
//
this->axWindowsMediaPlayer1->Enabled = true;
this->axWindowsMediaPlayer1->Location = System::Drawing::Point(261, 90);
this->axWindowsMediaPlayer1->Name = L"axWindowsMediaPlayer1";
this->axWindowsMediaPlayer1->OcxState = (cli::safe_cast<System::Windows::Forms::AxHost::State^>(resources->GetObject(L"axWindowsMediaPlayer1.OcxState")));
this->axWindowsMediaPlayer1->Size = System::Drawing::Size(222, 99);
this->axWindowsMediaPlayer1->TabIndex = 10;
this->axWindowsMediaPlayer1->Enter += gcnew System::EventHandler(this, &MyForm::axWindowsMediaPlayer1_Enter);
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(507, 415);
this->Controls->Add(this->axWindowsMediaPlayer1);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->listView1);
this->Controls->Add(this->button6);
this->Controls->Add(this->button5);
this->Controls->Add(this->button4);
this->Controls->Add(this->button3);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Controls->Add(this->menuStrip1);
this->MainMenuStrip = this->menuStrip1;
this->Name = L"MyForm";
this->Text = L"MyForm";
this->menuStrip1->ResumeLayout(false);
this->menuStrip1->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->axWindowsMediaPlayer1))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void quitToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
this->Close();
}
private: System::Void openFileToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
Stream^ myStream;
if (OpenFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
if ((myStream = OpenFileDialog1->OpenFile()) != nullptr)
{
String^ strfilename = OpenFileDialog1->InitialDirectory + OpenFileDialog1->FileName;
MessageBox::Show(strfilename);
//textBox1->Text = OpenFileDialog1->FileName;
listViewItem = gcnew Windows::Forms::ListViewItem(this->OpenFileDialog1->FileName);
this->listView1->Items->Add(this->listViewItem);
myStream->Close();
}
}
}
private: System::Void listView1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Player::open();
//if (axWindowsMediaPlayer1->URL != OpenFileDialog1->FileName)
//axWindowsMediaPlayer1->URL = OpenFileDialog1->FileName;
//axWindowsMediaPlayer1->Ctlcontrols->play();
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
axWindowsMediaPlayer1->Ctlcontrols->pause();
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
axWindowsMediaPlayer1->Ctlcontrols->stop();
}
private: System::Void openFolderToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void axWindowsMediaPlayer1_Enter(System::Object^ sender, System::EventArgs^ e) {
}
};
}
|
[
"gloryseeker66@gmail.com"
] |
gloryseeker66@gmail.com
|
d095c26090762548dc580b650dc558094555da02
|
c41b487ea8a7452f9dffcff8e173d1b300cdc6e7
|
/pvr/channels/PVRChannelGroupInternal.cpp
|
e536bce3024df35a0e752aa24f8d9f1d23c6657a
|
[] |
no_license
|
PengWEI9/seebo
|
0ade683df5acee18c6458d7326b5a2b761cb9b0e
|
615caa9f9e625d7961bb4499061d64cec5299019
|
refs/heads/master
| 2020-06-18T07:38:48.104372
| 2016-11-30T09:24:47
| 2016-11-30T09:24:47
| 75,152,259
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,679
|
cpp
|
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "PVRChannelGroupInternal.h"
#include "guilib/GUIWindowManager.h"
#include "dialogs/GUIDialogYesNo.h"
#include "dialogs/GUIDialogOK.h"
#include "settings/AdvancedSettings.h"
#include "utils/log.h"
#include "PVRChannelGroupsContainer.h"
#include "pvr/PVRDatabase.h"
#include "pvr/PVRManager.h"
#include "epg/EpgContainer.h"
#include "pvr/timers/PVRTimers.h"
#include "pvr/addons/PVRClients.h"
using namespace PVR;
using namespace EPG;
using namespace std;
CPVRChannelGroupInternal::CPVRChannelGroupInternal(bool bRadio) :
CPVRChannelGroup(bRadio, bRadio ? XBMC_INTERNAL_GROUP_RADIO : XBMC_INTERNAL_GROUP_TV, g_localizeStrings.Get(bRadio ? 19216 : 19217))
{
m_iHiddenChannels = 0;
m_iGroupType = PVR_GROUP_TYPE_INTERNAL;
}
CPVRChannelGroupInternal::CPVRChannelGroupInternal(const CPVRChannelGroup &group) :
CPVRChannelGroup(group)
{
m_iHiddenChannels = group.GetNumHiddenChannels();
}
CPVRChannelGroupInternal::~CPVRChannelGroupInternal(void)
{
Unload();
g_PVRManager.UnregisterObserver(this);
}
bool CPVRChannelGroupInternal::Load(void)
{
if (CPVRChannelGroup::Load())
{
UpdateChannelPaths();
g_PVRManager.RegisterObserver(this);
return true;
}
CLog::Log(LOGERROR, "PVRChannelGroupInternal - %s - failed to load channels", __FUNCTION__);
return false;
}
void CPVRChannelGroupInternal::CheckGroupName(void)
{
CSingleLock lock(m_critSection);
/* check whether the group name is still correct, or channels will fail to load after the language setting changed */
CStdString strNewGroupName = g_localizeStrings.Get(m_bRadio ? 19216 : 19217);
if (!m_strGroupName.Equals(strNewGroupName))
{
SetGroupName(strNewGroupName, true);
UpdateChannelPaths();
}
}
void CPVRChannelGroupInternal::UpdateChannelPaths(void)
{
for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++)
{
PVRChannelGroupMember member = m_members.at(iChannelPtr);
member.channel->UpdatePath(this, iChannelPtr);
}
}
void CPVRChannelGroupInternal::UpdateFromClient(const CPVRChannel &channel, unsigned int iChannelNumber /* = 0 */)
{
CSingleLock lock(m_critSection);
CPVRChannelPtr realChannel = GetByClient(channel.UniqueID(), channel.ClientID());
if (realChannel)
{
realChannel->UpdateFromClient(channel);
}
else
{
PVRChannelGroupMember newMember = { CPVRChannelPtr(new CPVRChannel(channel)), iChannelNumber > 0l ? iChannelNumber : (int)m_members.size() + 1 };
m_members.push_back(newMember);
m_bChanged = true;
SortAndRenumber();
}
}
bool CPVRChannelGroupInternal::InsertInGroup(CPVRChannel &channel, int iChannelNumber /* = 0 */)
{
CSingleLock lock(m_critSection);
return CPVRChannelGroup::AddToGroup(channel, iChannelNumber);
}
bool CPVRChannelGroupInternal::Update(void)
{
CPVRChannelGroupInternal PVRChannels_tmp(m_bRadio);
PVRChannels_tmp.SetPreventSortAndRenumber();
return PVRChannels_tmp.LoadFromClients() && UpdateGroupEntries(PVRChannels_tmp);
}
bool CPVRChannelGroupInternal::AddToGroup(CPVRChannel &channel, int iChannelNumber /* = 0 */)
{
CSingleLock lock(m_critSection);
bool bReturn(false);
/* get the actual channel since this is called from a fileitemlist copy */
CPVRChannelPtr realChannel = GetByChannelID(channel.ChannelID());
if (!realChannel)
return bReturn;
/* switch the hidden flag */
if (realChannel->IsHidden())
{
realChannel->SetHidden(false);
m_iHiddenChannels--;
SortAndRenumber();
}
/* move this channel and persist */
bReturn = (iChannelNumber > 0l) ?
MoveChannel(realChannel->ChannelNumber(), iChannelNumber, true) :
MoveChannel(realChannel->ChannelNumber(), m_members.size() - m_iHiddenChannels, true);
if (m_bLoaded)
realChannel->Persist();
return bReturn;
}
bool CPVRChannelGroupInternal::RemoveFromGroup(const CPVRChannel &channel)
{
CSingleLock lock(m_critSection);
/* check if this channel is currently playing if we are hiding it */
CPVRChannelPtr currentChannel;
if (g_PVRManager.GetCurrentChannel(currentChannel) && *currentChannel == channel)
{
CGUIDialogOK::ShowAndGetInput(19098,19101,0,19102);
return false;
}
/* get the actual channel since this is called from a fileitemlist copy */
CPVRChannelPtr realChannel = GetByChannelID(channel.ChannelID());
if (!realChannel)
return false;
/* switch the hidden flag */
if (!realChannel->IsHidden())
{
realChannel->SetHidden(true);
++m_iHiddenChannels;
}
else
{
realChannel->SetHidden(false);
--m_iHiddenChannels;
}
/* renumber this list */
SortAndRenumber();
/* and persist */
return realChannel->Persist() &&
Persist();
}
bool CPVRChannelGroupInternal::MoveChannel(unsigned int iOldChannelNumber, unsigned int iNewChannelNumber, bool bSaveInDb /* = true */)
{
CSingleLock lock(m_critSection);
/* new channel number out of range */
if (iNewChannelNumber > m_members.size() - m_iHiddenChannels)
iNewChannelNumber = m_members.size() - m_iHiddenChannels;
return CPVRChannelGroup::MoveChannel(iOldChannelNumber, iNewChannelNumber, bSaveInDb);
}
int CPVRChannelGroupInternal::GetMembers(CFileItemList &results, bool bGroupMembers /* = true */) const
{
int iOrigSize = results.Size();
CSingleLock lock(m_critSection);
for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++)
{
CPVRChannelPtr channel = m_members.at(iChannelPtr).channel;
if (!channel)
continue;
if (bGroupMembers != channel->IsHidden())
{
CFileItemPtr pFileItem(new CFileItem(*channel));
results.Add(pFileItem);
}
}
return results.Size() - iOrigSize;
}
int CPVRChannelGroupInternal::LoadFromDb(bool bCompress /* = false */)
{
CPVRDatabase *database = GetPVRDatabase();
if (!database)
return -1;
int iChannelCount = Size();
if (database->Get(*this) > 0)
{
if (bCompress)
database->Compress(true);
}
else
{
CLog::Log(LOGINFO, "PVRChannelGroupInternal - %s - no channels in the database",
__FUNCTION__);
}
SortByChannelNumber();
return Size() - iChannelCount;
}
bool CPVRChannelGroupInternal::LoadFromClients(void)
{
/* get the channels from the backends */
return g_PVRClients->GetChannels(this) == PVR_ERROR_NO_ERROR;
}
bool CPVRChannelGroupInternal::Renumber(void)
{
CSingleLock lock(m_critSection);
bool bReturn(CPVRChannelGroup::Renumber());
m_iHiddenChannels = 0;
for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++)
{
if (m_members.at(iChannelPtr).channel->IsHidden())
m_iHiddenChannels++;
else
m_members.at(iChannelPtr).channel->UpdatePath(this, iChannelPtr);
}
return bReturn;
}
bool CPVRChannelGroupInternal::IsGroupMember(const CPVRChannel &channel) const
{
return !channel.IsHidden();
}
bool CPVRChannelGroupInternal::UpdateChannel(const CPVRChannel &channel)
{
CSingleLock lock(m_critSection);
CPVRChannelPtr updateChannel = GetByUniqueID(channel.UniqueID());
if (!updateChannel)
{
updateChannel = CPVRChannelPtr(new CPVRChannel(channel.IsRadio()));
PVRChannelGroupMember newMember = { updateChannel, 0 };
m_members.push_back(newMember);
updateChannel->SetUniqueID(channel.UniqueID());
}
updateChannel->UpdateFromClient(channel);
return updateChannel->Persist(!m_bLoaded);
}
bool CPVRChannelGroupInternal::AddAndUpdateChannels(const CPVRChannelGroup &channels, bool bUseBackendChannelNumbers)
{
bool bReturn(false);
SetPreventSortAndRenumber();
CSingleLock lock(m_critSection);
// BadJin 13/11/2015 /////////////////////////////////////////
// HPrasad - ECO - START
// 2016.01.26
// Bug :- iUniqueId and chName were statically allocated arrays of size 150. There can be segmentation faults for
// more that 150 channels loading.So PVR is going to halt
// Fix :- They are Dynamically allocated according to channel group size
unsigned int iChanGroupSize = channels.m_members.size();
unsigned int *iUniqueId = new unsigned int[iChanGroupSize];
CStdString *chName = new CStdString[iChanGroupSize];
// HPrasad - ECO - FINISH
for (unsigned int iChannelPtr = 0; iChannelPtr < iChanGroupSize; iChannelPtr++){
PVRChannelGroupMember member = channels.m_members.at(iChannelPtr);
if (!member.channel)
continue;
chName[iChannelPtr] = member.channel->ChannelName().c_str();
iUniqueId[iChannelPtr] = member.channel->UniqueID();
}
//////////////////////////////////////////////////////////////
/* go through the channel list and check for updated or new channels */
for (unsigned int iChannelPtr = 0; iChannelPtr < iChanGroupSize; iChannelPtr++)
{
PVRChannelGroupMember member = channels.m_members.at(iChannelPtr);
if (!member.channel)
continue;
/* check whether this channel is present in this container */
CPVRChannelPtr existingChannel = GetByClient(member.channel->UniqueID(), member.channel->ClientID());
if (existingChannel)
{
/* if it's present, update the current tag */
if (existingChannel->UpdateFromClient(*member.channel))
{
bReturn = true;
CLog::Log(LOGINFO,"PVRChannelGroupInternal - %s - updated %s channel '%s'", __FUNCTION__, m_bRadio ? "radio" : "TV", member.channel->ChannelName().c_str());
}
}
else
{
// BadJin 13/11/2015 /////////////////////////////////////////
bool bSkipFlag = false;
for (int i=0 ; i < iChannelPtr ; i++){
if (member.channel->ChannelName().c_str() == chName[i]){
if (member.channel->m_iUniqueId != iUniqueId[i]){
bSkipFlag = true;
}
}
}
if (!bSkipFlag){
UpdateFromClient(*member.channel, bUseBackendChannelNumbers ? member.channel->ClientChannelNumber() : 0);
bReturn = true;
CLog::Log(LOGINFO,"PVRChannelGroupInternal - %s - added %s channel '%s'", __FUNCTION__, m_bRadio ? "radio" : "TV", member.channel->ChannelName().c_str());
}
else{
CLog::Log(LOGINFO,"BJ(1) : skipped channel '%s'", member.channel->ChannelName().c_str());
}
//////////////////////////////////////////////////////////////
}
}
SetPreventSortAndRenumber(false);
if (m_bChanged)
SortAndRenumber();
// HPrasad - ECO - START
// 2016.01.26
delete[] iUniqueId;
delete[] chName;
// HPrasad - ECO - FINISH
return bReturn;
}
bool CPVRChannelGroupInternal::UpdateGroupEntries(const CPVRChannelGroup &channels)
{
bool bReturn(false);
if (CPVRChannelGroup::UpdateGroupEntries(channels))
{
/* try to find channel icons */
if (g_advancedSettings.m_bPVRChannelIconsAutoScan)
SearchAndSetChannelIcons();
g_PVRTimers->UpdateChannels();
Persist();
bReturn = true;
}
return bReturn;
}
void CPVRChannelGroupInternal::CreateChannelEpg(CPVRChannelPtr channel, bool bForce /* = false */)
{
if (!channel)
return;
CSingleLock lock(channel->m_critSection);
if (!channel->m_bEPGCreated || bForce)
{
CEpg *epg = g_EpgContainer.CreateChannelEpg(channel);
if (epg)
{
channel->m_bEPGCreated = true;
if (epg->EpgID() != channel->m_iEpgId)
{
channel->m_iEpgId = epg->EpgID();
channel->m_bChanged = true;
}
}
}
}
bool CPVRChannelGroupInternal::CreateChannelEpgs(bool bForce /* = false */)
{
if (!g_EpgContainer.IsStarted())
return false;
{
CSingleLock lock(m_critSection);
for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++)
CreateChannelEpg(m_members.at(iChannelPtr).channel);
}
if (HasChangedChannels())
{
g_EpgContainer.PersistTables();
return Persist();
}
return true;
}
void CPVRChannelGroupInternal::Notify(const Observable &obs, const ObservableMessage msg)
{
if (msg == ObservableMessageManagerStateChanged)
{
g_PVRManager.TriggerEpgsCreate();
}
}
|
[
"peng.wei8899@gmail.com"
] |
peng.wei8899@gmail.com
|
eaeeb17fa551a66474d234025e42e5b18aafd07b
|
f97babbde971815bcc118da750ad462726a87858
|
/fastText/src/loss.h
|
d20423b627d54046eb7c144027ca22077e77bee7
|
[
"MIT"
] |
permissive
|
key2long/HyperbolicEmbedding
|
925d4204f744ac2f6376edfdd26a30f685f69229
|
5eb05b7816b774be42e08004ce5b5ead14fe5650
|
refs/heads/master
| 2023-06-09T16:25:10.413547
| 2019-08-20T09:45:59
| 2019-08-20T09:45:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,728
|
h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include <random>
#include <vector>
#include "matrix.h"
#include "model.h"
#include "real.h"
#include "utils.h"
#include "vector.h"
namespace fasttext {
class Loss {
private:
void findKBest(
int32_t k,
real threshold,
Predictions& heap,
const Vector& output) const;
protected:
std::vector<real> t_sigmoid_;
std::vector<real> t_log_;
std::shared_ptr<Matrix>& wo_;
real log(real x) const;
real sigmoid(real x) const;
public:
explicit Loss(std::shared_ptr<Matrix>& wo);
virtual ~Loss() = default;
virtual real forward(
const std::vector<int32_t>& targets,
int32_t targetIndex,
Model::State& state,
real lr,
bool backprop) = 0;
virtual real forwardHyper(
Matrix & wi_,
int32_t inWordId,
int32_t outWordId,
Model::State& state,
real lr,
bool backprop) = 0;
virtual void computeOutput(Model::State& state) const = 0;
virtual void predict(
int32_t /*k*/,
real /*threshold*/,
Predictions& /*heap*/,
Model::State& /*state*/) const;
};
class UnitBiLogisticLoss: public Loss {
protected:
real unitBiLogistic(
int32_t target,
Model::State& state,
real uNorm,
bool labelIsPositive,
real lr,
bool backprop) const;
public:
explicit UnitBiLogisticLoss(std::shared_ptr<Matrix>& wo);
virtual ~UnitBiLogisticLoss() noexcept override = default;
void computeOutput(Model::State& state) const override;
};
class BinaryLogisticLoss : public Loss {
protected:
real binaryLogistic(
int32_t target,
Model::State& state,
bool labelIsPositive,
real lr,
bool backprop) const;
public:
explicit BinaryLogisticLoss(std::shared_ptr<Matrix>& wo);
virtual ~BinaryLogisticLoss() noexcept override = default;
void computeOutput(Model::State& state) const override;
};
class OneVsAllLoss : public BinaryLogisticLoss {
public:
explicit OneVsAllLoss(std::shared_ptr<Matrix>& wo);
~OneVsAllLoss() noexcept override = default;
real forward(
const std::vector<int32_t>& targets,
int32_t targetIndex,
Model::State& state,
real lr,
bool backprop) override;
};
class UnitNegativeSamplingLoss: public UnitBiLogisticLoss {
protected:
static const int32_t UNITNEGATIVE_TABLE_SIZE = 10000000;
int neg_;
std::vector<int32_t> negatives_;
std::uniform_int_distribution<size_t> uniform_;
int32_t getNegative(int32_t target, std::minstd_rand& rng);
int32_t getNegativeHyper(int32_t inputId, int32_t target, std::minstd_rand& rng);
public:
explicit UnitNegativeSamplingLoss(
std::shared_ptr<Matrix>& wo,
int neg,
const std::vector<int64_t>& targetCounts);
~UnitNegativeSamplingLoss() noexcept override = default;
// real lorentzProduct(Vector& x);
real forward(
const std::vector<int32_t>& targets,
int32_t targetIndex,
Model::State& state,
real lr,
bool backprop) override;
real forwardHyper(
Matrix & wi_,
int32_t inWordId,
int32_t outWordId,
Model::State& state,
real lr,
bool backprop) override;
};
class NegativeSamplingLoss : public BinaryLogisticLoss {
protected:
static const int32_t NEGATIVE_TABLE_SIZE = 10000000;
int neg_;
std::vector<int32_t> negatives_;
std::uniform_int_distribution<size_t> uniform_;
int32_t getNegative(int32_t target, std::minstd_rand& rng);
public:
explicit NegativeSamplingLoss(
std::shared_ptr<Matrix>& wo,
int neg,
const std::vector<int64_t>& targetCounts);
~NegativeSamplingLoss() noexcept override = default;
real forward(
const std::vector<int32_t>& targets,
int32_t targetIndex,
Model::State& state,
real lr,
bool backprop) override;
real forwardHyper(
Matrix & wi_,
int32_t inputId,
int32_t outWordId,
Model::State& state,
real lr,
bool backprop) override;
};
class HierarchicalSoftmaxLoss : public BinaryLogisticLoss {
protected:
struct Node {
int32_t parent;
int32_t left;
int32_t right;
int64_t count;
bool binary;
};
std::vector<std::vector<int32_t>> paths_;
std::vector<std::vector<bool>> codes_;
std::vector<Node> tree_;
int32_t osz_;
void buildTree(const std::vector<int64_t>& counts);
void dfs(
int32_t k,
real threshold,
int32_t node,
real score,
Predictions& heap,
const Vector& hidden) const;
public:
explicit HierarchicalSoftmaxLoss(
std::shared_ptr<Matrix>& wo,
const std::vector<int64_t>& counts);
~HierarchicalSoftmaxLoss() noexcept override = default;
real forward(
const std::vector<int32_t>& targets,
int32_t targetIndex,
Model::State& state,
real lr,
bool backprop) override;
void predict(
int32_t k,
real threshold,
Predictions& heap,
Model::State& state) const override;
};
class SoftmaxLoss : public Loss {
public:
explicit SoftmaxLoss(std::shared_ptr<Matrix>& wo);
~SoftmaxLoss() noexcept override = default;
real forward(
const std::vector<int32_t>& targets,
int32_t targetIndex,
Model::State& state,
real lr,
bool backprop) override;
void computeOutput(Model::State& state) const override;
};
} // namespace fasttext
|
[
"yaopeizhang1@yeah.net"
] |
yaopeizhang1@yeah.net
|
aaf31aa1fb9aefab2c2bfdada85afd1ca9f5b90d
|
be56db18beb96bb0584baa423caa8effabc28d03
|
/src/gpu/kernel_runner.cpp
|
0bb0345f2c6d7c9b8bf660809b092163bd030921
|
[
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
jingjing54007/clDNN
|
c09fa54de686a65e98396cc19751a4b629863c33
|
32b63d833ae078907b85343164708a541fe4d5a5
|
refs/heads/master
| 2020-03-14T23:31:47.650731
| 2018-04-09T02:36:31
| 2018-04-09T10:17:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,392
|
cpp
|
/*
// Copyright (c) 2016 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.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "kernel_runner.h"
#include "kernel.h"
#include <chrono>
namespace cldnn { namespace gpu {
kernel_runner::kernel_runner(engine_impl& engine_ref, bool weights_and_bias_exist) :
engine(&engine_ref),
weights_and_bias_exist(weights_and_bias_exist)
{
}
void kernel_runner::prepare_kernel_args(const KernelSelector::KernelsData& kernels_data, gpu::kernel::kernel_arguments_data& args)
{
const auto& base_params = *static_cast<KernelSelector::BaseParams*>(kernels_data[0].params.get());
// Prepare input buffers
if (input_buffers.empty())
{
for (const auto& input : base_params.inputs)
{
int num_of_input_elements = (int)input.PhysicalSize();
input_buffers.push_back(engine->allocate_memory({ from_data_type(input.GetDType()), format::bfyx, tensor(1, 1, num_of_input_elements, 1) }));
}
}
for (const auto& input : input_buffers)
{
args.inputs.push_back(input);
}
// Prepare output buffer
if (output_buffers.empty())
{
int num_of_output_elements = (int)base_params.output.PhysicalSize();
output_buffers.push_back(engine->allocate_memory({ from_data_type(base_params.output.GetDType()), format::bfyx, tensor(1, 1, num_of_output_elements, 1) }));
}
args.output = output_buffers[0];
if (weights_and_bias_exist)
{
// Prepare weight buffer
const auto& weights_bias_params = *static_cast<KernelSelector::WeightBiasParams*>(kernels_data[0].params.get());
int num_of_weight_elements = (int)weights_bias_params.weights.PhysicalSize();
if (weight_buffers.empty())
{
weight_buffers.push_back(engine->allocate_memory({ from_weights_type(weights_bias_params.weights.GetDType()), format::bfyx, tensor(1, 1, num_of_weight_elements, 1) }));
}
while (weight_buffers[0]->get_layout().bytes_count() < weights_bias_params.weights.PhysicalSizeInBytes())
{
// Weights layout depends on the kernel. Multiply the buffer size by 2 until it is big enough
// (to avoid complex computations of the exact buffer size according to the chosen layout).
weight_buffers.clear();
num_of_weight_elements *= 2;
weight_buffers.push_back(engine->allocate_memory({ from_weights_type(weights_bias_params.weights.GetDType()), format::bfyx, tensor(1, 1, num_of_weight_elements, 1) }));
}
args.weights = weight_buffers[0];
// Prepare bias buffer
if (!weights_bias_params.bias.empty())
{
if (bias_buffers.empty())
{
int num_of_bias_elements = (int)weights_bias_params.bias[0].PhysicalSize();
bias_buffers.push_back(engine->allocate_memory({ from_data_type(weights_bias_params.bias[0].GetDType()), format::bfyx, tensor(1, 1, num_of_bias_elements, 1) }));
}
args.bias = bias_buffers[0];
}
}
args.split = 0;
}
std::vector<uint64_t> kernel_runner::run_kernels(const KernelSelector::KernelsData& kernels_data)
{
auto context = engine->get_context();
std::vector<uint64_t> run_times;
int num_of_kernels_to_run = (int)kernels_data.size();
KernelSelector::KernelsData::const_iterator batch_start = kernels_data.begin();
KernelSelector::KernelsData::const_iterator batch_end;
while (num_of_kernels_to_run > 0)
{
int current_compilation_batch = std::min(num_of_kernels_to_run, compilation_batch_size);
batch_end = batch_start + current_compilation_batch;
std::vector<gpu::kernel> kernels;
for (auto it = batch_start; it < batch_end; it++)
{
kernels.push_back(kernel(context, it->kernels[0].kernelString, false, true));
}
gpu::kernel::kernel_arguments_data args;
prepare_kernel_args(kernels_data, args);
int i = 0;
for (auto it = batch_start; it < batch_end; it++)
{
std::vector<event_impl::ptr> events;
uint64_t kernel_run_time = 0;
int num_of_runs = 0;
for (int iteration = 0; iteration < runs_per_kernel; iteration++)
{
event_impl::ptr event;
try
{
event = kernels[i].run(it->kernels[0], {}, args);
}
catch (...)
{
// Could not run this kernel. Push back NULL event (will be ignored later).
}
events.push_back(event);
}
context->queue().finish();
for (auto& event : events)
{
if (event.get() != NULL)
{
auto profiling_intervals = event->get_profiling_info();
for (auto const& profiling_interval : profiling_intervals)
{
if (strcmp(profiling_interval.name, "executing") == 0)
{
kernel_run_time += profiling_interval.nanoseconds;
num_of_runs++;
break;
}
}
}
}
if (num_of_runs > 0)
{
run_times.push_back(kernel_run_time / num_of_runs);
}
else
{
run_times.push_back(std::numeric_limits<uint64_t>::max());
}
i++;
}
num_of_kernels_to_run -= current_compilation_batch;
batch_start += current_compilation_batch;
}
return run_times;
}
}}
|
[
"tomasz.poniecki@intel.com"
] |
tomasz.poniecki@intel.com
|
d3efc75cc1ff0484c8503a1b239dfe4baf0b914c
|
b3366048ca173c251028344fa69cf54c121a993b
|
/Neuron.cpp
|
af7ea210fc9a33e87be36df1e1c050b16df152d0
|
[] |
no_license
|
sanny1/Backpropagation
|
bc93c41165fd88ef36fa2c19cfed33d6ff3dc663
|
5ef33ea247f2a7807a0974c9659190ec98402698
|
refs/heads/master
| 2020-09-25T19:31:45.680812
| 2017-12-22T23:32:36
| 2017-12-22T23:32:36
| 66,761,695
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,824
|
cpp
|
//
// Created by Sanyog Chhetri on 18/12/15.
//
#include "Neuron.h"
#include <random>
using namespace Ann;
using namespace std;
Neuron::Neuron(int size, int Bias) : actual_output(1, 0), weight(size + 1, 0), input(size, 0),
hidden_e_gradient(size, 0)
{
default_random_engine generator(rand());
uniform_real_distribution<float> wei(-0.5,0.5);
for (int i = 0; i < (size + 1); i++)
{
weight.at(i) = wei(generator);
}
threshold = 0.7;
bias = Bias;//bais is what was needed to help me
learning_rate = 0.1;//0.3 seems to output the fastest in this set up
// learning rate changes the speed but comes at a price of
// missing the right value and might skip it
}
Neuron::~Neuron()
{
}
void Neuron::Set_input(vector<float> inputs)
{
input = inputs;
}
int Neuron::Get_Input_Size()
{
return input.size();
}
void Neuron::Activation_Func()
{
float sum = 0;
for (int i = 0; i < (input.size()); i++)//change this and the error gradient function for better
{
sum += (input.at(i) * weight.at(i+1));
// sum += bias*(weight.at(0));
}
sum += bias * weight.at(0);
actual_output.at(0) = (2 / (1 + exp(-sum)))-1;//haven't initialised however many outputs
// cout << " This is actual "
// << actual_output.at(0) << endl;
}
void Neuron::Error_Evalutation(int i)
{
error = desired_output.at(i) - actual_output.at(0);
error_gradient = (1 - (actual_output.at(0)*actual_output.at(0))) * error;
float sum = 0;
// for(int j = 0; j < input.size(); j++)
// {
// sum += weight.at(j)*error_gradient;
// }
// sum = sum/input.size();
for (int k = 0; k < input.size(); k++)
hidden_e_gradient.at(k) = (1 - (input.at(k)*input.at(k))) * weight.at(k + 1) * error_gradient;
// cout << " this is error " << error_gradient << endl;
}
// remember to implement momentum you need to add change in weigh member as well
// this is so you can store the weigh change and add it in the future iteration
void Neuron::Adjustment_Func()
{
fak_weig = weight;
for (int i = 0; i < weight.size(); i++)
{
if (i == 0)
{
weight.at(i) += learning_rate * bias * error_gradient;
}
else
{
fak_weig.at(i) = ((learning_rate * input.at(i-1) * error_gradient));
weight.at(i) += fak_weig.at(i);
}
}
}
vector<float> Neuron::Get_Weight()
{
return weight;
}
void Neuron::Set_Error_Gradient(float error_grad)
{
error_gradient = error_grad;
}
vector<float> Neuron::Get_Hidden_Grad()
{
return hidden_e_gradient;
}
void Neuron::Set_Desired_Output(vector<float> desired)
{
desired_output = desired;
}
float Neuron::Get_Actual_Output()
{
return actual_output.at(0);
}
float Neuron::Get_Error()
{
return error;
}
float Neuron::Get_Thres()
{
return threshold;
}
void Neuron::Set_pre_it(vector<float> pre)
{
pre_it = pre;
}
void Neuron::Set_weight(vector<float> weig)
{
weight = weig;
}
|
[
"Sanyog2.Chhetri@live.uwe.ac.uk"
] |
Sanyog2.Chhetri@live.uwe.ac.uk
|
cd39232ecebf8397db538ec966e604e4a475de04
|
c32ee8ade268240a8064e9b8efdbebfbaa46ddfa
|
/Libraries/m2sdk/C_Traffic_Subdiv_Evaluator.h
|
03efa6712782e19ed5954071bd7c159b2cef376c
|
[] |
no_license
|
hopk1nz/maf2mp
|
6f65bd4f8114fdeb42f9407a4d158ad97f8d1789
|
814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8
|
refs/heads/master
| 2021-03-12T23:56:24.336057
| 2015-08-22T13:53:10
| 2015-08-22T13:53:10
| 41,209,355
| 19
| 21
| null | 2015-08-31T05:28:13
| 2015-08-22T13:56:04
|
C++
|
UTF-8
|
C++
| false
| false
| 230
|
h
|
// auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <I_TrafficEvaluator.h>
/** C_Traffic_Subdiv_Evaluator (VTable=0xFFFFFFFF) */
class C_Traffic_Subdiv_Evaluator : public I_TrafficEvaluator
{
public:
};
|
[
"hopk1nz@gmail.com"
] |
hopk1nz@gmail.com
|
485de1992d09f2ed397435ff6dea04d61b1645e6
|
08613205986ad9671c661f0d8e2668df4c24c91c
|
/Aliza_Naqvi_zz/serialComm/serialComm.ino
|
542ab0ca613d6cd7b474d9f448681d8d0c86233e
|
[] |
no_license
|
zhenzhenqi/baruchPresentation
|
3570008e50de4cb9b973335a4efd46d38f8a140a
|
92cbe580c08fb916d84f281459ba5e0e09f02246
|
refs/heads/master
| 2021-06-25T03:15:15.174942
| 2017-09-13T02:32:23
| 2017-09-13T02:32:23
| 103,343,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 419
|
ino
|
const int SENSOR_PIN = 0; // Analog input pin
void setup()
{
Serial.begin(9600);
// No need for any code here
// analogWrite() sets up the pins as outputs
}
void loop()
{
int sensorValue;
//
// // Read the voltage from the softpot (0-1023)
//
sensorValue = analogRead(A0);
Serial.write(map(sensorValue,0,1024,255,0));
// Serial.write(map(sensorValue, 0, 1024, 255, 0));
delay(100);
}
|
[
"jane363636@gmail.com"
] |
jane363636@gmail.com
|
5dfd7789707632222e997ab1d27a8bebb4f2219d
|
e9ac38a3c8e09ec3b5050fb8d60b695f592f0cca
|
/src/base/buffer.cpp
|
aa91df2bbbac9adb5ba71ea9252102e4773bd5cd
|
[] |
no_license
|
AnaBit/cobweb
|
54572bdd116d8ceb71eba9e6ac81b88304dc0957
|
4288898f542176684d1ee347277375768dc6b274
|
refs/heads/master
| 2016-09-01T13:21:34.329864
| 2016-04-12T10:53:13
| 2016-04-12T10:53:13
| 54,700,752
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,238
|
cpp
|
#include "buffer.hpp"
namespace cobweb {
namespace base {
atom_buffer::buffer_data atom_buffer::conv_data(std::vector<unsigned char> & data)
{
buffer_data buf(data);
return buf;
}
atom_buffer::buffer_data atom_buffer::conv_data(std::vector<unsigned char> && data)
{
buffer_data buf(data);
return buf;
}
atom_buffer::atom_buffer()
{
}
atom_buffer::~atom_buffer()
{
}
void atom_buffer::push_back(atom_buffer::buffer_data & data)
{
wait();
_buffer.push_back(data);
leave();
}
void atom_buffer::push_back(atom_buffer::buffer_data && data)
{
wait();
_buffer.push_back(data);
leave();
}
atom_buffer::buffer_data atom_buffer::front()
{
wait();
buffer_data buf = _buffer.front();
leave();
return buf;
}
atom_buffer::buffer_data atom_buffer::pop_front()
{
wait();
buffer_data buf = _buffer.front();
_buffer.pop_front();
leave();
return buf;
}
void atom_buffer::clear()
{
wait();
_buffer.clear();
leave();
}
size_t atom_buffer::size()
{
wait();
size_t size = _buffer.size();
leave();
return size;
}
void atom_buffer::wait()
{
while (_flag_buffer.test_and_set());
}
void atom_buffer::leave()
{
_flag_buffer.clear();
}
}
}
|
[
"AnaBitIO@hotmail.com"
] |
AnaBitIO@hotmail.com
|
fbea2b8a5a02bc3c189b4feb934383072e7e9507
|
889626966d3f108522c753db83a1a23318d4d6fd
|
/src/governance-object.h
|
149c20758d17543c584e7f2aae0b1a798b0f93e3
|
[
"MIT"
] |
permissive
|
safepeofficial/safepeofficial
|
5a14d0aeaa140c52d3d96f3e7bb892cd28e143c0
|
aca67695fedfabbdd6dc512358fee54fefc912de
|
refs/heads/master
| 2023-06-23T08:00:42.237747
| 2021-07-22T14:06:58
| 2021-07-22T14:06:58
| 386,934,834
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,097
|
h
|
// Copyright (c) 2014-2019 The Dash Core developers
// Copyright (c) 2021 The SafePe Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GOVERNANCE_OBJECT_H
#define GOVERNANCE_OBJECT_H
#include "cachemultimap.h"
#include "governance-exceptions.h"
#include "governance-vote.h"
#include "governance-votedb.h"
#include "key.h"
#include "net.h"
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"
#include "bls/bls.h"
#include <univalue.h>
class CGovernanceManager;
class CGovernanceTriggerManager;
class CGovernanceObject;
class CGovernanceVote;
static const int MIN_GOVERNANCE_PEER_PROTO_VERSION = 70213;
static const int GOVERNANCE_FILTER_PROTO_VERSION = 70206;
static const int GOVERNANCE_POSE_BANNED_VOTES_VERSION = 70215;
static const double GOVERNANCE_FILTER_FP_RATE = 0.001;
static const int GOVERNANCE_OBJECT_UNKNOWN = 0;
static const int GOVERNANCE_OBJECT_PROPOSAL = 1;
static const int GOVERNANCE_OBJECT_TRIGGER = 2;
static const CAmount GOVERNANCE_PROPOSAL_FEE_TX = (5.0 * COIN);
static const int64_t GOVERNANCE_FEE_CONFIRMATIONS = 6;
static const int64_t GOVERNANCE_MIN_RELAY_FEE_CONFIRMATIONS = 1;
static const int64_t GOVERNANCE_UPDATE_MIN = 60 * 60;
static const int64_t GOVERNANCE_DELETION_DELAY = 10 * 60;
static const int64_t GOVERNANCE_ORPHAN_EXPIRATION_TIME = 10 * 60;
// FOR SEEN MAP ARRAYS - GOVERNANCE OBJECTS AND VOTES
static const int SEEN_OBJECT_IS_VALID = 0;
static const int SEEN_OBJECT_ERROR_INVALID = 1;
static const int SEEN_OBJECT_ERROR_IMMATURE = 2;
static const int SEEN_OBJECT_EXECUTED = 3; //used for triggers
static const int SEEN_OBJECT_UNKNOWN = 4; // the default
typedef std::pair<CGovernanceVote, int64_t> vote_time_pair_t;
inline bool operator<(const vote_time_pair_t& p1, const vote_time_pair_t& p2)
{
return (p1.first < p2.first);
}
struct vote_instance_t {
vote_outcome_enum_t eOutcome;
int64_t nTime;
int64_t nCreationTime;
vote_instance_t(vote_outcome_enum_t eOutcomeIn = VOTE_OUTCOME_NONE, int64_t nTimeIn = 0, int64_t nCreationTimeIn = 0) :
eOutcome(eOutcomeIn),
nTime(nTimeIn),
nCreationTime(nCreationTimeIn)
{
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
int nOutcome = int(eOutcome);
READWRITE(nOutcome);
READWRITE(nTime);
READWRITE(nCreationTime);
if (ser_action.ForRead()) {
eOutcome = vote_outcome_enum_t(nOutcome);
}
}
};
typedef std::map<int, vote_instance_t> vote_instance_m_t;
typedef vote_instance_m_t::iterator vote_instance_m_it;
typedef vote_instance_m_t::const_iterator vote_instance_m_cit;
struct vote_rec_t {
vote_instance_m_t mapInstances;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(mapInstances);
}
};
/**
* Governance Object
*
*/
class CGovernanceObject
{
friend class CGovernanceManager;
friend class CGovernanceTriggerManager;
friend class CSuperblock;
public: // Types
typedef std::map<COutPoint, vote_rec_t> vote_m_t;
typedef vote_m_t::iterator vote_m_it;
typedef vote_m_t::const_iterator vote_m_cit;
typedef CacheMultiMap<COutPoint, vote_time_pair_t> vote_cmm_t;
private:
/// critical section to protect the inner data structures
mutable CCriticalSection cs;
/// Object typecode
int nObjectType;
/// parent object, 0 is root
uint256 nHashParent;
/// object revision in the system
int nRevision;
/// time this object was created
int64_t nTime;
/// time this object was marked for deletion
int64_t nDeletionTime;
/// fee-tx
uint256 nCollateralHash;
/// Data field - can be used for anything
std::vector<unsigned char> vchData;
/// Masternode info for signed objects
COutPoint masternodeOutpoint;
std::vector<unsigned char> vchSig;
/// is valid by blockchain
bool fCachedLocalValidity;
std::string strLocalValidityError;
// VARIOUS FLAGS FOR OBJECT / SET VIA MASTERNODE VOTING
/// true == minimum network support has been reached for this object to be funded (doesn't mean it will for sure though)
bool fCachedFunding;
/// true == minimum network has been reached flagging this object as a valid and understood governance object (e.g, the serialized data is correct format, etc)
bool fCachedValid;
/// true == minimum network support has been reached saying this object should be deleted from the system entirely
bool fCachedDelete;
/** true == minimum network support has been reached flagging this object as endorsed by an elected representative body
* (e.g. business review board / technecial review board /etc)
*/
bool fCachedEndorsed;
/// object was updated and cached values should be updated soon
bool fDirtyCache;
/// Object is no longer of interest
bool fExpired;
/// Failed to parse object data
bool fUnparsable;
vote_m_t mapCurrentMNVotes;
/// Limited map of votes orphaned by MN
vote_cmm_t cmmapOrphanVotes;
CGovernanceObjectVoteFile fileVotes;
public:
CGovernanceObject();
CGovernanceObject(const uint256& nHashParentIn, int nRevisionIn, int64_t nTime, const uint256& nCollateralHashIn, const std::string& strDataHexIn);
CGovernanceObject(const CGovernanceObject& other);
// Public Getter methods
int64_t GetCreationTime() const
{
return nTime;
}
int64_t GetDeletionTime() const
{
return nDeletionTime;
}
int GetObjectType() const
{
return nObjectType;
}
const uint256& GetCollateralHash() const
{
return nCollateralHash;
}
const COutPoint& GetMasternodeOutpoint() const
{
return masternodeOutpoint;
}
bool IsSetCachedFunding() const
{
return fCachedFunding;
}
bool IsSetCachedValid() const
{
return fCachedValid;
}
bool IsSetCachedDelete() const
{
return fCachedDelete;
}
bool IsSetCachedEndorsed() const
{
return fCachedEndorsed;
}
bool IsSetDirtyCache() const
{
return fDirtyCache;
}
bool IsSetExpired() const
{
return fExpired;
}
const CGovernanceObjectVoteFile& GetVoteFile() const
{
return fileVotes;
}
// Signature related functions
void SetMasternodeOutpoint(const COutPoint& outpoint);
bool Sign(const CBLSSecretKey& key);
bool CheckSignature(const CBLSPublicKey& pubKey) const;
std::string GetSignatureMessage() const;
uint256 GetSignatureHash() const;
// CORE OBJECT FUNCTIONS
bool IsValidLocally(std::string& strError, bool fCheckCollateral) const;
bool IsValidLocally(std::string& strError, bool& fMissingMasternode, bool& fMissingConfirmations, bool fCheckCollateral) const;
/// Check the collateral transaction for the budget proposal/finalized budget
bool IsCollateralValid(std::string& strError, bool& fMissingConfirmations) const;
void UpdateLocalValidity();
void UpdateSentinelVariables();
CAmount GetMinCollateralFee() const;
UniValue GetJSONObject();
void Relay(CConnman& connman);
uint256 GetHash() const;
// GET VOTE COUNT FOR SIGNAL
int CountMatchingVotes(vote_signal_enum_t eVoteSignalIn, vote_outcome_enum_t eVoteOutcomeIn) const;
int GetAbsoluteYesCount(vote_signal_enum_t eVoteSignalIn) const;
int GetAbsoluteNoCount(vote_signal_enum_t eVoteSignalIn) const;
int GetYesCount(vote_signal_enum_t eVoteSignalIn) const;
int GetNoCount(vote_signal_enum_t eVoteSignalIn) const;
int GetAbstainCount(vote_signal_enum_t eVoteSignalIn) const;
bool GetCurrentMNVotes(const COutPoint& mnCollateralOutpoint, vote_rec_t& voteRecord) const;
// FUNCTIONS FOR DEALING WITH DATA STRING
std::string GetDataAsHexString() const;
std::string GetDataAsPlainString() const;
// SERIALIZER
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
// SERIALIZE DATA FOR SAVING/LOADING OR NETWORK FUNCTIONS
READWRITE(nHashParent);
READWRITE(nRevision);
READWRITE(nTime);
READWRITE(nCollateralHash);
READWRITE(vchData);
READWRITE(nObjectType);
READWRITE(masternodeOutpoint);
if (!(s.GetType() & SER_GETHASH)) {
READWRITE(vchSig);
}
if (s.GetType() & SER_DISK) {
// Only include these for the disk file format
LogPrint("gobject", "CGovernanceObject::SerializationOp Reading/writing votes from/to disk\n");
READWRITE(nDeletionTime);
READWRITE(fExpired);
READWRITE(mapCurrentMNVotes);
READWRITE(fileVotes);
LogPrint("gobject", "CGovernanceObject::SerializationOp hash = %s, vote count = %d\n", GetHash().ToString(), fileVotes.GetVoteCount());
}
// AFTER DESERIALIZATION OCCURS, CACHED VARIABLES MUST BE CALCULATED MANUALLY
}
private:
// FUNCTIONS FOR DEALING WITH DATA STRING
void LoadData();
void GetData(UniValue& objResult);
bool ProcessVote(CNode* pfrom,
const CGovernanceVote& vote,
CGovernanceException& exception,
CConnman& connman);
/// Called when MN's which have voted on this object have been removed
void ClearMasternodeVotes();
// Revalidate all votes from this MN and delete them if validation fails.
// This is the case for DIP3 MNs that changed voting or operator keys and
// also for MNs that were removed from the list completely.
// Returns deleted vote hashes.
std::set<uint256> RemoveInvalidVotes(const COutPoint& mnOutpoint);
void CheckOrphanVotes(CConnman& connman);
};
#endif
|
[
"dev.vanshtah@gmail.com"
] |
dev.vanshtah@gmail.com
|
8b22858c0fb6b21e108253672b59baf2c4fdc6cd
|
50bdaa2e71aae37240c61c930decbfe9d1e504b8
|
/harp-daal-app/daal-src/include/algorithms/neural_networks/layers/loss/softmax_cross_layer_types.h
|
f034df3012b3a8b227a4b370b77cd8f23f38fc61
|
[
"Apache-2.0"
] |
permissive
|
prawalgangwar/harp
|
010b1f669ee54941365ba1204be4e1484c15f108
|
3c3a3bf2d519f76ccf8ae17d8b3681e0a93048b7
|
refs/heads/master
| 2020-09-13T19:57:54.274328
| 2017-06-20T00:03:57
| 2017-06-20T00:03:57
| 94,464,682
| 0
| 0
| null | 2017-06-15T17:49:16
| 2017-06-15T17:49:16
| null |
UTF-8
|
C++
| false
| false
| 3,460
|
h
|
/* file: softmax_cross_layer_types.h */
/*******************************************************************************
* Copyright 2014-2016 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.
*******************************************************************************/
/*
//++
// Implementation of the softmax cross-entropy layer types.
//--
*/
#ifndef __NEURAL_NENTWORK_LOSS_SOFTMAX_CROSS_LAYER_TYPES_H__
#define __NEURAL_NENTWORK_LOSS_SOFTMAX_CROSS_LAYER_TYPES_H__
#include "algorithms/algorithm.h"
#include "data_management/data/tensor.h"
#include "data_management/data/homogen_tensor.h"
#include "services/daal_defines.h"
#include "algorithms/neural_networks/layers/layer_types.h"
namespace daal
{
namespace algorithms
{
namespace neural_networks
{
namespace layers
{
namespace loss
{
/**
* @defgroup softmax_cross Softmax Cross-entropy Layer
* \copydoc daal::algorithms::neural_networks::layers::loss::softmax_cross
* @ingroup loss
* @{
*/
namespace softmax_cross
{
/**
* <a name="DAAL-ENUM-ALGORITHMS__NEURAL_NETWORKS__LAYERS__LOSS__SOFTMAX_CROSS__METHOD"></a>
* \brief Computation methods for the softmax cross-entropy layer
*/
enum Method
{
defaultDense = 0, /*!< Default: performance-oriented method */
};
/**
* <a name="DAAL-ENUM-ALGORITHMS__NEURAL_NETWORKS__LAYERS__LOSS__SOFTMAX_CROSS__LAYERDATAID"></a>
* \brief Identifiers of input objects for the backward softmax cross-entropy layer and results for the forward softmax cross-entropy layer
*/
enum LayerDataId
{
auxProbabilities = 2, /*!< Tensor that stores probabilities for the forward softmax cross-entropy layer */
auxGroundTruth = 3, /*!< Tensor that stores ground truth data for the forward softmax cross-entropy layer */
};
/**
* \brief Contains version 1.0 of Intel(R) Data Analytics Acceleration Library (Intel(R) DAAL) interface.
*/
namespace interface1
{
/**
* <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__LOSS__SOFTMAX_CROSS__PARAMETER"></a>
* \brief Parameters for the softmax cross-entropy layer
*
* \snippet neural_networks/layers/loss/softmax_cross_layer_types.h Parameter source code
*/
/* [Parameter source code] */
class Parameter: public layers::Parameter
{
public:
/**
* Constructs parameters of the softmax cross-entropy layer
* \param[in] accuracyThreshold_ Value needed to avoid degenerate cases in logarithm computing
*/
Parameter(const double accuracyThreshold_ = 1.0e-04) : accuracyThreshold(accuracyThreshold_)
{};
double accuracyThreshold; /*!< Value needed to avoid degenerate cases in logarithm computing */
/**
* Checks the correctness of the parameter
*/
virtual void check() const
{}
};
/* [Parameter source code] */
} // namespace interface1
using interface1::Parameter;
} // namespace softmax_cross
/** @} */
} // namespace loss
} // namespace layers
} // namespace neural_networks
} // namespace algorithm
} // namespace daal
#endif
|
[
"lc37@156-56-102-164.dhcp-bl.indiana.edu"
] |
lc37@156-56-102-164.dhcp-bl.indiana.edu
|
87a339c2edb699ac2cd0f0f1c4c8fa2b62cbd06d
|
07834560a94f1617df35b057a26c3976e0e4f519
|
/VC2013_AES_Security/AES_Security/Function/FileManager.h
|
d7121e65b036b0d1e9de7ec107b987d382ee4a46
|
[] |
no_license
|
liqing90/VC_Test_S_3
|
8d4a07988663251e2cb2b09e49414c82743b694f
|
75e6cfbfc54129b4e43bab677bba7f27f217ab59
|
refs/heads/master
| 2021-03-25T09:50:26.819830
| 2018-02-28T08:24:34
| 2018-02-28T08:24:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,313
|
h
|
// FileManager.h: interface for the CFileManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_FILEMANAGER_H__A9E277BD_2182_44DA_B68A_EE1CBAB6E67F__INCLUDED_)
#define AFX_FILEMANAGER_H__A9E277BD_2182_44DA_B68A_EE1CBAB6E67F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//--------------------------------------------------------------------------------------------------
#include <vector>
#include <string>
//--------------------------------------------------------------------------------------------------
namespace std {
#if defined (_UNICODE) || defined(UNICODE)
typedef wstring tstring;
#else
typedef string tstring;
#endif
}
using namespace std;
//--------------------------------------------------------------------------------------------------
class CFileManager
{
public:
CFileManager();
virtual ~CFileManager();
// ini
int ReadIniFile(IN TCHAR *pszIniFileName, IN TCHAR *pszSectionName, IN TCHAR *pszKeyName, OUT TCHAR *pszBuffer, IN DWORD dwBufferLen);
int WriteIniFile(IN TCHAR *pszIniFileName, IN TCHAR *pszSectionName, IN TCHAR *pszKeyName, IN TCHAR *pszBuffer);
// file
int GetCurrentExeFilePath(OUT TCHAR *pszBuffer, IN DWORD dwBufferLen);
int GetFileSize(IN TCHAR *pszFullFileName, OUT DWORD64 *pdw64FileSize); // output pdw64FileSize unit: Bytes
int RenameFileName(IN TCHAR *pszOldName, IN TCHAR *pszNewFileName);
void ParseFullFileName(IN TCHAR *pszFullFileName, OUT TCHAR *pszDrive, OUT TCHAR *pszDir, OUT TCHAR *pszFileName, OUT TCHAR *pszExtension);
BOOL IsFileExist(IN TCHAR *pszPath);
BOOL IsFolderExist(IN TCHAR *pszPath);
int DumpBinaryDataToFile(IN TCHAR *szTargetFile, IN void *pDataBuffer, IN DWORD dwDataSize);
int GetFileLastWriteTime(IN TCHAR *pszFileFullPathName, OUT SYSTEMTIME *pSystemTime);
// folder
int BuildDirectory(IN TCHAR *ADir);
int DeleteDirectory(IN TCHAR *pszDirPath);
int FindFileFromFolder(IN TCHAR *pszFolder, IN TCHAR *pszExtNameFilter, OUT std::vector<tstring> *pFullFileName);
// string
int UnicodeStrToAnsiStr(IN WCHAR *pszUnicode, OUT char *pszAnsi);
int AnsiStrToUnicodeStr(IN char *pszAnsi, OUT WCHAR *pszUnicode);
};
#endif // !defined(AFX_FILEMANAGER_H__A9E277BD_2182_44DA_B68A_EE1CBAB6E67F__INCLUDED_)
|
[
"rex721101@google.com.tw"
] |
rex721101@google.com.tw
|
67332bc032c936ceec98e18ad0fd3fbfb27f9caa
|
6b3e19170e2bfe62a57656a5836bd64b946366bf
|
/W6/G1/D2/358.cpp
|
02d5907a6de6b62f06390d153035b928fc8f1135
|
[] |
no_license
|
Beisenbek/PP1_2018R
|
299da157ec370bd4d4ff7fff3f1722505a95dee4
|
2f5d0a94dc4193ca648655168d4decbfacd6f92e
|
refs/heads/master
| 2021-05-12T01:11:11.694365
| 2018-04-16T13:53:38
| 2018-04-16T13:53:38
| 117,552,376
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 641
|
cpp
|
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <ctype.h>
using namespace std;
int main(){
freopen("input.txt","r",stdin);
int n,m;
cin >> n >> m;
int a[n][m];
int s[n];
for(int i = 0; i < n; ++i){
s[i] = 0;
for(int j = 0; j < m; ++j){
cin >> a[i][j];
s[i] = s[i] + a[i][j];
}
}
int bestI = 0;
int bestJ = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
if(a[bestI][bestJ] < a[i][j]){
bestI = i;
bestJ = j;
}else if(a[bestI][bestJ] == a[i][j] && s[bestI] < s[i]){
bestI = i;
bestJ = j;
}
}
}
cout << bestI << endl;
return 0;
}
|
[
"beysenbek@gmail.com"
] |
beysenbek@gmail.com
|
576c9dfb33579334eca1f1f94a57194f5299c29d
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5706278382862336_1/C++/Mejor/A.cpp
|
0e9a1cfcd02d12e7ec8e7fa0777298d61f2fbd6b
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,071
|
cpp
|
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <limits>
#include <string>
#include <queue>
#include <cstdio>
using namespace std;
long long gcd(long long a, long long b){
while (b!=0){
//fout<<a<<" "<<b<<endl;
long long temp=a;
a=b;
b=temp%b;
}
// fout<<a<<" "<<b<<endl;
return a;
}
bool verf (long long a){
while (a!=1){
if (a%2==1) return false;
a/=2;
}
return true;
}
int main (){
ifstream fin("A-large.in");
ofstream fout("A-large.out");
int cpt; fin>>cpt;
for (int k=1;k<=cpt;++k){
long long p,q,d,ans=0;
char c;
bool stop=false;
fin>>p>>c>>q;
do {
d=gcd(q,p);
p=p/d,q=q/d;
if (!verf(q)) stop=true;
else p*=2,ans++;
} while (p<q && !stop);
if (ans>40) stop=true;
if (stop) fout<<"Case #"<<k<<": impossible"<<endl;
else fout<<"Case #"<<k<<": "<<ans<<endl;
}
return 0;
}
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
d0aca4879164840117fda1f44f02a67d20f97900
|
fa683fdb9a812992e2069e1ce85270746f3575fc
|
/src/ui/sprite.cpp
|
2080d21dea3905af95038bdec5d5f02b58594d03
|
[
"Apache-2.0"
] |
permissive
|
kevinfyc/KGE
|
da2021682eec72188db4b1de24f019e915867143
|
3b3d805317765c1c67f7584f8c1eee6e7c94c3a3
|
refs/heads/master
| 2021-07-14T11:31:06.296883
| 2017-10-18T03:08:13
| 2017-10-18T03:08:13
| 104,315,430
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 391
|
cpp
|
//
// sprite.cpp
// libkge
//
// Created by kevin on 17-10-10.
//
//
//
#include "sprite.h"
namespace kge
{
Ref<Sprite> Sprite::Create(const Rect& rect, const Vector4& border)
{
Ref<Sprite> sprite;
sprite = Ref<Sprite>(new Sprite());
sprite->_rect = rect;
sprite->_border = border;
return sprite;
}
Sprite::Sprite():
_rect(0, 0, 1, 1),
_border(0, 0, 0, 0)
{
}
}
|
[
"kevin"
] |
kevin
|
d0c7133b06aa53eb9c73eb9d686f83e730b10e2e
|
bdc6119c5910093d2417830e15f2389a7e5e74b7
|
/sols/s-topcoder/tree_weighting.cpp
|
d2afad291ad51faae1f3b97b38f77a241579a952
|
[] |
no_license
|
danscu/onlinejudge
|
0d10d4902cb152dd6401d3624ebb7bc6c44bba38
|
a981794d868dd8366d8f50931f10704066fbab96
|
refs/heads/master
| 2021-01-15T15:33:47.893332
| 2016-08-31T00:50:50
| 2016-08-31T00:50:58
| 17,789,216
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,693
|
cpp
|
#include <cstdio>
#include <iostream>
#include <list>
#include <set>
using namespace std;
#define DBG 1
#if DBG
#define D(x) x;
#else
#define D(x)
#endif
#define REP(v,n) for(int v=0;v<n;v++)
#define every(iter, iterable) \
typeof((iterable).begin()) iter = (iterable).begin(); iter != (iterable).end(); iter++
typedef long long Num;
const int maxn = 100005;
const int mod = 1000000007;
int N;
Num grandSum;
struct Node {
#if DBG
int idx;
#endif
int degrees;
list<pair<Node*,Num> > edges; // target, weight
Num wts;
Node() {
wts = 1;
}
void removeEdge(Node *tgt) {
for (every(it, edges))
if (it->first == tgt) {
edges.erase(it);
break;
}
}
void clear() {
edges.clear();
degrees = 0;
wts = 1;
}
Num multiply(Num wt, Node *c) {
Num nodeSum = wts * wt % mod * c->wts % mod;
#if DBG
Num oldWts = wts;
#endif
wts = (wts + c->wts * wt % mod) % mod;
#if DBG
printf("path sum = %ld (node %d) * %ld (wt) * %ld (node %d) = %ld, ", oldWts, idx+1, wt, c->wts, c->idx+1, nodeSum);
printf("Node %d new weight = %ld + %ld * %ld = %ld, ", idx + 1, oldWts, c->wts, wt, wts);
#endif
removeEdge(c);
return nodeSum;
}
};
struct NodeComp {
bool operator()(const Node *lhs, const Node *rhs) {
return lhs->degrees < rhs->degrees ||
(lhs->degrees == rhs->degrees && lhs < rhs);
}
} nodeComp;
multiset<Node*,NodeComp> que;
Node nodes[maxn];
Num solve() {
// push all to priority_q
multiset<Node*,NodeComp>::iterator it = que.begin();
REP(i, N) {
if (nodes[i].degrees)
it = que.insert(it, &nodes[i]);
}
grandSum = 0;
while (que.size() > 1) {
Node *cur = *que.begin();
que.erase(cur);
for (every(it, cur->edges)) {
Node *tgt = it->first;
Num wt = it->second;
// cumulate path weights
#if DBG
printf("Merge Node %d into Node %d: ", cur->idx + 1, tgt->idx + 1);
int oldGS = grandSum;
#endif
Num nodeSum = tgt->multiply(wt, cur);
grandSum = (grandSum + nodeSum) % mod;
#if DBG
printf("Grand sum = %ld + %ld = %ld\n", oldGS, nodeSum, grandSum);
#endif
que.erase(tgt);
tgt->degrees--;
que.insert(tgt);
}
}
// clean-up
que.clear();
REP(i,N)
nodes[i].clear();
return grandSum;
}
int getnum() {
char cc;
int dd;
while (cc = getchar(), (cc<'0'||cc>'9'));
dd=cc=='-'?0:cc-'0';
while (cc = getchar(), cc>='0'&&cc<='9')
dd = dd*10+cc-'0';
return dd;
}
int main() {
int T;
#if BENCH
freopen("tree_weighting.txt","r",stdin);
#endif
T = getnum();
for (int tc = 0; tc < T; tc++) {
N = getnum();
#if DBG
REP(i,N) nodes[i].idx = i;
#endif
for (int i = 0; i < N - 1; i++) {
int a, b, w;
a = getnum(), b = getnum(), w = getnum();
a--; b--;
nodes[a].degrees++; nodes[b].degrees++;
nodes[a].edges.push_back(make_pair(&nodes[b],w));
nodes[b].edges.push_back(make_pair(&nodes[a],w));
}
printf("%ld\n", solve());
}
return 0;
}
/*
Merge Node 1 into Node 6: path sum = 1 (node 6) * 5 (wt) * 1 (node 1) = 5, Node 6 new weight = 1 + 1 * 5 = 6, Grand sum = 0 + 5 = 5
Merge Node 4 into Node 6: path sum = 6 (node 6) * 2 (wt) * 1 (node 4) = 12, Node 6 new weight = 6 + 1 * 2 = 8, Grand sum = 5 + 12 = 17
Merge Node 7 into Node 3: path sum = 1 (node 3) * 4 (wt) * 1 (node 7) = 4, Node 3 new weight = 1 + 1 * 4 = 5, Grand sum = 17 + 4 = 21
Merge Node 8 into Node 6: path sum = 8 (node 6) * 5 (wt) * 1 (node 8) = 40, Node 6 new weight = 8 + 1 * 5 = 13, Grand sum = 21 + 40 = 61
Merge Node 9 into Node 6: path sum = 13 (node 6) * 2 (wt) * 1 (node 9) = 26, Node 6 new weight = 13 + 1 * 2 = 15, Grand sum = 61 + 26 = 87
Merge Node 11 into Node 6: path sum = 15 (node 6) * 3 (wt) * 1 (node 11) = 45, Node 6 new weight = 15 + 1 * 3 = 18, Grand sum = 87 + 45 = 132
Merge Node 12 into Node 10: path sum = 1 (node 10) * 3 (wt) * 1 (node 12) = 3, Node 10 new weight = 1 + 1 * 3 = 4, Grand sum = 132 + 3 = 135
Merge Node 10 into Node 14: path sum = 1 (node 14) * 4 (wt) * 4 (node 10) = 16, Node 14 new weight = 1 + 4 * 4 = 17, Grand sum = 135 + 16 = 151
Merge Node 13 into Node 6: path sum = 18 (node 6) * 5 (wt) * 1 (node 13) = 90, Node 6 new weight = 18 + 1 * 5 = 23, Grand sum = 151 + 90 = 241
Merge Node 6 into Node 3: path sum = 5 (node 3) * 2 (wt) * 23 (node 6) = 230, Node 3 new weight = 5 + 23 * 2 = 51, Grand sum = 241 + 230 = 471
Merge Node 3 into Node 2: path sum = 1 (node 2) * 4 (wt) * 51 (node 3) = 204, Node 2 new weight = 1 + 51 * 4 = 205, Grand sum = 471 + 204 = 675
Merge Node 2 into Node 5: path sum = 1 (node 5) * 4 (wt) * 205 (node 2) = 820, Node 5 new weight = 1 + 205 * 4 = 821, Grand sum = 675 + 820 = 1495
Merge Node 5 into Node 14: path sum = 17 (node 14) * 5 (wt) * 821 (node 5) = 69785, Node 14 new weight = 17 + 821 * 5 = 4122, Grand sum = 1495 + 69785 = 71280
*/
|
[
"d.xie@sta.samsung.com"
] |
d.xie@sta.samsung.com
|
eb2c1dd1a9516f5e61ccb7737188815bd1678e9e
|
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
|
/chromium/third_party/crashpad/crashpad/snapshot/win/module_snapshot_win.cc
|
d9d74c1b7ff20083a6618e1369dd490b1929129f
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] |
permissive
|
Csineneo/Vivaldi
|
4eaad20fc0ff306ca60b400cd5fad930a9082087
|
d92465f71fb8e4345e27bd889532339204b26f1e
|
refs/heads/master
| 2022-11-23T17:11:50.714160
| 2019-05-25T11:45:11
| 2019-05-25T11:45:11
| 144,489,531
| 5
| 4
|
BSD-3-Clause
| 2022-11-04T05:55:33
| 2018-08-12T18:04:37
| null |
UTF-8
|
C++
| false
| false
| 11,509
|
cc
|
// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/win/module_snapshot_win.h"
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "client/crashpad_info.h"
#include "client/simple_address_range_bag.h"
#include "snapshot/win/memory_snapshot_win.h"
#include "snapshot/win/pe_image_annotations_reader.h"
#include "snapshot/win/pe_image_reader.h"
#include "util/misc/tri_state.h"
#include "util/misc/uuid.h"
namespace crashpad {
namespace internal {
ModuleSnapshotWin::ModuleSnapshotWin()
: ModuleSnapshot(),
name_(),
pdb_name_(),
uuid_(),
memory_range_(),
streams_(),
vs_fixed_file_info_(),
initialized_vs_fixed_file_info_(),
process_reader_(nullptr),
pe_image_reader_(),
crashpad_info_(),
timestamp_(0),
age_(0),
initialized_() {}
ModuleSnapshotWin::~ModuleSnapshotWin() {
}
bool ModuleSnapshotWin::Initialize(
ProcessReaderWin* process_reader,
const ProcessInfo::Module& process_reader_module) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
process_reader_ = process_reader;
name_ = process_reader_module.name;
timestamp_ = process_reader_module.timestamp;
pe_image_reader_.reset(new PEImageReader());
if (!pe_image_reader_->Initialize(process_reader_,
process_reader_module.dll_base,
process_reader_module.size,
base::UTF16ToUTF8(name_))) {
return false;
}
DWORD age_dword;
if (pe_image_reader_->DebugDirectoryInformation(
&uuid_, &age_dword, &pdb_name_)) {
static_assert(sizeof(DWORD) == sizeof(uint32_t), "unexpected age size");
age_ = age_dword;
} else {
// If we fully supported all old debugging formats, we would want to extract
// and emit a different type of CodeView record here (as old Microsoft tools
// would do). As we don't expect to ever encounter a module that wouldn't be
// using .PDB that we actually have symbols for, we simply set a plausible
// name here, but this will never correspond to symbols that we have.
pdb_name_ = base::UTF16ToUTF8(name_);
}
if (!memory_range_.Initialize(process_reader_->Memory(),
process_reader_->Is64Bit())) {
return false;
}
WinVMAddress crashpad_info_address;
WinVMSize crashpad_info_size;
if (pe_image_reader_->GetCrashpadInfoSection(&crashpad_info_address,
&crashpad_info_size)) {
ProcessMemoryRange info_range;
info_range.Initialize(memory_range_);
info_range.RestrictRange(crashpad_info_address,
crashpad_info_address + crashpad_info_size);
auto info = std::make_unique<CrashpadInfoReader>();
if (info->Initialize(&info_range, crashpad_info_address)) {
crashpad_info_ = std::move(info);
}
}
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
void ModuleSnapshotWin::GetCrashpadOptions(CrashpadInfoClientOptions* options) {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
if (process_reader_->Is64Bit())
GetCrashpadOptionsInternal<process_types::internal::Traits64>(options);
else
GetCrashpadOptionsInternal<process_types::internal::Traits32>(options);
}
std::string ModuleSnapshotWin::Name() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return base::UTF16ToUTF8(name_);
}
uint64_t ModuleSnapshotWin::Address() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return pe_image_reader_->Address();
}
uint64_t ModuleSnapshotWin::Size() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return pe_image_reader_->Size();
}
time_t ModuleSnapshotWin::Timestamp() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return timestamp_;
}
void ModuleSnapshotWin::FileVersion(uint16_t* version_0,
uint16_t* version_1,
uint16_t* version_2,
uint16_t* version_3) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
const VS_FIXEDFILEINFO* ffi = VSFixedFileInfo();
if (ffi) {
*version_0 = ffi->dwFileVersionMS >> 16;
*version_1 = ffi->dwFileVersionMS & 0xffff;
*version_2 = ffi->dwFileVersionLS >> 16;
*version_3 = ffi->dwFileVersionLS & 0xffff;
} else {
*version_0 = 0;
*version_1 = 0;
*version_2 = 0;
*version_3 = 0;
}
}
void ModuleSnapshotWin::SourceVersion(uint16_t* version_0,
uint16_t* version_1,
uint16_t* version_2,
uint16_t* version_3) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
const VS_FIXEDFILEINFO* ffi = VSFixedFileInfo();
if (ffi) {
*version_0 = ffi->dwProductVersionMS >> 16;
*version_1 = ffi->dwProductVersionMS & 0xffff;
*version_2 = ffi->dwProductVersionLS >> 16;
*version_3 = ffi->dwProductVersionLS & 0xffff;
} else {
*version_0 = 0;
*version_1 = 0;
*version_2 = 0;
*version_3 = 0;
}
}
ModuleSnapshot::ModuleType ModuleSnapshotWin::GetModuleType() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
const VS_FIXEDFILEINFO* ffi = VSFixedFileInfo();
if (ffi) {
switch (ffi->dwFileType) {
case VFT_APP:
return ModuleSnapshot::kModuleTypeExecutable;
case VFT_DLL:
return ModuleSnapshot::kModuleTypeSharedLibrary;
case VFT_DRV:
case VFT_VXD:
return ModuleSnapshot::kModuleTypeLoadableModule;
}
}
return ModuleSnapshot::kModuleTypeUnknown;
}
void ModuleSnapshotWin::UUIDAndAge(crashpad::UUID* uuid, uint32_t* age) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*uuid = uuid_;
*age = age_;
}
std::string ModuleSnapshotWin::DebugFileName() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return pdb_name_;
}
std::vector<std::string> ModuleSnapshotWin::AnnotationsVector() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
// These correspond to system-logged things on Mac. We don't currently track
// any of these on Windows, but could in the future. See
// https://crashpad.chromium.org/bug/38.
return std::vector<std::string>();
}
std::map<std::string, std::string> ModuleSnapshotWin::AnnotationsSimpleMap()
const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
PEImageAnnotationsReader annotations_reader(
process_reader_, pe_image_reader_.get(), name_);
return annotations_reader.SimpleMap();
}
std::vector<AnnotationSnapshot> ModuleSnapshotWin::AnnotationObjects() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
PEImageAnnotationsReader annotations_reader(
process_reader_, pe_image_reader_.get(), name_);
return annotations_reader.AnnotationsList();
}
std::set<CheckedRange<uint64_t>> ModuleSnapshotWin::ExtraMemoryRanges() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
std::set<CheckedRange<uint64_t>> ranges;
if (process_reader_->Is64Bit())
GetCrashpadExtraMemoryRanges<process_types::internal::Traits64>(&ranges);
else
GetCrashpadExtraMemoryRanges<process_types::internal::Traits32>(&ranges);
return ranges;
}
std::vector<const UserMinidumpStream*>
ModuleSnapshotWin::CustomMinidumpStreams() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
streams_.clear();
if (process_reader_->Is64Bit()) {
GetCrashpadUserMinidumpStreams<process_types::internal::Traits64>(
&streams_);
} else {
GetCrashpadUserMinidumpStreams<process_types::internal::Traits32>(
&streams_);
}
std::vector<const UserMinidumpStream*> result;
for (const auto& stream : streams_) {
result.push_back(stream.get());
}
return result;
}
template <class Traits>
void ModuleSnapshotWin::GetCrashpadOptionsInternal(
CrashpadInfoClientOptions* options) {
if (!crashpad_info_) {
options->crashpad_handler_behavior = TriState::kUnset;
options->system_crash_reporter_forwarding = TriState::kUnset;
options->gather_indirectly_referenced_memory = TriState::kUnset;
options->indirectly_referenced_memory_cap = 0;
return;
}
options->crashpad_handler_behavior =
crashpad_info_->CrashpadHandlerBehavior();
options->system_crash_reporter_forwarding =
crashpad_info_->SystemCrashReporterForwarding();
options->gather_indirectly_referenced_memory =
crashpad_info_->GatherIndirectlyReferencedMemory();
options->indirectly_referenced_memory_cap =
crashpad_info_->IndirectlyReferencedMemoryCap();
}
const VS_FIXEDFILEINFO* ModuleSnapshotWin::VSFixedFileInfo() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
if (initialized_vs_fixed_file_info_.is_uninitialized()) {
initialized_vs_fixed_file_info_.set_invalid();
if (pe_image_reader_->VSFixedFileInfo(&vs_fixed_file_info_)) {
initialized_vs_fixed_file_info_.set_valid();
}
}
return initialized_vs_fixed_file_info_.is_valid() ? &vs_fixed_file_info_
: nullptr;
}
template <class Traits>
void ModuleSnapshotWin::GetCrashpadExtraMemoryRanges(
std::set<CheckedRange<uint64_t>>* ranges) const {
if (!crashpad_info_ || !crashpad_info_->ExtraMemoryRanges())
return;
std::vector<SimpleAddressRangeBag::Entry> simple_ranges(
SimpleAddressRangeBag::num_entries);
if (!process_reader_->Memory()->Read(
crashpad_info_->ExtraMemoryRanges(),
simple_ranges.size() * sizeof(simple_ranges[0]),
&simple_ranges[0])) {
LOG(WARNING) << "could not read simple address_ranges from "
<< base::UTF16ToUTF8(name_);
return;
}
for (const auto& entry : simple_ranges) {
if (entry.base != 0 || entry.size != 0) {
// Deduplication here is fine.
ranges->insert(CheckedRange<uint64_t>(entry.base, entry.size));
}
}
}
template <class Traits>
void ModuleSnapshotWin::GetCrashpadUserMinidumpStreams(
std::vector<std::unique_ptr<const UserMinidumpStream>>* streams) const {
if (!crashpad_info_)
return;
for (uint64_t cur = crashpad_info_->UserDataMinidumpStreamHead(); cur;) {
internal::UserDataMinidumpStreamListEntry list_entry;
if (!process_reader_->Memory()->Read(
cur, sizeof(list_entry), &list_entry)) {
LOG(WARNING) << "could not read user data stream entry from "
<< base::UTF16ToUTF8(name_);
return;
}
if (list_entry.size != 0) {
std::unique_ptr<internal::MemorySnapshotWin> memory(
new internal::MemorySnapshotWin());
memory->Initialize(
process_reader_, list_entry.base_address, list_entry.size);
streams->push_back(std::make_unique<UserMinidumpStream>(
list_entry.stream_type, memory.release()));
}
cur = list_entry.next;
}
}
} // namespace internal
} // namespace crashpad
|
[
"csineneo@gmail.com"
] |
csineneo@gmail.com
|
433e563e3cd11109cb8478ab8bd2ea5ac8e225fe
|
89b7ffc5c56331a189501cda035648e2b2016d74
|
/WebLayoutCoreOnly/Source/WebCore/RenderTableRow.h
|
99ec28cb7e860b456892a3b352eda5f863ac7d12
|
[
"MIT"
] |
permissive
|
jjbheda/trylearn
|
60343fdb74dd597f0a49286de4ec1f0f57a06faa
|
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
|
refs/heads/master
| 2020-03-22T17:49:17.391764
| 2018-03-30T16:25:32
| 2018-03-30T16:25:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,398
|
h
|
/*
* Copyright (C) 1997 Martin Jones (mjones@kde.org)
* (C) 1997 Torben Weis (weis@kde.org)
* (C) 1998 Waldo Bastian (bastian@kde.org)
* (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#pragma once
#include "RenderTableSection.h"
namespace WebCore {
static const unsigned unsetRowIndex = 0x7FFFFFFF;
static const unsigned maxRowIndex = 0x7FFFFFFE; // 2,147,483,646
class RenderTableRow final : public RenderBox {
WTF_MAKE_ISO_ALLOCATED(RenderTableRow);
public:
RenderTableRow(RenderStyle&&);
RenderTableRow* nextRow() const;
RenderTableRow* previousRow() const;
RenderTableCell* firstCell() const;
RenderTableCell* lastCell() const;
RenderTable* table() const;
void paintOutlineForRowIfNeeded(PaintInfo&, const LayoutPoint&);
static RenderPtr<RenderTableRow> createAnonymousWithParentRenderer(const RenderTableSection&);
RenderPtr<RenderBox> createAnonymousBoxWithSameTypeAs(const RenderBox&) const override;
void setRowIndex(unsigned);
bool rowIndexWasSet() const { return m_rowIndex != unsetRowIndex; }
unsigned rowIndex() const;
const BorderValue& borderAdjoiningTableStart() const;
const BorderValue& borderAdjoiningTableEnd() const;
const BorderValue& borderAdjoiningStartCell(const RenderTableCell&) const;
const BorderValue& borderAdjoiningEndCell(const RenderTableCell&) const;
void addChild(RenderPtr<RenderObject> child, RenderObject* beforeChild = 0) override;
bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) override;
void collapseAndDestroyAnonymousSiblingRows();
private:
static RenderPtr<RenderTableRow> createTableRowWithStyle(const RenderStyle&);
const char* renderName() const override { return (isAnonymous() || isPseudoElement()) ? "RenderTableRow (anonymous)" : "RenderTableRow"; }
bool isTableRow() const override { return true; }
bool canHaveChildren() const override { return true; }
void willBeRemovedFromTree() override;
void layout() override;
LayoutRect clippedOverflowRectForRepaint(const RenderElement* repaintContainer) const override;
bool requiresLayer() const override { return false; //hasOverflowClip() || hasTransformRelatedProperty() || hasHiddenBackface() || hasClipPath() || createsGroup() || isStickilyPositioned();
}
//void paint(PaintInfo&, const LayoutPoint&) override;
void styleDidChange(StyleDifference, const RenderStyle* oldStyle) override;
RenderTableSection* section() const { return downcast<RenderTableSection>(parent()); }
void firstChild() const = delete;
void lastChild() const = delete;
void nextSibling() const = delete;
void previousSibling() const = delete;
unsigned m_rowIndex : 31;
};
inline void RenderTableRow::setRowIndex(unsigned rowIndex)
{
if (UNLIKELY(rowIndex > maxRowIndex))
CRASH();
m_rowIndex = rowIndex;
}
inline unsigned RenderTableRow::rowIndex() const
{
ASSERT(rowIndexWasSet());
return m_rowIndex;
}
inline const BorderValue& RenderTableRow::borderAdjoiningTableStart() const
{
if (isDirectionSame(section(), table()))
return style().borderStart();
return style().borderEnd();
}
inline const BorderValue& RenderTableRow::borderAdjoiningTableEnd() const
{
if (isDirectionSame(section(), table()))
return style().borderEnd();
return style().borderStart();
}
inline RenderTable* RenderTableRow::table() const
{
RenderTableSection* section = this->section();
if (!section)
return nullptr;
return downcast<RenderTable>(section->parent());
}
inline RenderTableRow* RenderTableRow::nextRow() const
{
return downcast<RenderTableRow>(RenderBox::nextSibling());
}
inline RenderTableRow* RenderTableRow::previousRow() const
{
return downcast<RenderTableRow>(RenderBox::previousSibling());
}
inline RenderTableRow* RenderTableSection::firstRow() const
{
return downcast<RenderTableRow>(RenderBox::firstChild());
}
inline RenderTableRow* RenderTableSection::lastRow() const
{
return downcast<RenderTableRow>(RenderBox::lastChild());
}
inline RenderPtr<RenderBox> RenderTableRow::createAnonymousBoxWithSameTypeAs(const RenderBox& renderer) const
{
return RenderTableRow::createTableRowWithStyle(renderer.style());
}
} // namespace WebCore
SPECIALIZE_TYPE_TRAITS_RENDER_OBJECT(RenderTableRow, isTableRow())
|
[
"jianbai.gbj@alibaba-inc.com"
] |
jianbai.gbj@alibaba-inc.com
|
943bacdce81d365058783fed35770c2759f7edfc
|
189041dd0815ef75a49080dc49606edaf9cc33c9
|
/17.电话号码的字母组合.cpp
|
2f760cf1287740b7163591c3d7b264408bcb8fde
|
[] |
no_license
|
nercoeus/leetcode_practice
|
1b3e9e3165fb7af9a69da695de823c423e4b85b0
|
5181467cc80b417137ff32133460ad58f8fad365
|
refs/heads/master
| 2022-12-26T18:45:31.700552
| 2021-05-19T15:54:07
| 2021-05-19T15:54:07
| 152,102,663
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 975
|
cpp
|
/*
* @lc app=leetcode.cn id=17 lang=cpp
*
* [17] 电话号码的字母组合
*/
// @lc code=start
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:
vector<string> letterCombinations(string digits)
{
vector<string> res;
if (digits.empty())
return res;
vector<string> letter({"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"});
string path = "";
DFS(digits, 0, path, res, letter);
return res;
}
void DFS(string digits, int pos, string &path, vector<string> &res, vector<string> &letter)
{
if (pos == digits.size())
{
res.push_back(path);
return;
}
for (auto c : letter[digits[pos] - '0'])
{
path.push_back(c);
DFS(digits, pos + 1, path, res, letter);
path.pop_back();
}
}
};
// @lc code=end
|
[
"18252116593@163.com"
] |
18252116593@163.com
|
bc60a68efd2e2be024ca355f53cf0800fdba24eb
|
9fa292d97ceb374068d355bd41097d0407d68bd3
|
/include/rspf/base/rspfKeywordlist.h
|
a29bfe9f5c159a038694345590bdbcf9d995566e
|
[] |
no_license
|
mfkiwl/rspf_v2.0
|
4d90153b92cc416663c798e05f87e348ad8792ef
|
f22d2707b775a4776fc8359a255f39c26ecc96a3
|
refs/heads/master
| 2021-05-27T04:36:34.132569
| 2013-07-16T04:04:12
| 2013-07-16T04:04:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,740
|
h
|
//*******************************************************************
//
// License: See top level LICENSE.txt file.
//
// Author: Ken Melero
//
// Description: This class provides capabilities for keywordlists.
//
//********************************************************************
// $Id: rspfKeywordlist.h 21527 2012-08-26 16:50:49Z dburken $
#ifndef rspfKeywordlist_HEADER
#define rspfKeywordlist_HEADER 1
#include <rspf/base/rspfErrorStatusInterface.h>
#include <rspf/base/rspfReferenced.h>
#include <rspf/base/rspfConstants.h>
#include <rspf/base/rspfErrorCodes.h>
#include <rspf/base/rspfString.h>
#include <iosfwd>
#include <map>
#include <vector>
#include <algorithm>
static const char DEFAULT_DELIMITER = ':';
class rspfFilename;
class RSPF_DLL rspfKeywordlist : public rspfErrorStatusInterface,
public rspfReferenced
{
public:
typedef std::map<std::string, std::string> KeywordMap;
rspfKeywordlist(const rspfKeywordlist& src);
rspfKeywordlist(char delimiter = DEFAULT_DELIMITER,
bool expandEnvVars = false);
rspfKeywordlist(const char* file,
char delimiter = DEFAULT_DELIMITER,
bool ignoreBinaryChars = false,
bool expandEnvVars = false );
rspfKeywordlist(const rspfFilename& fileName,
char delimiter = DEFAULT_DELIMITER,
bool ignoreBinaryChars = false,
bool expandEnvVars = false);
~rspfKeywordlist();
static const std::string NULL_KW;
/*!
* Reads file and adds keywords to the KeywordMap.
* Returns true if file was parsed, false on error.
*/
bool addFile(const char* file);
/*!
* Reads file and adds keywords to the KeywordMap.
* Returns true if file was parsed, false on error.
*/
bool addFile(const rspfFilename& file);
/*!
* Method to change default delimiter. Handy when parsing
* files similar to a rspfKeywordlist. (DEFAULT = ':')
*/
void change_delimiter(char del);
rspfString delimiter_str() const;
/*!
* If set to true, then strings found having the format
* "$(env_var_name)" are expanded in place.
*/
void setExpandEnvVarsFlag( bool flag );
/*!
* Returns the flag that determines whether or not
* environment variables are expanded.
*/
bool getExpandEnvVarsFlag( void ) const;
void add(const char* prefix,
const rspfKeywordlist& kwl,
bool overwrite=true);
/**
* This is a generic find method that takes a comparator type and iterates through
* the map executing the overloaded operator ().
* Typical code example format
<pre>
typedef std::unary_function<std::pair<rspfString, rspfString>, bool> KwlCompareFunctionType;
class KwlKeyCaseInsensitiveEquals : public KwlCompareFunctionType
{
public:
KwlKeyCaseInsensitiveEquals(const rspfString& key):m_key(key){}
virtual bool operator()(const KwlComparePairType& rhs)const
{
return (m_key == rhs.first.downcase());
}
rspfString m_key;
};
// now for use case example:
kwl.findValue(value, KwlKeyCaseInsensitiveEquals("foo"));
</pre>
This example shows how to supplly your own comparator and do a case insensitive
search for the key foo and the value is set to the variable value.
*
*/
template<class CompareType>
bool findValue(rspfString& value, const CompareType& compare)const
{
KeywordMap::const_iterator iter = std::find_if(m_map.begin(), m_map.end(), compare);
bool result = (iter != m_map.end());
if(result) value = iter->second;
return result;
}
std::string& operator[](const std::string& key)
{
return m_map[key];
}
std::string operator[](const std::string& key)const
{
rspfString result = find(key.c_str());
return result.c_str();
}
// Methods to add keywords to list.
void addPair(const std::string& key,
const std::string& value,
bool overwrite = true);
void addPair(const std::string& prefix,
const std::string& key,
const std::string& value,
bool overwrite = true);
/*!
* Allows you to extract out a sub keywordlist from another
* you can also collapse the hieracrchy by setting
* strip prefix to true.
*/
void add(const rspfKeywordlist& kwl,
const char* prefix=0,
bool stripPrefix=true);
void add(const char* key,
const char* value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
const char* value,
bool overwrite = true);
void add(const char* key,
char value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
char value,
bool overwrite = true);
void add(const char* key,
rspf_int16 value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
rspf_int16 value,
bool overwrite = true);
void add(const char* key,
rspf_uint16 value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
rspf_uint16 value,
bool overwrite = true);
void add(const char* key,
rspf_int32 value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
rspf_int32 value,
bool overwrite = true);
void add(const char* key,
rspf_uint32 value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
rspf_uint32 value,
bool overwrite = true);
void add(const char* key,
rspf_int64 value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
rspf_int64 value,
bool overwrite = true);
void add(const char* key,
rspf_uint64 value,
bool overwrite = true);
void add(const char* prefix,
const char* key,
rspf_uint64 value,
bool overwrite = true);
/**
* @param key Key for key-value pair.
*
* @param value Value to pair with key. Note this will be stored as a
* string.
*
* @param precision Decimal point precision of the output. (default = 8)
*
* @param trimZeroFlag If true trailing '0's and any trailing '.' will
* be trimmed from the converted string. (default = false)
*
* @param scientific If true output will be in scientific notation else
* fixed is used. (default = false)
*/
void add(const char* key,
rspf_float32 value,
bool overwrite = true,
int precision = 8);
/**
* @param key Key for key-value pair.
*
* @param value Value to pair with key. Note this will be stored as a
* string.
*
* @param precision Decimal point precision of the output. (default = 8)
*
* @param trimZeroFlag If true trailing '0's and any trailing '.' will
* be trimmed from the converted string. (default = false)
*
* @param scientific If true output will be in scientific notation else
* fixed is used. (default = false)
*/
void add(const char* prefix,
const char* key,
rspf_float32 value,
bool overwrite = true,
int precision = 8);
/**
* @param key Key for key-value pair.
*
* @param value Value to pair with key. Note this will be stored as a
* string.
*
* @param precision Decimal point precision of the output. (default = 15)
*
* @param trimZeroFlag If true trailing '0's and any trailing '.' will
* be trimmed from the converted string. (default = false)
*
* @param scientific If true output will be in scientific notation else
* fixed is used. (default = false)
*/
void add(const char* key,
rspf_float64 value,
bool overwrite = true,
int precision = 15);
/**
* @param key Key for key-value pair.
*
* @param value Value to pair with key. Note this will be stored as a
* string.
*
* @param precision Decimal point precision of the output. (default = 15)
*
* @param trimZeroFlag If true trailing '0's and any trailing '.' will
* be trimmed from the converted string. (default = false)
*
* @param scientific If true output will be in scientific notation else
* fixed is used. (default = false)
*/
void add(const char* prefix,
const char* key,
rspf_float64 value,
bool overwrite = true,
int precision = 15);
/**
* @brief Checks for key in map.
*
* Note that "find" and findKey will alway return an empty string even if
* the key in not in the map.
*
* @return true if key is in map even if value is empty; false, if not.
*/
bool hasKey( const std::string& key ) const;
/**
* @brief Find methods that take std::string(s).
* Searches the map for key(/prefix) and returns the resulting value
* or an empty string if the key was not found.
* @param key e.g. "number_line"
* @param prefix e..g "image0."
* @return Reference to string. This will be emptry if not found or
* if value is empty.
*/
const std::string& findKey(const std::string& key) const;
const std::string& findKey(const std::string& prefix,
const std::string& key) const;
const char* find(const char* key) const;
const char* find(const char* prefix,
const char* key) const;
void remove(const char * key);
void remove(const char* prefix, const char * key);
/*!
* Searches the map for the number of keys containing the string.
*/
rspf_uint32 numberOf(const char* str) const;
/*!
* Searches the map for the number of keys containing the prefix+key.
*
* Given the keyword list contains:
*
* source.type1: foo
* source.type2: you
*
* This:
*
* int number_of_sources = numberOf("source", "type");
*
* number_of_sources equals 2
*/
rspf_uint32 numberOf(const char* prefix, const char* key) const;
/**
* Methods to dump the rspfKeywordlist to a file on disk.
*
* @param file Name of output file.
* @param comment Optional string that will be written to line 1
* as a C++-style comment. A "//" is prepended to the input string.
*
* @return true on success, false on error.
*/
virtual bool write(const char* file, const char* comment = 0) const;
virtual rspfString toString()const;
virtual void toString(rspfString& result)const;
virtual void writeToStream(std::ostream &out)const;
virtual std::ostream& print(std::ostream& os) const;
RSPFDLLEXPORT friend std::ostream& operator<<(std::ostream& os,
const rspfKeywordlist& kwl);
bool operator ==(rspfKeywordlist& kwl)const;
/*!
* Clear all contents out of the rspfKeywordlist.
*/
void clear();
/*!
* Add contents of another keyword list to this one.
*
* @param src the keyword list to copy items from.
* @param overwrite true if keys existing in this and src should have
* their value overwritten by the src value, otherwise false to preserve
* the original value. Defaults to true.
*/
void addList( const rspfKeywordlist &src, bool overwrite = true );
/** deprecated method */
virtual bool parseStream(std::istream& is,
bool ignoreBinaryChars);
virtual bool parseStream(std::istream& is);
virtual bool parseString(const std::string& inString);
/*!
* Will return a list of keys that contain the string passed in.
* Later we will need to allow a user to specify regular expresion
* searches.
*/
std::vector<rspfString> findAllKeysThatContains(
const rspfString &searchString)const;
std::vector<rspfString> findAllKeysThatMatch(
const rspfString ®ularExpression)const;
void extractKeysThatMatch(rspfKeywordlist& kwl,
const rspfString ®ularExpression)const;
void removeKeysThatMatch(const rspfString ®ularExpression);
/*!
* Will return only the portion of the key that
* matches the regular expression.
*
* example:
*
* source1.source1.a:
* source1.source2.a:
* source1.source3.a:
* source1.source4.a:
* source1.source10.a:
*
* kwl.getSubstringKeyList("source1.source[0-9]*\\.");
*
* will return:
*
* source1.source1.
* source1.source2.
* source1.source3.
* source1.source4.
* source1.source10.
*
*/
std::vector<rspfString> getSubstringKeyList(const rspfString& regularExpression)const;
void getSubstringKeyList(std::vector<rspfString>& result,
const rspfString& regularExpression)const;
rspf_uint32 getNumberOfSubstringKeys(
const rspfString& regularExpression)const;
void addPrefixToAll(const rspfString& prefix);
void addPrefixToKeysThatMatch(const rspfString& prefix,
const rspfString& regularExpression);
void stripPrefixFromAll(const rspfString& regularExpression);
/*!
* Returns the number of elements.
*/
rspf_uint32 getSize()const;
const rspfKeywordlist::KeywordMap& getMap()const;
rspfKeywordlist::KeywordMap& getMap();
rspfKeywordlist& downcaseKeywords();
rspfKeywordlist& upcaseKeywords();
rspfKeywordlist& trimAllValues(const rspfString& valueToTrim= rspfString(" \t\n\r"));
rspfKeywordlist trimAllValues(const rspfString& valueToTrim= rspfString(" \t\n\r"))const;
//! [OLK, Aug/2008]
//! Sets the boolean <rtn_val> depending on value associated with keyword for values =
//! (yes|no|true|false|1|0). Returns TRUE if keyword found, otherwise false. Also returns false
//! if none of the above permitted values are specified (rtn_val left unchanged in this case).
bool getBoolKeywordValue(bool& rtn_val,
const char* keyword,
const char* prefix=0) const;
protected:
enum KeywordlistParseState
{
KeywordlistParseState_OK = 0,
KeywordlistParseState_FAIL = 1, // just used to say this set of token has failed the rules
KeywordlistParseState_BAD_STREAM = 2, // Means an error occured that is a mal formed stream for Keywordlist
};
/*!
* Method to parse files to initialize the list. Method will error on
* binary characters if "ignoreBinaryChars = false". This is used by
* ImageHandler factories that can be passed a binary file inadvertently
* by a user. The "ignoreBinaryChars" flag should be set to true if
* a text file contains mixed ascii/binary values.
* Returns true if file was parsed, false on error.
*/
bool parseFile(const rspfFilename& file,
bool ignoreBinaryChars = false);
bool isValidKeywordlistCharacter(rspf_uint8 c)const;
void skipWhitespace(std::istream& in)const;
KeywordlistParseState readComments(rspfString& sequence, std::istream& in)const;
KeywordlistParseState readKey(rspfString& sequence, std::istream& in)const;
KeywordlistParseState readValue(rspfString& sequence, std::istream& in)const;
KeywordlistParseState readKeyAndValuePair(rspfString& key, rspfString& value, std::istream& in)const;
// Method to see if keyword exists in list.
KeywordMap::iterator getMapEntry(const std::string& key);
KeywordMap::iterator getMapEntry(const rspfString& key);
KeywordMap::iterator getMapEntry(const char* key);
KeywordMap m_map;
char m_delimiter;
bool m_preserveKeyValues; // enables preserving empty field values, multi lines, ... etc
bool m_expandEnvVars;
};
#endif /* #ifndef rspfKeywordlist_HEADER */
|
[
"loongfee@gmail.com"
] |
loongfee@gmail.com
|
c17318d3696465f153cec26f0cc3d5d390624f6d
|
fdc26fead1306592b84068ec9ac3ca5bcc1b9834
|
/INTERVIEWBIT/Other/OSSTesting.cpp
|
65a6e38f186824ce95ca2927c858c582edaccc46
|
[
"MIT"
] |
permissive
|
yashsanghvi001/Hacktober-CP-contributions
|
f4e34d8061d9b8be8cf5e5004a983098a3022b11
|
a42628c48b00e296eb41f9dd1e223781ebc841a6
|
refs/heads/main
| 2022-12-31T11:58:25.515263
| 2020-10-24T07:17:08
| 2020-10-24T07:17:08
| 302,109,476
| 1
| 0
|
MIT
| 2020-10-14T16:18:48
| 2020-10-07T17:22:07
|
C++
|
UTF-8
|
C++
| false
| false
| 267
|
cpp
|
#include<iostream>
#include<sstream>
using namespace std;
int main(){
int i;
ostringstream oss;
string str = "";
for(i = 0; i < 5; i++){
oss << i;
str = str + oss.str();
oss.str("");
}
cout << str;
return 0;
}
|
[
"yogeshgaur1995@gmail.com"
] |
yogeshgaur1995@gmail.com
|
15aa535c4a0005cfb5d9c8f99c44b741aa41118e
|
05dee134ef4e552fecd0d39dea5d6cdc3a82965c
|
/LuoGu/洛谷-P3258.cpp
|
a0d04e7d9f44745c9021350ca1d43889fd223446
|
[] |
no_license
|
yliu-cs/ACM
|
35239420f36baf336e17a5c45d2c7a5ae9317413
|
f67ca3e6de900afabe38201e19c74d0e1c6a40a3
|
refs/heads/master
| 2022-03-20T10:10:25.787434
| 2019-12-05T16:30:29
| 2019-12-05T16:30:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,707
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
struct Edge {
int V, Next;
};
Edge edges[maxn << 1];
int Head[maxn];
int Tot;
void Init() {
Tot = 0;
memset(Head, -1, sizeof(Head));
}
void AddEdge(int U, int V) {
edges[Tot] = Edge {V, Head[U]};
Head[U] = Tot++;
}
int Rmq[maxn << 1];
struct ST {
int Dp[maxn << 1][20];
void Init(int N) {
for (int i = 1; i <= N; ++i) {
Dp[i][0] = i;
}
for (int j = 1; (1 << j) <= N; ++j) {
for (int i = 1; i + (1 << j) - 1 <= N; ++i) {
Dp[i][j] = Rmq[Dp[i][j - 1]] < Rmq[Dp[i + (1 << (j - 1))][j - 1]] ? Dp[i][j - 1] : Dp[i + (1 << (j - 1))][j - 1];
}
}
}
int Query(int Left, int Right) {
if (Left > Right) {
swap(Left, Right);
}
int Len = int(log2(Right - Left + 1));
return Rmq[Dp[Left][Len]] <= Rmq[Dp[Right - (1 << Len) + 1][Len]] ? Dp[Left][Len] : Dp[Right - (1 << Len) + 1][Len];
}
};
int Vertex[maxn << 1];
int First[maxn];
int Parent[maxn];
int LCATot;
ST St;
void LCADfs(int Cur, int Pre, int Depth) {
Vertex[++LCATot] = Cur;
First[Cur] = LCATot;
Rmq[LCATot] = Depth;
Parent[Cur] = Pre;
for (int i = Head[Cur]; ~i; i = edges[i].Next) {
if (edges[i].V == Pre) {
continue;
}
LCADfs(edges[i].V, Cur, Depth + 1);
Vertex[++LCATot] = Cur;
Rmq[LCATot] = Depth;
}
}
void LCAInit(int Root, int NodeNum) {
LCATot = 0;
LCADfs(Root, 0, 0);
St.Init(2 * NodeNum - 1);
}
int QueryLCA(int U, int V) {
return Vertex[St.Query(First[U], First[V])];
}
int N;
int A[maxn];
int Cnt[maxn];
int Dfs(int Cur, int Pre) {
for (int i = Head[Cur]; ~i; i = edges[i].Next) {
if (edges[i].V == Pre) {
continue;
}
Cnt[Cur] += Dfs(edges[i].V, Cur);
}
return Cnt[Cur];
}
int main(int argc, char *argv[]) {
Init();
scanf("%d", &N);
for (int i = 1; i <= N; ++i) {
scanf("%d", &A[i]);
}
for (int i = 1, X, Y; i < N; ++i) {
scanf("%d%d", &X, &Y);
AddEdge(X, Y);
AddEdge(Y, X);
}
Parent[1] = 0;
LCAInit(1, N);
memset(Cnt, 0, sizeof(Cnt));
for (int i = 1; i < N; ++i) {
int LCA = QueryLCA(A[i], A[i + 1]);
Cnt[A[i]]++; Cnt[A[i + 1]]++;
Cnt[LCA]--; Cnt[Parent[LCA]]--;
}
Dfs(1, 0);
for (int i = 2; i <= N; ++i) {
Cnt[A[i]]--;
}
for (int i = 1; i <= N; ++i) {
printf("%d\n", Cnt[i]);
}
return 0;
}
|
[
"978539910@qq.com"
] |
978539910@qq.com
|
f8d4a206c917c7481d34b354ec62b0b9a6b4c800
|
bc4f3bae021fb7db65c5fc571cc26fdec38c28b4
|
/Pods/Headers/Public/SARUnArchiveANY/ulinks.hpp
|
93506a6330e5d9c0bc8f42d37740632aa5a93e0a
|
[] |
no_license
|
a349112363/RarDecompression
|
e00f101cb10f2275cee31f1cbb2a4ad0f3f757b0
|
c26b8ded3ad99473f3cae81836e329acf8ba16b0
|
refs/heads/master
| 2020-03-18T02:56:12.417401
| 2018-05-21T06:14:27
| 2018-05-21T06:14:27
| 134,214,466
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 58
|
hpp
|
../../../SARUnArchiveANY/External/Unrar/Headers/ulinks.hpp
|
[
"kiss.loo@qq.com"
] |
kiss.loo@qq.com
|
20adf1e4f02b92c80a99a778db630e8bb7972486
|
d6d0117815cd0328bfd6e8f433db5cc5b7e1b9fd
|
/hw4/twiteng.cpp
|
75bd94a4ef224d0713d9fb44feb1b47c21c31faf
|
[] |
no_license
|
dshebib/USC-CS104-Data-Structures
|
ec623a67c9ecfcf6e6904038f19cd2d068e37f51
|
e1d533f182d8c751688658c332a07c45a7b93d0a
|
refs/heads/master
| 2023-03-21T14:30:31.524416
| 2017-07-17T06:54:57
| 2017-07-17T06:54:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,282
|
cpp
|
#include "twiteng.h"
TwitEng::TwitEng()
{
tweetSize_ = 0;
tweets_ = new Tweet[10];
tweetMaxSize_ = 10;
}
TwitEng::~TwitEng()
{
delete [] tweets_;
for(std::map<std::string, User*>::iterator it = usrs.begin(); it != usrs.end(); it++)
{
delete it->second;
}
}
void TwitEng::adduser(std::string name)
{
User* usr = new User(name);
usrs.insert(std::make_pair(name, usr));
}
void TwitEng::follows(std::string usr, std::string usr2)
{
usrs.find(usr)->second->addFollowing(usrs.find(usr2)->second);
if(usrs.find(usr2) != usrs.end())
usrs.find(usr2)->second->addFollower(usrs.find(usr)->second);
}
void TwitEng::setallfollowers()
{
for(std::map<std::string, User*>::iterator it = usrs.begin(); it != usrs.end(); it++)
{
std::set<User*> following = it->second->following();
for(std::set<User*>::iterator itu = following.begin(); itu != following.end(); itu++)
{
(*itu)->addFollower(it->second);
}
}
}
std::string TwitEng::toUpper(std::string in)
{
std::string out;
for(unsigned int i = 0; i < in.length(); i++)
{
out += std::toupper(in[i]);
}
return out;
}
void TwitEng::addTweet(std::string& username, DateTime& dt, std::string& text)
{
if(usrs.find(username) == usrs.end())
throw username;
User* usr = usrs.find(username)->second;
if(tweetSize_ == tweetMaxSize_)
{
Tweet* tmp = tweets_;
tweets_ = new Tweet[tweetMaxSize_*2];
for(int i = 0; i < tweetSize_; i++)
{
tweets_[i] = tmp[i];
}
tweetMaxSize_ = tweetMaxSize_*2;
}
Tweet* tmp = new Tweet(username, usr, dt, text);
tweets_[tweetSize_] = *tmp;
tweetSize_++;
usr->addTweet(tweets_+tweetSize_-1);
//Add hashtags
std::set<std::string> newtags = tmp->hashTags();
for(std::set<std::string>::iterator it = newtags.begin(); it != newtags.end(); it++)
{
std::string tag = toUpper(*it);
bool inserted = false;
for(unsigned int i = 0; i < tags.size(); i++)
{
if(tags[i].first.compare(tag) == 0)
{
tags[i].second.insert(tmp);
inserted = true;
}
else if(tags[i].first.compare(tag) < 0)
{
std::set<Tweet*> newset;
newset.insert(tmp);
tags.insert(tags.begin()+i, std::make_pair(tag, newset));
inserted = true;
}
if(inserted)
break;
}
if(!inserted)
{
std::set<Tweet*> newset;
newset.insert(tmp);
tags.push_back(std::make_pair(tag, newset));
}
}
}
bool TwitEng::parse(char* filename)
{
std::ifstream fin(filename);
if(!fin.good()) {//check input file
std::cout << "Error: Input file not found";
return true;
}
std::stringstream ss;
std::string tmp;
std::getline(fin, tmp);
ss.str(tmp);
int num = 0;
ss >> num;
for(int i = 0; i < num; i++)
{
std::getline(fin, tmp);
ss.flush();
ss.clear();
ss.str(tmp);
std::string usr;
ss >> usr;
adduser(usr);
std::string follow;
while(ss >>follow)
{
//follows(usr, follow);
//Do this again later once we ahve all users
}
}
//do that again to add all folloewrs/followings properly
//this took me aprox one year to figure out
std::ifstream fin2(filename);
std::getline(fin2, tmp);
for(int i = 0; i < num; i++)
{
std::getline(fin2, tmp);
ss.flush();
ss.clear();
ss.str(tmp);
std::string usr;
ss >> usr;
std::string follow;
while(ss >>follow)
{
follows(usr, follow);
}
}
while(!fin.eof())
{
std::getline(fin, tmp);
if(tmp.empty())
break;
std::string ins[6];
ins[0] = tmp.substr(0, 4);
ins[1] = tmp.substr(5, 2);
ins[2] = tmp.substr(8, 2);
ins[3] = tmp.substr(11, 2);
ins[4] = tmp.substr(14, 2);
ins[5] = tmp.substr(17, 2);
int intin[6];
for(int i = 0; i < 6; i++)
{
ss.flush();
ss.clear();
ss.str(ins[i]);
ss >> intin[i];
}
int yyyy = intin[0];
int mm = intin[1];
int dd = intin[2];
int hh = intin[3];
int min = intin[4];
int ss = intin[5];
int sp = tmp.find(" ", 20);
std::string username = tmp.substr(20, sp-20);
std::string text = tmp.substr(sp+1);
DateTime dt(hh, min, ss, yyyy, mm, dd);
addTweet(username, dt, text);
}
setallfollowers();
return false;
}
std::set<Tweet*> TwitEng::bsearch(std::string key)
{
key = toUpper(key);
int l = 0;
int r = tags.size() - 1;
while(!(l>r))
{
int m = (l+r)/2;
if(tags[m].first.compare(key) < 0)
r = m-1;
else if(tags[m].first.compare(key) > 0)
l = m+1;
else
{
return tags[m].second;
}
}
throw NULL;
}
std::vector<Tweet*> TwitEng::search(std::vector<std::string>& terms, int strategy)
{
std::vector<Tweet*> out;
std::vector<std::set<Tweet*> > sets;
for(unsigned int i = 0; i < terms.size(); i++)
{
try
{
sets.push_back(bsearch(terms[i]));
}
catch (...)
{
if(strategy == 0)
return out;
}
}
if(strategy == 0)
{
for(std::set<Tweet*>::iterator it = sets[0].begin(); it != sets[0].end(); it++)
{
bool exists = true;
for(unsigned int i = 0; i < sets.size(); i++)
{
if(sets[i].find(*it) == sets[i].end())
exists = false;
}
if (exists)
out.push_back(*it);
}
}
if(strategy == 1)
{
std::set<Tweet*> sout;
for(unsigned int i = 0; i < sets.size(); i++)
{
for(std::set<Tweet*>::iterator it = sets[i].begin(); it != sets[i].end(); it++)
{
sout.insert(*it);
}
}
for(std::set<Tweet*>::iterator it = sout.begin(); it != sout.end(); it++)
{
out.push_back(*it);
}
}
return out;
}
void TwitEng::dumpFeeds()
{
for(std::map<std::string, User*>::iterator it = usrs.begin(); it != usrs.end(); it++)
{
std::string filename = it->first;
filename = filename + ".feed";
const char* fname = filename.c_str();
std::ofstream fout(fname);
std::vector<Tweet*> feed = it->second->getFeed();
std::sort(feed.begin(), feed.end(), TweetComp());
for(unsigned int i = 0; i < feed.size(); i++)
{
fout << *feed[i] << std::endl;
}
fout.close();
}
}
|
[
"shebib@usc.edu"
] |
shebib@usc.edu
|
75a5d7ea4486cfc425a7aee1cc54bbd0c63b72ee
|
2254fb093ccf0b8cfece31e39d05b34b79acb275
|
/priormap_localization/lidar/include/lidar/hough_transform.hpp
|
b9708fb5073078a96c9e531d030ed737731b0b6b
|
[] |
no_license
|
wvu-irl/Bramblebee-Nav-system
|
0badd510941a4a59d6467f5a68ad2292976ef367
|
f88debfc68faf4286726c4ef6c1cec2e6f1906d6
|
refs/heads/master
| 2020-04-02T11:12:11.296935
| 2019-09-19T00:22:17
| 2019-09-19T00:22:17
| 154,376,286
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,902
|
hpp
|
// hough transform in here works for localization in greenhouse
// input: processed lidar data: project to xy coordinate
// output: robot's pose
#ifndef HOUGH_H_
#define HOUGH_H_
#include "ros/ros.h"
#include "ros/console.h"
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/common/common.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/voxel_grid.h>
#define deg2rad 0.017453293f
class Hough
{
public:
Hough();
virtual ~Hough();
ros::NodeHandle _nh;
ros::Subscriber _sub_localmap;
void GeneratePointcloud(); // generate fake 2d point cloud for testing
void GetPointcloud(pcl::PointCloud<pcl::PointXYZ> const &raw_cloud); // read pointcloud from pcd file
// void GetBoundary(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud);
void GetBoundary();
// hough transform to detect lines
void Transform(pcl::PointCloud<pcl::PointXYZ>::Ptr _cloud);
void DrawLines(); //draw lines for visualization
void DetectUShape(); //detect u shape from line information
void GetPose();
void DrawUShape();
bool newLocalmapAvailable();
void setPreviousCounters();
void clearVariables();
// lidar data from precessed pointcloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
std::vector< std::vector<int> > u_shape;
std::vector< std::vector< int > > line_info;
// Store lines for draw
std::vector< std::pair< std::pair<int, int>, std::pair<int, int> > > lines;
int threshold; // intensity of the lines
float min_x, min_y, max_x, max_y;
int _accu_w, _accu_h, _img_w, _img_h;
unsigned int* _accu;
double global_x, global_y, global_theta;
short int _registration_counter;
short int _registration_counter_prev;
private:
// Store lines for draw
// std::vector< std::pair< std::pair<int, int>, std::pair<int, int> > > lines;
bool _registration_new;
};
#endif /* HOUGH_H_ */
|
[
"noreply@github.com"
] |
wvu-irl.noreply@github.com
|
2aef979a06044fa5cf4e12f0729d4deb3b094b38
|
387549ab27d89668e656771a19c09637612d57ed
|
/DRGLib UE project/Plugins/Modio/Source/ThirdParty/NativeSDK/ext/asio/asio/src/tests/properties/cpp11/require_free.cpp
|
ab366a4c6db149d25d236a52a68e8ed045477b41
|
[
"BSL-1.0",
"MIT"
] |
permissive
|
SamsDRGMods/DRGLib
|
3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a
|
76f17bc76dd376f0d0aa09400ac8cb4daad34ade
|
refs/heads/main
| 2023-07-03T10:37:47.196444
| 2023-04-07T23:18:54
| 2023-04-07T23:18:54
| 383,509,787
| 16
| 5
|
MIT
| 2023-04-07T23:18:55
| 2021-07-06T15:08:14
|
C++
|
UTF-8
|
C++
| false
| false
| 1,484
|
cpp
|
//
// cpp11/require_free.cpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "asio/require.hpp"
#include <cassert>
template <int>
struct prop
{
static constexpr bool is_requirable = true;
};
template <int>
struct object
{
template <int N>
friend constexpr object<N> require(const object&, prop<N>)
{
return object<N>();
}
};
namespace asio {
template<int N, int M>
struct is_applicable_property<object<N>, prop<M> >
{
static constexpr bool value = true;
};
} // namespace asio
int main()
{
object<1> o1 = {};
object<2> o2 = asio::require(o1, prop<2>());
object<3> o3 = asio::require(o1, prop<2>(), prop<3>());
object<4> o4 = asio::require(o1, prop<2>(), prop<3>(), prop<4>());
(void)o2;
(void)o3;
(void)o4;
const object<1> o5 = {};
object<2> o6 = asio::require(o5, prop<2>());
object<3> o7 = asio::require(o5, prop<2>(), prop<3>());
object<4> o8 = asio::require(o5, prop<2>(), prop<3>(), prop<4>());
(void)o6;
(void)o7;
(void)o8;
constexpr object<2> o9 = asio::require(object<1>(), prop<2>());
constexpr object<3> o10 = asio::require(object<1>(), prop<2>(), prop<3>());
constexpr object<4> o11 = asio::require(object<1>(), prop<2>(), prop<3>(), prop<4>());
(void)o9;
(void)o10;
(void)o11;
}
|
[
"noreply@github.com"
] |
SamsDRGMods.noreply@github.com
|
a5d42e0eae1a2b6beca313554316239fce002474
|
96feb31b215645ec438c09588e1c9dc5691f283b
|
/plugins/dali-script-v8/src/rendering/shader-wrapper.cpp
|
f3aff6cb89cb1600a2623cb4c46468f26592d031
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
nui-dali/dali-toolkit
|
28a99e6f117023e95920ee8eda35b6346485e074
|
b514a4671789bee2f03b0177393b9a21f62ac2c3
|
refs/heads/master
| 2020-05-26T23:44:18.106253
| 2019-05-17T10:06:27
| 2019-05-17T10:06:27
| 188,398,539
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,394
|
cpp
|
/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "shader-wrapper.h"
// INTERNAL INCLUDES
#include <v8-utils.h>
#include <rendering/shader-api.h>
#include <shared/api-function.h>
#include <shared/object-template-helper.h>
#include <dali-wrapper.h>
namespace Dali
{
namespace V8Plugin
{
v8::Persistent<v8::ObjectTemplate> ShaderWrapper::mShaderTemplate;
ShaderWrapper::ShaderWrapper( const Dali::Shader& shader, GarbageCollectorInterface& gc )
: HandleWrapper( BaseWrappedObject::SHADER , shader, gc )
{
mShader = shader;
}
v8::Handle<v8::Object> ShaderWrapper::WrapShader(v8::Isolate* isolate, const Dali::Shader& shader )
{
v8::EscapableHandleScope handleScope( isolate );
v8::Local<v8::ObjectTemplate> objectTemplate;
objectTemplate = GetShaderTemplate( isolate);
// create an instance of the template
v8::Local<v8::Object> localObject = objectTemplate->NewInstance();
// create the Shader wrapper
ShaderWrapper* pointer = new ShaderWrapper( shader, Dali::V8Plugin::DaliWrapper::Get().GetDaliGarbageCollector() );
// assign the JavaScript object to the wrapper.
pointer->SetJavascriptObject( isolate, localObject );
return handleScope.Escape( localObject );
}
v8::Local<v8::ObjectTemplate> ShaderWrapper::GetShaderTemplate( v8::Isolate* isolate)
{
v8::EscapableHandleScope handleScope( isolate );
v8::Local<v8::ObjectTemplate> objectTemplate;
if( mShaderTemplate.IsEmpty() )
{
objectTemplate = MakeShaderTemplate( isolate );
mShaderTemplate.Reset( isolate, objectTemplate );
}
else
{
// get the object template
objectTemplate = v8::Local<v8::ObjectTemplate>::New( isolate, mShaderTemplate );
}
return handleScope.Escape( objectTemplate );
}
v8::Handle<v8::ObjectTemplate> ShaderWrapper::MakeShaderTemplate( v8::Isolate* isolate )
{
v8::EscapableHandleScope handleScope( isolate );
v8::Local<v8::ObjectTemplate> objTemplate = v8::ObjectTemplate::New();
// property handle intercepts property getters and setters and signals
HandleWrapper::AddInterceptsToTemplate( isolate, objTemplate );
objTemplate->SetInternalFieldCount( BaseWrappedObject::FIELD_COUNT );
return handleScope.Escape( objTemplate );
}
void ShaderWrapper::NewShader( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate);
if(!args.IsConstructCall())
{
DALI_SCRIPT_EXCEPTION( isolate, "Shader constructor called without 'new'");
return;
}
Dali::Shader shader = ShaderApi::New( isolate, args );
if(shader)
{
v8::Local<v8::Object> localObject = WrapShader( isolate, shader );
args.GetReturnValue().Set( localObject );
}
}
Shader ShaderWrapper::GetShader()
{
return mShader;
}
} // namespace V8Plugin
} // namespace Dali
|
[
"r.huang@samsung.com"
] |
r.huang@samsung.com
|
d6ca27eb144a76ea106a53c99c5484ad763fd386
|
34a294504a848c7f8ded96d0abaac08ebd4193e3
|
/sparse_matrix.h
|
8b4bcf1f4ca3b36e72aa843a8dcb1dedb147e239
|
[] |
no_license
|
ma-hei/Fluid-Simulation
|
dbcd1adabf23d92ec08391b592e7f917c1eeada2
|
c129a9da67197e409858c28810f84444c0bc04b1
|
refs/heads/master
| 2021-01-22T07:32:26.278484
| 2017-05-01T00:48:10
| 2017-05-01T00:48:10
| 4,194,245
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,335
|
h
|
#ifndef SPARSE_MATRIX_H
#define SPARSE_MATRIX_H
#include <iostream>
#include <vector>
#include "util.h"
//============================================================================
// Dynamic compressed sparse row matrix.
using namespace std;
template<class T>
struct SparseMatrix
{
unsigned int n; // dimension
std::vector<std::vector<unsigned int> > index; // for each row, a list of all column indices (sorted)
std::vector<std::vector<T> > value; // values corresponding to index
explicit SparseMatrix(unsigned int n_=0, unsigned int expected_nonzeros_per_row=7)
: n(n_), index(n_), value(n_)
{
for(unsigned int i=0; i<n; ++i){
index[i].reserve(expected_nonzeros_per_row);
value[i].reserve(expected_nonzeros_per_row);
}
}
void clear(void)
{
n=0;
index.clear();
value.clear();
}
void zero(void)
{
for(unsigned int i=0; i<n; ++i){
index[i].resize(0);
value[i].resize(0);
}
}
void resize(int n_)
{
n=n_;
index.resize(n);
value.resize(n);
}
T operator()(unsigned int i, unsigned int j) const
{
for(unsigned int k=0; k<index[i].size(); ++k){
if(index[i][k]==j) return value[i][k];
else if(index[i][k]>j) return 0;
}
return 0;
}
void set_element(unsigned int i, unsigned int j, T new_value)
{
unsigned int k=0;
for(; k<index[i].size(); ++k){
if(index[i][k]==j){
value[i][k]=new_value;
return;
}else if(index[i][k]>j){
insert(index[i], k, j);
insert(value[i], k, new_value);
return;
}
}
index[i].push_back(j);
value[i].push_back(new_value);
}
void add_to_element(unsigned int i, unsigned int j, T increment_value)
{
unsigned int k=0;
for(; k<index[i].size(); ++k){
if(index[i][k]==j){
value[i][k]+=increment_value;
return;
}else if(index[i][k]>j){
insert(index[i], k, j);
insert(value[i], k, increment_value);
return;
}
}
index[i].push_back(j);
value[i].push_back(increment_value);
}
// assumes indices is already sorted
void add_sparse_row(unsigned int i, const std::vector<unsigned int> &indices, const std::vector<T> &values)
{
unsigned int j=0, k=0;
while(j<indices.size() && k<index[i].size()){
if(index[i][k]<indices[j]){
++k;
}else if(index[i][k]>indices[j]){
insert(index[i], k, indices[j]);
insert(value[i], k, values[j]);
++j;
}else{
value[i][k]+=values[j];
++j;
++k;
}
}
for(;j<indices.size(); ++j){
index[i].push_back(indices[j]);
value[i].push_back(values[j]);
}
}
// assumes matrix has symmetric structure - so the indices in row i tell us which columns to delete i from
void symmetric_remove_row_and_column(unsigned int i)
{
for(unsigned int a=0; a<index[i].size(); ++a){
unsigned int j=index[i][a]; //
for(unsigned int b=0; b<index[j].size(); ++b){
if(index[j][b]==i){
erase(index[j], b);
erase(value[j], b);
break;
}
}
}
index[i].resize(0);
value[i].resize(0);
}
void write_matlab(std::ostream &output, const char *variable_name)
{
output<<variable_name<<"=sparse([";
for(unsigned int i=0; i<n; ++i){
for(unsigned int j=0; j<index[i].size(); ++j){
output<<i+1<<" ";
}
}
output<<"],...\n [";
for(unsigned int i=0; i<n; ++i){
for(unsigned int j=0; j<index[i].size(); ++j){
output<<index[i][j]+1<<" ";
}
}
output<<"],...\n [";
for(unsigned int i=0; i<n; ++i){
for(unsigned int j=0; j<value[i].size(); ++j){
output<<value[i][j]<<" ";
}
}
output<<"], "<<n<<", "<<n<<");"<<std::endl;
}
};
typedef SparseMatrix<float> SparseMatrixf;
typedef SparseMatrix<double> SparseMatrixd;
// perform result=matrix*x
template<class T>
void multiply(const SparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result)
{
//assert(matrix.n==x.size());
if (matrix.n!=x.size()){
cout<<"assert stuff";
}
result.resize(matrix.n);
for(unsigned int i=0; i<matrix.n; ++i){
result[i]=0;
for(unsigned int j=0; j<matrix.index[i].size(); ++j){
result[i]+=matrix.value[i][j]*x[matrix.index[i][j]];
}
}
}
// perform result=result-matrix*x
template<class T>
void multiply_and_subtract(const SparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result)
{
//assert(matrix.n==x.size());
if (matrix.n!=x.size()){
cout<<"assert stuff";
}
result.resize(matrix.n);
for(unsigned int i=0; i<matrix.n; ++i){
for(unsigned int j=0; j<matrix.index[i].size(); ++j){
result[i]-=matrix.value[i][j]*x[matrix.index[i][j]];
}
}
}
//============================================================================
// Fixed version of SparseMatrix. This is not a good structure for dynamically
// modifying the matrix, but can be significantly faster for matrix-vector
// multiplies due to better data locality.
template<class T>
struct FixedSparseMatrix
{
unsigned int n; // dimension
std::vector<T> value; // nonzero values row by row
std::vector<unsigned int> colindex; // corresponding column indices
std::vector<unsigned int> rowstart; // where each row starts in value and colindex (and last entry is one past the end, the number of nonzeros)
explicit FixedSparseMatrix(unsigned int n_=0)
: n(n_), value(0), colindex(0), rowstart(n_+1)
{}
void clear(void)
{
n=0;
value.clear();
colindex.clear();
rowstart.clear();
}
void resize(int n_)
{
n=n_;
rowstart.resize(n+1);
}
void construct_from_matrix(const SparseMatrix<T> &matrix)
{
resize(matrix.n);
rowstart[0]=0;
for(unsigned int i=0; i<n; ++i){
rowstart[i+1]=rowstart[i]+matrix.index[i].size();
}
value.resize(rowstart[n]);
colindex.resize(rowstart[n]);
unsigned int j=0;
for(unsigned int i=0; i<n; ++i){
for(unsigned int k=0; k<matrix.index[i].size(); ++k){
value[j]=matrix.value[i][k];
colindex[j]=matrix.index[i][k];
++j;
}
}
}
void write_matlab(std::ostream &output, const char *variable_name)
{
output<<variable_name<<"=sparse([";
for(unsigned int i=0; i<n; ++i){
for(unsigned int j=rowstart[i]; j<rowstart[i+1]; ++j){
output<<i+1<<" ";
}
}
output<<"],...\n [";
for(unsigned int i=0; i<n; ++i){
for(unsigned int j=rowstart[i]; j<rowstart[i+1]; ++j){
output<<colindex[j]+1<<" ";
}
}
output<<"],...\n [";
for(unsigned int i=0; i<n; ++i){
for(unsigned int j=rowstart[i]; j<rowstart[i+1]; ++j){
output<<value[j]<<" ";
}
}
output<<"], "<<n<<", "<<n<<");"<<std::endl;
}
};
typedef FixedSparseMatrix<float> FixedSparseMatrixf;
typedef FixedSparseMatrix<double> FixedSparseMatrixd;
// perform result=matrix*x
template<class T>
void multiply(const FixedSparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result)
{
if (matrix.n!=x.size()){
cout<<"assert stuff";
}
result.resize(matrix.n);
for(unsigned int i=0; i<matrix.n; ++i){
result[i]=0;
for(unsigned int j=matrix.rowstart[i]; j<matrix.rowstart[i+1]; ++j){
result[i]+=matrix.value[j]*x[matrix.colindex[j]];
}
}
}
// perform result=result-matrix*x
template<class T>
void multiply_and_subtract(const FixedSparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result)
{
if (matrix.n!=x.size()){
cout<<"assert stuff";
}
result.resize(matrix.n);
for(unsigned int i=0; i<matrix.n; ++i){
for(unsigned int j=matrix.rowstart[i]; j<matrix.rowstart[i+1]; ++j){
result[i]-=matrix.value[j]*x[matrix.colindex[j]];
}
}
}
#endif
|
[
"marten_heidemeyer@web.de"
] |
marten_heidemeyer@web.de
|
f9ec2b82ce740c09121b98180028ff0331e40c10
|
39eac74fa6a244d15a01873623d05f480f45e079
|
/PackageUseSelectionDlg.h
|
f400301599d944a066eeaf5ccad419b24c110fc3
|
[] |
no_license
|
15831944/Practice
|
a8ac8416b32df82395bb1a4b000b35a0326c0897
|
ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94
|
refs/heads/master
| 2021-06-15T12:10:18.730367
| 2016-11-30T15:13:53
| 2016-11-30T15:13:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,949
|
h
|
#if !defined(AFX_PACKAGEUSESELECTIONDLG_H__CF3B3301_44EE_411F_BD52_68DD1866FF7C__INCLUDED_)
#define AFX_PACKAGEUSESELECTIONDLG_H__CF3B3301_44EE_411F_BD52_68DD1866FF7C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// PackageUseSelectionDlg.h : header file
//
// (j.jones 2008-05-22 11:44) - PLID 28450 - added a proper memory object
struct PackageChargeObject {
long nPackageChargeID;
long nServiceID;
double dblQuantity;
};
/////////////////////////////////////////////////////////////////////////////
// CPackageUseSelectionDlg dialog
class CPackageUseSelectionDlg : public CNxDialog
{
// Construction
public:
CPackageUseSelectionDlg(CWnd* pParent); // standard constructor
~CPackageUseSelectionDlg();
NXDATALISTLib::_DNxDataListPtr m_PackageList;
long m_nQuoteID;
// (j.jones 2008-05-22 11:44) - PLID 28450 - added a new package charge array
// that replaced the old service & quantity arrays
CArray<PackageChargeObject*, PackageChargeObject*> m_arypPackageCharges;
BOOL m_bPackageIsUsedUp;
// (j.jones 2007-03-26 14:37) - PLID 25287 - used to determine if we need to
// offset our bill amount to match the remaining package amount
COleCurrency m_cyMatchRemainingPackageAmount;
//used with the above to determine which service ID to assign the matched amount to
// (j.jones 2011-02-03 09:12) - PLID 42291 - changed to calculate the package charge ID, not service ID
long m_nMatchRemAmountToChargeID;
// Dialog Data
//{{AFX_DATA(CPackageUseSelectionDlg)
enum { IDD = IDD_PACKAGE_USE_SELECTION_DLG };
CNxIconButton m_btnOK;
CNxIconButton m_btnCancel;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPackageUseSelectionDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// (j.jones 2008-05-22 11:45) - PLID 28450 - this function will properly clear m_arypPackageCharges
void ClearPackageChargeArray();
// Generated message map functions
//{{AFX_MSG(CPackageUseSelectionDlg)
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnEditingStartingPackageList(long nRow, short nCol, VARIANT FAR* pvarValue, BOOL FAR* pbContinue);
afx_msg void OnEditingFinishingPackageList(long nRow, short nCol, const VARIANT FAR& varOldValue, LPCTSTR strUserEntered, VARIANT FAR* pvarNewValue, BOOL FAR* pbCommit, BOOL FAR* pbContinue);
afx_msg void OnEditingFinishedPackageList(long nRow, short nCol, const VARIANT FAR& varOldValue, const VARIANT FAR& varNewValue, BOOL bCommit);
afx_msg void OnRequeryFinishedPackageList(short nFlags);
DECLARE_EVENTSINK_MAP()
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PACKAGEUSESELECTIONDLG_H__CF3B3301_44EE_411F_BD52_68DD1866FF7C__INCLUDED_)
|
[
"h.shah@WALD"
] |
h.shah@WALD
|
30977a359a1ec3d2a8d22558ba241055d33576c6
|
97ce80e44d5558cad2ca42758e2d6fb1805815ce
|
/Source/Foundation/bsfCore/Private/RTTI/BsTextureImportOptionsRTTI.h
|
7768ee9af0c4a8186dcac219393fa1bdbe4d2aa9
|
[
"MIT"
] |
permissive
|
cwmagnus/bsf
|
ff83ca34e585b32d909b3df196b8cf31ddd625c3
|
36de1caf1f7532d497b040d302823e98e7b966a8
|
refs/heads/master
| 2020-12-08T00:53:11.021847
| 2020-03-23T22:05:24
| 2020-03-23T22:05:24
| 232,839,774
| 3
| 0
|
MIT
| 2020-01-09T15:26:22
| 2020-01-09T15:26:21
| null |
UTF-8
|
C++
| false
| false
| 1,284
|
h
|
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "BsCorePrerequisites.h"
#include "Reflection/BsRTTIType.h"
#include "Reflection/BsRTTIPlain.h"
#include "Importer/BsTextureImportOptions.h"
namespace bs
{
/** @cond RTTI */
/** @addtogroup RTTI-Impl-Core
* @{
*/
class BS_CORE_EXPORT TextureImportOptionsRTTI : public RTTIType<TextureImportOptions, ImportOptions, TextureImportOptionsRTTI>
{
private:
BS_BEGIN_RTTI_MEMBERS
BS_RTTI_MEMBER_PLAIN(format, 0)
BS_RTTI_MEMBER_PLAIN(generateMips, 1)
BS_RTTI_MEMBER_PLAIN(maxMip, 2)
BS_RTTI_MEMBER_PLAIN(cpuCached, 3)
BS_RTTI_MEMBER_PLAIN(sRGB, 4)
BS_RTTI_MEMBER_PLAIN(cubemap, 5)
BS_RTTI_MEMBER_PLAIN(cubemapSourceType, 6)
BS_END_RTTI_MEMBERS
public:
const String& getRTTIName() override
{
static String name = "TextureImportOptions";
return name;
}
UINT32 getRTTIId() override
{
return TID_TextureImportOptions;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<TextureImportOptions>();
}
};
/** @} */
/** @endcond */
}
|
[
"bearishsun@gmail.com"
] |
bearishsun@gmail.com
|
32262cdbe0cf52960edff93162aba3e1488c2879
|
0fed3d6c4a6dbdb49029913b6ce96a9ede9eac6c
|
/Codeforces/861/861B.cpp
|
3ddb69585855ee7e19f52b3c9aaddddcdfb7801b
|
[] |
no_license
|
87ouo/The-road-to-ACMer
|
72df2e834027dcfab04b02ba0ddd350e5078dfc0
|
0a39a9708a0e7fd0e3b2ffff5d1f4a793b031df5
|
refs/heads/master
| 2021-02-18T17:44:29.937434
| 2019-07-31T11:30:27
| 2019-07-31T11:30:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,516
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define clr(a, x) memset(a, x, sizeof(a))
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define X first
#define Y second
#define fastin \
ios_base::sync_with_stdio(0); \
cin.tie(0);
typedef long long ll;
typedef long double ld;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-6;
PII a[105];
int main()
{
int n, m;
while (cin >> n >> m)
{
int ans = -1;
for (int i = 0; i < m; i++)
{
cin >> a[i].X >> a[i].Y;
a[i].X--, a[i].Y--;
}
if (n == 1)
{
cout << 1 << endl;
continue;
}
n--;
for (int i = 1; i <= 100; i++)
{
// cout << "i = " << i << endl;
bool flag = 0;
for (int j = 0; j < m; j++)
{
int k = a[j].X / i;
// cout << k << " " << a[j].Y << endl;
if (k != a[j].Y)
{
flag = 1;
break;
}
}
if (!flag)
{
int tmp = n / i + 1;
if (ans == -1)
ans = tmp;
else if (ans != tmp)
{
ans = -1;
break;
}
}
}
cout << ans << endl;
}
return 0;
}
|
[
"zbszx040504@126.com"
] |
zbszx040504@126.com
|
fecc04712635d9a33293026ccbdb4cbe918a984a
|
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
|
/out/release/gen/content/common/field_trial_recorder.mojom.h
|
213394e05ba5bbbce6e6af16cefacdaa54b34876
|
[
"BSD-3-Clause"
] |
permissive
|
xueqiya/chromium_src
|
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
|
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
|
refs/heads/main
| 2022-07-30T03:15:14.818330
| 2021-01-16T16:47:22
| 2021-01-16T16:47:22
| 330,115,551
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,635
|
h
|
// content/common/field_trial_recorder.mojom.h is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2013 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.
#ifndef CONTENT_COMMON_FIELD_TRIAL_RECORDER_MOJOM_H_
#define CONTENT_COMMON_FIELD_TRIAL_RECORDER_MOJOM_H_
#include <stdint.h>
#include <limits>
#include <type_traits>
#include <utility>
#include "base/callback.h"
#include "base/macros.h"
#include "base/optional.h"
#include "mojo/public/cpp/bindings/mojo_buildflags.h"
#if BUILDFLAG(MOJO_TRACE_ENABLED)
#include "base/trace_event/trace_event.h"
#endif
#include "mojo/public/cpp/bindings/clone_traits.h"
#include "mojo/public/cpp/bindings/equals_traits.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
#include "mojo/public/cpp/bindings/union_traits.h"
#include "content/common/field_trial_recorder.mojom-shared.h"
#include "content/common/field_trial_recorder.mojom-forward.h"
#include <string>
#include <vector>
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr_info.h"
#include "mojo/public/cpp/bindings/associated_interface_request.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/lib/control_message_handler.h"
#include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h"
#include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
#include "content/common/content_export.h"
namespace content {
namespace mojom {
class FieldTrialRecorderProxy;
template <typename ImplRefTraits>
class FieldTrialRecorderStub;
class FieldTrialRecorderRequestValidator;
class CONTENT_EXPORT FieldTrialRecorder
: public FieldTrialRecorderInterfaceBase {
public:
static const char Name_[];
static constexpr uint32_t Version_ = 0;
static constexpr bool PassesAssociatedKinds_ = false;
static constexpr bool HasSyncMethods_ = false;
using Base_ = FieldTrialRecorderInterfaceBase;
using Proxy_ = FieldTrialRecorderProxy;
template <typename ImplRefTraits>
using Stub_ = FieldTrialRecorderStub<ImplRefTraits>;
using RequestValidator_ = FieldTrialRecorderRequestValidator;
using ResponseValidator_ = mojo::PassThroughFilter;
enum MethodMinVersions : uint32_t {
kFieldTrialActivatedMinVersion = 0,
};
virtual ~FieldTrialRecorder() {}
virtual void FieldTrialActivated(const std::string& trial_name) = 0;
};
class CONTENT_EXPORT FieldTrialRecorderProxy
: public FieldTrialRecorder {
public:
using InterfaceType = FieldTrialRecorder;
explicit FieldTrialRecorderProxy(mojo::MessageReceiverWithResponder* receiver);
void FieldTrialActivated(const std::string& trial_name) final;
private:
mojo::MessageReceiverWithResponder* receiver_;
};
class CONTENT_EXPORT FieldTrialRecorderStubDispatch {
public:
static bool Accept(FieldTrialRecorder* impl, mojo::Message* message);
static bool AcceptWithResponder(
FieldTrialRecorder* impl,
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder);
};
template <typename ImplRefTraits =
mojo::RawPtrImplRefTraits<FieldTrialRecorder>>
class FieldTrialRecorderStub
: public mojo::MessageReceiverWithResponderStatus {
public:
using ImplPointerType = typename ImplRefTraits::PointerType;
FieldTrialRecorderStub() {}
~FieldTrialRecorderStub() override {}
void set_sink(ImplPointerType sink) { sink_ = std::move(sink); }
ImplPointerType& sink() { return sink_; }
bool Accept(mojo::Message* message) override {
if (ImplRefTraits::IsNull(sink_))
return false;
return FieldTrialRecorderStubDispatch::Accept(
ImplRefTraits::GetRawPointer(&sink_), message);
}
bool AcceptWithResponder(
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override {
if (ImplRefTraits::IsNull(sink_))
return false;
return FieldTrialRecorderStubDispatch::AcceptWithResponder(
ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder));
}
private:
ImplPointerType sink_;
};
class CONTENT_EXPORT FieldTrialRecorderRequestValidator : public mojo::MessageReceiver {
public:
bool Accept(mojo::Message* message) override;
};
} // namespace mojom
} // namespace content
namespace mojo {
} // namespace mojo
#endif // CONTENT_COMMON_FIELD_TRIAL_RECORDER_MOJOM_H_
|
[
"xueqi@zjmedia.net"
] |
xueqi@zjmedia.net
|
9cd0d406c0ed531aaa5cd49dc730b034f51d0ee2
|
b012cd346ca2a31bc3b3bb145d8e89bd71c7ccdc
|
/NFS/server.h
|
d3d333960ef80a3545d75d4a90dcebbf532af9e2
|
[] |
no_license
|
Natfeitosa/IPFS_Network
|
cc0918922ea8a6075e4eda211d4a998c903251ac
|
000943116b4c6e7a04bfdc4e47e03d38e07c872d
|
refs/heads/main
| 2023-05-08T01:46:14.213336
| 2021-05-25T13:14:06
| 2021-05-25T13:14:06
| 369,966,787
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,937
|
h
|
#ifndef SERVER
#define SERVER
#include <iostream>
#include <stdio.h>
#include "filesys.h"
#include <vector>
#include "header.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <Windows.h>
#include <iphlpapi.h>
#define DEFAULT_PORT "27015"
#define BUFFER_SIZE 1024
#pragma comment(lib,"Ws2_32.lib")
/*
IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE
When using the class you must Bind and set the server to listen, before requesting to receive info
public:
void Create_server()-
void Listen()
void Bind()
char *Receive_Msg()
Proposed chages:
stadby()- this is where we might have select() and allow for multiple connections, then create a table
where you can determine the reason for connection, if its to be on standby or if its to send message etc.
FD will keep track of the clients since i am not using threads.
List of addresses will keep track of where the server is located to send data.
For recieving data, just listen to the port and wait for someone to connect.
type of messages that will be recieved:
-UPDATE
-NEW FILE
*/
/*
THINGS NEED TO BE DONE:
CREATE RESEND FILE IF CONNECTION FAILS
CREATE TIMEOUT FOR DDOS ATTACKS OR FAILED CONNECTIONS
*/
class Server
{
public:
Server();
char *Receive_Msg(); //Function to practice sending messages
std::string Stand_by(); //To find what type of operation the client_socket wants the server to peform
//std::string Read_file();// Recieves the name of the file the client_socket wants
void Send_file(std::string &file); // Sends the file the client_socket wants
std::string Get_filename(); //Gets the name of the File it is meant to create
std::string Get_Content(); //Gets the Content of the file
void Close_connection();
bool Get_handshake();
void Server_init();
private:
fd_set readio;
vector<SOCKET> client_list;//This will hold onto all the clients it connected to
SOCKET server_socket;
SOCKET client_socket;
bool handshake_;
SOCKET active_client;
int iResult;
char buffer[BUFFER_SIZE]={0};
int buffer_size=BUFFER_SIZE;
struct addrinfo *result=NULL,*ptr=NULL,hints;
void Clear_buffer();
void Bind(); //Binds the server to a PORT
void Listen(); //Listens for incoming sockets
void Create_Server(); //Creates the server socket
void Remove_socket(SOCKET peer);
void Handshake()
{
printf("staring Handshake...\n");
Header clienth;
Header serverh;
iResult = recv(client_socket, (char*)&clienth, sizeof(clienth), 0);
if (clienth.syn == 1 )
{
serverh.ack = 1;
serverh.syn = 1;
iResult = send(client_socket, (char*)&serverh, sizeof(serverh), 0);
iResult = recv(client_socket, (char*)&clienth, sizeof(clienth), 0);
if (clienth.ack == 1)
{
printf("it worked!\n");
handshake_=true;
}
else {
printf("it Failed!\n");
handshake_ = false;
}
}
else {
printf("it Failed!\n");
handshake_ = false;
}
}
};
Server::Server()
{
WSADATA wsaData;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
printf("WSASstartup failed: %d\n", iResult);
}
}
void Server::Create_Server()
{
printf("Creating Server\n");
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult !=0 )
{
printf("getaddinfo failed: %d\n", iResult);
WSACleanup();
return;
}
server_socket = INVALID_SOCKET;//this is the int for the socket
server_socket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if(server_socket==INVALID_SOCKET){
printf("failed to create socket\n");
}
printf("Created Server\n");
}
void Server::Bind()
{
iResult = bind(server_socket, result->ai_addr, (int)result->ai_addrlen);
if(iResult == SOCKET_ERROR)
{
printf("failed to bind the socket: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(server_socket);
WSACleanup();
return;
}
printf("Binded Server\n");
//freeaddrinfo(result);
}
void Server::Listen()
{
printf("Listening for connections...\n");
if(listen(server_socket,SOMAXCONN) == SOCKET_ERROR)
{
printf("Error with listening : %d\n", WSAGetLastError());
closesocket(server_socket);
WSACleanup();
//return EXIT_FAILURE;
}
}
char* Server::Receive_Msg()
{
int Sendresults;
iResult = recv(client_socket, buffer, buffer_size, 0);
if (iResult > 0) {
Sendresults = send(client_socket, buffer, buffer_size, 0);
if (Sendresults == SOCKET_ERROR) {
printf("Error sending things to client_socket: %d\n", WSAGetLastError());
closesocket(client_socket);
WSACleanup();
//return EXIT_FAILURE;
}
}
else if (iResult == 0)
printf("Connection over\n");
else {
printf("Failed to recieve message from client_socket: %d\n", WSAGetLastError());
closesocket(client_socket);
WSACleanup();
return buffer;
}
printf("Message from server is: %s\n", buffer);
return buffer;
}
std::string Server::Stand_by()
{ // This is meant to recieve commands from the client_socket about operations
while (TRUE)
{
FD_ZERO(&readio);
FD_SET(server_socket, &readio);
SOCKET max_sd = server_socket;
//std::cout<<"client size is: "<<client_list.size()<<std::endl;
for (int i = 0; i < client_list.size(); i++)
{
SOCKET sd = client_list[i];
if (sd > 0)
{
FD_SET(sd, &readio);
if (sd > max_sd)
{
max_sd = sd;
}
}
}
Header serverh;
Header clienth;
int activity = select(max_sd + 1, &readio, NULL, NULL, NULL);
if (FD_ISSET(server_socket, &readio)) {//Connects new clients since FD_SET is listening for connections
client_socket = accept(server_socket, NULL, NULL);//Connects the client, that is now on the client list
std::cout << "Connecting socket:\t" << client_socket << std::endl;
if (client_socket == SOCKET_ERROR)
{
printf("Error accepting client: %d\n", WSAGetLastError());
closesocket(client_socket);
WSACleanup();
return "";
}
Handshake();
if (handshake_ == false) {std::cout<<"handshake failed\n"; Close_connection(); }
handshake_=false;
client_list.push_back(client_socket);
}
if (client_socket == INVALID_SOCKET) { std::cout << "Socket is invalid\n"; }
else
{
for (int i=0;i<client_list.size();i++)
{
//std::cout << i << std::endl;
char buff[BUFFER_SIZE] = { 0 };
SOCKET peer=client_list[i];
if (FD_ISSET(peer,&readio))
{
iResult = recv(peer, buff, buffer_size, 0); // recieves the operation READ/Write
if (iResult == SOCKET_ERROR) {
std::cout << "Connection closed, disconnection socket: " << peer << std::endl;
Remove_socket(peer);
closesocket(peer);
break;
}
std::cout << "Recieved command from\t" << peer << std::endl;
printf("Message is: %s\n", buff);
/*if(iResult==SOCKET_ERROR){
printf("Error sending things to client_socket: %d\n", WSAGetLastError());
}*/
serverh.ack = 1;
iResult = send(peer, (char*)&serverh, sizeof(serverh), 0);//Sends ack that recieved operation
if (!strcmp(buff, "read"))//Informs the main.cpp that client wants read command
{
client_socket=peer;
Clear_buffer();
return "read";
}
else if (!strcmp(buff, "write"))
{
client_socket=peer;
Clear_buffer();
return "write";
}
else if (!strcmp(buff, "list")) {
client_socket=peer;
return "list";
}
}
}
}
}
}
void Server::Remove_socket(SOCKET peer){
vector<SOCKET> temp;
for (SOCKET i : client_list) {
if (i != peer) {
temp.push_back(i);
}
}
client_list.clear();
client_list = temp;
}
/*
std::string Server::Read_file() //This is meant to be used to recieve the name of the file the client_socket wants.
{
Header serverh;
Clear_buffer();
//wait for files name
iResult=recv(client_socket,buffer,buffer_size,0);//Name of the file client wants to read
if(iResult==0)
{
printf("failed to recieve filesname\n");
std::string empty="";
Clear_buffer();
return empty;
}
serverh.ack=1;
iResult=send(client_socket,(char*)&serverh,sizeof(serverh),0);//Sends the client ack that recieved the name of the file
std::string filename(buffer);
Clear_buffer();
return filename;
}*/
void Server::Clear_buffer(){
for(int i=0;i<buffer_size;i++){
buffer[i]=0;
}
}
void Server::Send_file(std::string &file){ //Send the file to the client_socket once it finds it
Header serverh;
Header clienth;
std::cout<<file<<std::endl;
const char* message = file.c_str();
iResult=send(client_socket,message,(int)strlen(message),0);//Might have to loop to send it all
/*if(iResult==SOCKET_ERROR){
printf("Error sending things to client_socket: %d\n", WSAGetLastError());
}*/
iResult=recv(client_socket,(char*)&clienth,sizeof(clienth),0);//Waits for ack from client that it recieved the file
/*if(iResult==SOCKET_ERROR){
printf("Error recv things to client_socket: %d\n", WSAGetLastError());
}*/
if(clienth.ack==1){
printf("Client recieved data!\n");
}
else
{
printf("Client failed to recieve file\n");
}
}
std::string Server::Get_filename()
{
Header serverh;
Clear_buffer();
iResult=recv(client_socket,buffer,buffer_size,0);//Recives the Name of the File it will create
serverh.ack=1;
iResult=send(client_socket,(char*)&serverh,sizeof(serverh),0);//sends client ack that recieved the name of the file
std::string filename(buffer);
return filename;
}
std::string Server::Get_Content(){//Create a protocol to see check the size of content, in case content is bigger than BUFFER_SIZE
Header serverh;
Clear_buffer();
iResult=recv(client_socket,buffer,buffer_size,0);//Receives the content it is meant to put into the file. This might have to be looped if contet is to big
serverh.ack=1;
iResult=send(client_socket,(char*)&serverh,sizeof(serverh),0);//Sends client ACK that recieved all the contents of the files
std::string content(buffer);
return content;
}
void Server::Close_connection(){
closesocket(client_socket);
printf("Connection closed\n");
}
bool Server::Get_handshake() {
return handshake_;
}
void Server::Server_init(){
Create_Server();
Bind();
Listen();
}
#endif
|
[
"noreply@github.com"
] |
Natfeitosa.noreply@github.com
|
8bef19a548752d87346034296fc3a45d6fdefd0a
|
df13301ec4a28fbbdd85783fa093c58686dc4a85
|
/test/vecAdd_5.h
|
6ac225db3f6b922e6f641828e103db57f7316628
|
[] |
no_license
|
cjatin/tlib
|
3d0631b938035bb3b59148f2ffee7e9228691046
|
a45e8a80fd48a2dc7ca75e6100f9573228cdc626
|
refs/heads/master
| 2020-10-01T16:58:15.034497
| 2019-12-20T05:17:19
| 2019-12-20T05:17:19
| 227,581,470
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 347
|
h
|
#include "tlib.h"
#include <benchmark/benchmark.h>
static void vecAdd_5(benchmark::State& state) {
// Perform setup here
for (auto _ : state) {
// This code gets timed
std::vector<int> a = {1, 2, 3, 4, 5};
auto b = a;
std::vector<int> c;
vecAdd(a, b, c);
}
}
// Register the function as a benchmark
BENCHMARK(vecAdd_5);
|
[
"Jatin.Chaudhary@amd.com"
] |
Jatin.Chaudhary@amd.com
|
8c5c91c639b41e31d86fca6f46b1bb9eb7612c85
|
a6ed6ea5ebe14517e0ce1a9b7ba293b481cc1abe
|
/prog_lab_4_2/Tree.h
|
71eb736a4238a3105dac80ab394d6639deb200b1
|
[] |
no_license
|
RadiationX/ClionProjects
|
320c1e5a1be613d5d260b6c75b55da2d097f5011
|
3695271d84acd7a337e36930ed3fd4b455095030
|
refs/heads/master
| 2021-05-15T01:11:23.300882
| 2017-06-14T23:46:32
| 2017-06-14T23:46:32
| 56,440,201
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,853
|
h
|
//
// Created by radiationx on 10.05.17.
//
#ifndef PROG_LAB_4_2_TREE_H
#define PROG_LAB_4_2_TREE_H
#include "iostream"
using namespace std;
struct Node {
int value;
int size = 0;
Node *nodes = NULL;
};
class Tree {
private:
Node root;
int capacity = 0;
void add(Node &root, int value) {
if (root.nodes == NULL) {
root.nodes = new Node[capacity];
}
if (root.size < capacity) {
root.nodes[root.size].value = value;
root.size++;
} else {
int minIndex = 0;
for (int i = 1; i < capacity; i++) {
if (root.nodes[minIndex].size != root.nodes[i].size) {
minIndex = i;
break;
}
}
add(root.nodes[minIndex], value);
}
}
void printTree(Node &root, int level) {
for (int j = 0; j < level; j++) {
if (j == level - 1) {
cout << "+---";
} else {
cout << "| ";
}
}
cout << root.value << endl;
for (int i = 0; i < root.size; i++) {
level++;
printTree(root.nodes[i], level);
level--;
}
}
int sum(Node &root) {
int res = 0;
res += root.value;
for (int i = 0; i < root.size; i++) {
res += sum(root.nodes[i]);
}
return res;
}
public:
Tree(int capacity) {
this->capacity = capacity;
root.value = 0;
}
void add(int value) {
add(root, value);
}
void printTree() {
cout << "TREE:" << endl;
printTree(root, 0);
}
int sum() {
int res = sum(root);
cout << "SUM VALUES: " << res << endl;
return res;
}
};
#endif //PROG_LAB_4_2_TREE_H
|
[
"radiationx@yandex.ru"
] |
radiationx@yandex.ru
|
1c9194558fea4344eb438dacc2106281781a7499
|
0399fff8bacf9e54442f7166a0561a7089cce1fe
|
/src/mmo/ast/composition.h
|
cc773f5f0f708a0582823e6529488edb9bec69e0
|
[] |
no_license
|
mascha/qss-engine
|
a2a2b63703094becba5b31975092ca8985916601
|
0ff943707b1bc952b2f5e866c8bf27ffb98de5f2
|
refs/heads/master
| 2021-06-17T22:35:17.470498
| 2017-05-19T13:33:42
| 2017-05-19T13:33:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,906
|
h
|
/*****************************************************************************
This file is part of QSS Solver.
QSS Solver is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QSS Solver 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 QSS Solver. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#ifndef AST_COMPOSITION_H_
#define AST_COMPOSITION_H_
#include <string>
#include "../util/macros.h"
#include "../util/util_types.h"
#include "ast_node.h"
#include "ast_types.h"
class AST_CompositionElement_;
using namespace std;
/**
*
*/
class AST_Composition_ : public AST_Node_
{
public:
/**
*
* @param el
* @param cl
*/
AST_Composition_ (AST_ElementList el, AST_CompositionElementList cl);
/**
*
*/
DEFINE_CLASS_PRINTER(AST_Composition)
;
/**
*
* @return
*/
AST_CompositionElementList
compositionList () const;
/**
*
* @return
*/
bool
hasCompositionList ();
/**
*
* @return
*/
AST_ElementList
elementList () const;
/**
*
* @return
*/
bool
hasElementList ();
/**
*
* @param
*/
void
setExternalFunctionCall (AST_External_Function_Call);
/**
*
* @return
*/
AST_External_Function_Call
externalCall () const;
/**
*
* @return
*/
bool
hasExternalFunctionCall ();
/**
*
* @param
*/
void
setAnnotation (AST_ArgumentList);
/**
*
* @return
*/
bool
hasAnnotation ();
/**
*
* @param visitor
*/
void
accept (AST_Visitor visitor);
private:
AST_CompositionElementList _composition_list;
AST_ElementList _element_list;
AST_ArgumentList _annot;
AST_External_Function_Call _ext;
};
/**
*
*/
class AST_CompositionElement_ : public AST_Node_
{
public:
/**
*
* @param eqs_algs
*/
AST_CompositionElement_ (AST_CompositionEqsAlgs eqs_algs);
/**
*
* @param el
*/
AST_CompositionElement_ (AST_ElementList el);
/**
*
*/
DEFINE_CLASS_PRINTER(AST_CompositionElement)
;
/**
*
* @return
*/
AST_CompositionEqsAlgs
getEquationsAlgs ();
/**
*
* @return
*/
AST_ElementList
getElementList ();
/**
*
* @return
*/
bool
hasEquations ();
/**
*
* @return
*/
bool
hasStatements ();
/**
*
* @return
*/
bool
hasElements ();
/**
*
* @param visitor
*/
void
accept (AST_Visitor visitor);
private:
AST_CompositionEqsAlgs _eqs_algs;
AST_ElementList _el;
};
/**
*
*/
class AST_CompositionEqsAlgs_ : public AST_Node_
{
public:
/**
* @param eq
*/
AST_CompositionEqsAlgs_ (AST_EquationList eq);
/**
*
* @param st
*/
AST_CompositionEqsAlgs_ (AST_StatementList st);
/**
*
* @param st
* @param initial
*/
AST_CompositionEqsAlgs_ (AST_StatementList st, bool initial);
/**
*
* @param eq
* @param initial
*/
AST_CompositionEqsAlgs_ (AST_EquationList eq, bool initial);
/**
*
* @return
*/
AST_EquationList
getEquations ();
/**
*
* @return
*/
AST_StatementList
getAlgorithms ();
/**
*
* @return
*/
bool
isInitial ();
/**
*
* @return
*/
bool
hasEquations ();
/**
*
* @return
*/
bool
hasStatements ();
/**
*
* @param visitor
*/
void
accept (AST_Visitor visitor);
private:
bool _initial;
AST_EquationList _eq;
AST_StatementList _st;
};
/**
*
*/
class AST_External_Function_Call_ : public AST_Node_
{
public:
/**
*
* @param
* @param
* @param
* @param
*/
AST_External_Function_Call_ (AST_String, AST_Expression_ComponentReference,
AST_Expression, AST_ArgumentList);
/**
*
* @return
*/
AST_String
language ();
/**
*
* @return
*/
string
languageString ();
/**
*
* @return
*/
AST_ArgumentList
annotation ();
/**
*
* @return
*/
AST_ExpressionList
args ();
/**
*
* @return
*/
string
name ();
/**
*
* @return
*/
AST_Expression
exp ();
/**
*
* @return
*/
AST_Expression_ComponentReference
componentReference ();
/**
*
* @return
*/
bool
hasComponentReference ();
/**
*
* @param visitor
*/
void
accept (AST_Visitor visitor);
private:
AST_String _lang;
AST_ArgumentList _annot;
AST_Expression_Call _call;
AST_Expression _exp;
AST_Expression_ComponentReference _cr;
};
#endif /* AST_COMPOSITION_H_ */
|
[
"joaquin.f.fernandez@gmail.com"
] |
joaquin.f.fernandez@gmail.com
|
be6b224ee8ab0a36fea49e00d7e1df0a05418438
|
9627bdbd6f366de38685fe674cbcbda673127614
|
/src/shapes.cpp
|
7eba2d66b83654f4ab4fa568a88ba10cc6e099ef
|
[
"MIT"
] |
permissive
|
hermetikos/OpenGL-Cross-Platform-Benchmark
|
31ce1e9f536e45d480da66ae69d99778e264ad7e
|
4ed4017401aa6f072059f0d7d61933500427895b
|
refs/heads/master
| 2021-10-08T14:23:10.479886
| 2018-12-13T06:44:29
| 2018-12-13T06:44:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,691
|
cpp
|
/*
This file is part of OpenGL-Cross-Platform-Benchmark which is released under the MIT License.
Copyright Stan Slupecki 2018
Go to https://misturdust319.github.io/OpenGL-Cross-Platform-Benchmark/ for full license details.
*/
#include <GLBenchmark/shapes.h>
#include <vector>
// using these objects
// create a new shape
// init it
// use draw to render it
//constructor
Shape::Shape(const glm::vec3 origin) {
// set the buffers to ID
// VAO = VBO = EBO = ID;
// set origin
setOrigin(origin);
}
void Shape::init() {
// generate and bind buffers
glGenVertexArrays(1, &VAO); // VAO
glGenBuffers(1, &VBO); // VBO
glGenBuffers(1, &EBO); // EBO
// 1. bind VAO
bindVAO();
// 2. bind then copy verts into vertex buffer
initVBO();
// 3. bind then copy inidices into index buffer
initEBO();
// 4. set vertex attribute pointers
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
}
void Shape::bindVAO() {
glBindVertexArray(VAO);
}
void Shape::initVBO() {
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * getNumberVertices(),
getVertices(), GL_STATIC_DRAW);
}
void Shape::initEBO() {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * getNumberIndices(),
getIndices(), GL_STATIC_DRAW);
}
void Shape::draw() {
// ensure this Shape's VAO is bound
bindVAO();
// init(); // init the shape
glDrawElements(GL_TRIANGLES, getNumberIndices(), GL_UNSIGNED_INT, 0);
// glDrawArrays(GL_TRIANGLES, 0, getNumberVertices());
glBindVertexArray(0);
}
// set the vertices to an existing vertex of vertices
void Shape::setVertices(const std::vector<float>& verts) {
vertices = verts;
}
// set the vertices to array of floats
void Shape::setVertices(const float* verts, const int size) {
for (int i = 0; i < size; i++) {
this->vertices.emplace_back(verts[i]);
}
}
void Shape::setIndices(const unsigned int* indices, const int size) {
for (int i = 0; i < size; i++) {
this->indices.emplace_back(indices[i]);
}
}
int Shape::getNumberVertices() {
return vertices.size();
}
int Shape::getNumberIndices() {
return indices.size();
}
void Shape::setOrigin(const glm::vec3& shapeOrigin) {
origin = shapeOrigin;
}
void Shape::setOrigin(float x, float y, float z) {
origin = glm::vec3(x, y, z);
}
glm::vec3 Shape::getOrigin() {
return origin;
}
float* Shape::getVertices() {
// return vector as array
return &vertices[0];
}
unsigned int* Shape::getIndices() {
// return vector as array
return &indices[0];
}
|
[
"sslup@hermetikos.com"
] |
sslup@hermetikos.com
|
21081b430aa51807140ffe7b2cbc95f5dc7db02d
|
cb9c91c777c85404c89a5168f50119493d0280c5
|
/tests/unsigned_map.cpp
|
94b45cf628304127f8852a6515eb3ed3b76a741c
|
[
"BSD-3-Clause"
] |
permissive
|
p-groarke/fea_unsigned_map
|
dde1a574988e07d3fb458651a59e0b7719daa118
|
aab5ddeac7a71845a5f160bb69fc32e03cd281ee
|
refs/heads/master
| 2021-11-18T02:18:21.190488
| 2021-08-01T22:10:04
| 2021-08-01T22:10:04
| 199,511,416
| 3
| 0
|
BSD-3-Clause
| 2020-10-02T21:02:35
| 2019-07-29T19:03:20
|
C++
|
UTF-8
|
C++
| false
| false
| 8,916
|
cpp
|
#include <fea_unsigned_map/fea_unsigned_map.hpp>
#include <gtest/gtest.h>
#include <memory>
#include <unordered_map>
namespace {
struct test {
test() = default;
~test() = default;
test(const test&) = default;
test(test&&) = default;
test& operator=(const test&) = default;
test& operator=(test&&) = default;
test(size_t v)
: val(v) {
}
size_t val = 42;
};
bool operator==(const test& lhs, const test& rhs) {
return lhs.val == rhs.val;
}
bool operator!=(const test& lhs, const test& rhs) {
return !operator==(lhs, rhs);
}
TEST(unsigned_map, basics) {
constexpr size_t small_num = 10;
fea::unsigned_map<size_t, test> map1{ small_num };
map1.reserve(100);
EXPECT_EQ(map1.capacity(), 100u);
map1.shrink_to_fit();
EXPECT_EQ(map1.capacity(), 0u);
EXPECT_TRUE(map1.empty());
EXPECT_EQ(map1.size(), 0u);
EXPECT_FALSE(map1.contains(1));
EXPECT_EQ(map1.count(1), 0u);
map1.clear();
EXPECT_TRUE(map1.empty());
EXPECT_EQ(map1.size(), 0u);
EXPECT_FALSE(map1.contains(1));
EXPECT_EQ(map1.count(1), 0u);
for (size_t i = 0; i < small_num; ++i) {
auto ret_pair = map1.insert({ i, { i } });
EXPECT_TRUE(ret_pair.second);
EXPECT_EQ(ret_pair.first->second, test{ i });
}
for (size_t i = 0; i < small_num; ++i) {
auto ret_pair = map1.insert({ i, { i } });
EXPECT_FALSE(ret_pair.second);
EXPECT_EQ(ret_pair.first->second, test{ i });
}
for (size_t i = 0; i < small_num; ++i) {
test t{ i };
auto ret_pair = map1.insert({ i, t });
EXPECT_FALSE(ret_pair.second);
EXPECT_EQ(ret_pair.first->second, t);
}
fea::unsigned_map<size_t, test> map2{ map1 };
fea::unsigned_map<size_t, test> map_ded{ map1 };
fea::unsigned_map<size_t, test> map3{ std::move(map_ded) };
EXPECT_EQ(map1, map2);
EXPECT_EQ(map1, map3);
EXPECT_EQ(map1.max_size(), map2.max_size());
EXPECT_EQ(map1.max_size(), map3.max_size());
EXPECT_EQ(map1.size(), small_num);
EXPECT_EQ(map2.size(), small_num);
EXPECT_EQ(map3.size(), small_num);
EXPECT_FALSE(map1.empty());
EXPECT_FALSE(map2.empty());
EXPECT_FALSE(map3.empty());
map1.clear();
EXPECT_TRUE(map1.empty());
EXPECT_EQ(map1.size(), 0u);
auto it = map1.find(1);
EXPECT_EQ(it, map1.end());
EXPECT_THROW(map1.at(1), std::out_of_range);
EXPECT_FALSE(map1.contains(1));
EXPECT_EQ(map1.count(1), 0u);
EXPECT_EQ(map1[1], test{});
map1.at(1) = test{ 1 };
EXPECT_NE(map1[1], test{});
map1 = map2;
for (size_t i = 0; i < small_num; ++i) {
EXPECT_EQ(map1[i], test{ i });
EXPECT_EQ(map1.at(i), test{ i });
EXPECT_EQ(map1.at_unchecked(i), test{ i });
EXPECT_EQ(map1.find(i)->second, test{ i });
EXPECT_TRUE(map1.contains(i));
EXPECT_EQ(map1.count(i), 1u);
EXPECT_EQ(map2[i], test{ i });
EXPECT_EQ(map2.at(i), test{ i });
EXPECT_EQ(map2.at_unchecked(i), test{ i });
EXPECT_EQ(map2.find(i)->second, test{ i });
EXPECT_TRUE(map2.contains(i));
EXPECT_EQ(map2.count(i), 1u);
EXPECT_EQ(map3[i], test{ i });
EXPECT_EQ(map3.at(i), test{ i });
EXPECT_EQ(map3.at_unchecked(i), test{ i });
EXPECT_EQ(map3.find(i)->second, test{ i });
EXPECT_TRUE(map2.contains(i));
EXPECT_EQ(map2.count(i), 1u);
}
map1.erase(1);
EXPECT_EQ(map1.size(), small_num - 1);
EXPECT_NE(map1, map2);
EXPECT_NE(map1, map3);
EXPECT_FALSE(map1.contains(1));
EXPECT_EQ(map1.count(1), 0u);
map1.insert({ 1, { 1 } });
EXPECT_EQ(map1.size(), small_num);
EXPECT_EQ(map1, map2);
EXPECT_EQ(map1, map3);
EXPECT_TRUE(map1.contains(1));
EXPECT_EQ(map1.count(1), 1u);
map1.erase(map1.begin(), map1.end());
EXPECT_TRUE(map1.empty());
EXPECT_EQ(map1.size(), 0u);
it = map1.find(1);
EXPECT_EQ(it, map1.end());
EXPECT_THROW(map1.at(1), std::out_of_range);
EXPECT_FALSE(map1.contains(1));
EXPECT_EQ(map1.count(1), 0u);
map_ded = map2;
map1 = std::move(map_ded);
map1.erase(map1.begin());
EXPECT_EQ(map1.size(), small_num - 1);
EXPECT_NE(map1, map2);
EXPECT_NE(map1, map3);
EXPECT_FALSE(map1.contains(0));
EXPECT_EQ(map1.count(0), 0u);
EXPECT_THROW(map1.at(0), std::out_of_range);
map1 = map2;
for (it = map1.begin(); it != map1.end();) {
if (it->second.val % 2 == 1)
it = map1.erase(it);
else
++it;
}
EXPECT_EQ(map1.size(), small_num / 2);
for (auto t : map1) {
EXPECT_EQ(t.second.val % 2, 0u);
}
map1 = map2;
for (it = map1.begin() + 1; it != map1.end();) {
if (it->second.val % 2 == 0)
it = map1.erase(it, std::next(it, 2));
else
++it;
}
EXPECT_EQ(map1.size(), 4u);
EXPECT_TRUE(map1.contains(0));
EXPECT_TRUE(map1.contains(1));
EXPECT_TRUE(map1.contains(9));
EXPECT_TRUE(map1.contains(7));
map1 = map2;
{
auto ret_pair1 = map1.insert({ 19, { 19 } });
EXPECT_TRUE(ret_pair1.second);
auto ret_pair2 = map1.insert({ 19, { 42 } });
EXPECT_FALSE(ret_pair2.second);
EXPECT_EQ(ret_pair2.first, ret_pair1.first);
EXPECT_EQ(map1.at(19), test{ 19 });
EXPECT_EQ(map1.at_unchecked(19), test{ 19 });
ret_pair2 = map1.insert_or_assign(19, test{ 42 });
EXPECT_FALSE(ret_pair2.second);
EXPECT_EQ(ret_pair2.first, ret_pair1.first);
EXPECT_EQ(map1.at(19), test{ 42 });
EXPECT_EQ(map1.at_unchecked(19), test{ 42 });
ret_pair2 = map1.insert_or_assign(19, test{ 19 });
}
map2.insert({ 20, { 20 } });
map3.insert({ 20, { 20 } });
EXPECT_NE(map1, map2);
EXPECT_NE(map1, map3);
{
auto ret_pair = map1.equal_range(19);
EXPECT_EQ(std::distance(ret_pair.first, ret_pair.second), 1);
EXPECT_EQ(ret_pair.first->second, test{ 19 });
ret_pair = map1.equal_range(20);
EXPECT_EQ(std::distance(ret_pair.first, ret_pair.second), 0);
EXPECT_EQ(ret_pair.first, map1.end());
EXPECT_EQ(ret_pair.first, ret_pair.second);
}
{
map1.emplace(20, test{ 20 });
test t{ 21 };
map1.emplace(21, t);
}
map1 = map2;
map3 = map2;
map1 = fea::unsigned_map<size_t, test>(
{ { 0, { 0 } }, { 1, { 1 } }, { 2, { 2 } } });
map2 = fea::unsigned_map<size_t, test>(
{ { 3, { 3 } }, { 4, { 4 } }, { 5, { 5 } } });
map3 = fea::unsigned_map<size_t, test>(
{ { 6, { 6 } }, { 7, { 7 } }, { 8, { 8 } } });
EXPECT_EQ(map1.size(), 3u);
EXPECT_TRUE(map1.contains(0));
EXPECT_TRUE(map1.contains(1));
EXPECT_TRUE(map1.contains(2));
EXPECT_EQ(map1.at(0), test{ 0 });
EXPECT_EQ(map1.at_unchecked(0), test{ 0 });
EXPECT_EQ(map1[1], test{ 1 });
EXPECT_EQ(map1.find(2)->second, test{ 2 });
EXPECT_EQ(map2.size(), 3u);
EXPECT_TRUE(map2.contains(3));
EXPECT_TRUE(map2.contains(4));
EXPECT_TRUE(map2.contains(5));
EXPECT_EQ(map2.at(3), test{ 3 });
EXPECT_EQ(map2.at_unchecked(3), test{ 3 });
EXPECT_EQ(map2[4], test{ 4 });
EXPECT_EQ(map2.find(5)->second, test{ 5 });
EXPECT_EQ(map3.size(), 3u);
EXPECT_TRUE(map3.contains(6));
EXPECT_TRUE(map3.contains(7));
EXPECT_TRUE(map3.contains(8));
EXPECT_EQ(map3.at_unchecked(6), test{ 6 });
EXPECT_EQ(map3[7], test{ 7 });
EXPECT_EQ(map3.find(8)->second, test{ 8 });
{
fea::unsigned_map<size_t, test> map1_back = map1;
fea::unsigned_map<size_t, test> map2_back{ map2 };
fea::unsigned_map<size_t, test> map3_back{ map3 };
map1.swap(map2);
EXPECT_EQ(map1, map2_back);
EXPECT_EQ(map2, map1_back);
using std::swap;
swap(map1, map3);
EXPECT_EQ(map1, map3_back);
EXPECT_EQ(map3, map2_back);
map1.swap(map2);
EXPECT_EQ(map1, map1_back);
}
map1.insert({ { 3, { 3 } }, { 4, { 4 } }, { 5, { 5 } } });
EXPECT_EQ(map1.size(), 6u);
EXPECT_TRUE(map1.contains(0));
EXPECT_TRUE(map1.contains(1));
EXPECT_TRUE(map1.contains(2));
EXPECT_TRUE(map1.contains(3));
EXPECT_TRUE(map1.contains(4));
EXPECT_TRUE(map1.contains(5));
EXPECT_EQ(map1.at(0), test{ 0 });
EXPECT_EQ(map1.at_unchecked(0), test{ 0 });
EXPECT_EQ(map1[1], test{ 1 });
EXPECT_EQ(map1.find(2)->second, test{ 2 });
EXPECT_EQ(map1.at(3), test{ 3 });
EXPECT_EQ(map1.at_unchecked(3), test{ 3 });
EXPECT_EQ(map1[4], test{ 4 });
EXPECT_EQ(map1.find(5)->second, test{ 5 });
map2 = fea::unsigned_map<size_t, test>(map1.begin(), map1.end());
EXPECT_EQ(map1.size(), map2.size());
EXPECT_EQ(map1, map2);
map3.clear();
map3.insert(map1.begin(), map1.end());
EXPECT_EQ(map1.size(), map3.size());
EXPECT_EQ(map1, map3);
EXPECT_EQ(map2.size(), map3.size());
EXPECT_EQ(map2, map3);
}
TEST(unsigned_map, random) {
}
TEST(unsigned_map, uniqueptr) {
fea::unsigned_map<size_t, std::unique_ptr<unsigned>> map;
{
std::unique_ptr<unsigned> test = std::make_unique<unsigned>(0);
map[0] = std::move(test);
}
{
std::unique_ptr<unsigned> test = std::make_unique<unsigned>(1);
map.emplace(1, std::move(test));
}
{
std::unique_ptr<unsigned> test = std::make_unique<unsigned>(2);
map.insert({ 2, std::move(test) });
}
for (size_t i = 3; i < 10; ++i) {
map.emplace(i, std::make_unique<unsigned>(unsigned(i)));
}
EXPECT_EQ(map.size(), 10u);
for (size_t i = 0; i < 10; ++i) {
EXPECT_EQ(*map.at(i), i);
}
EXPECT_TRUE(map.contains(5));
EXPECT_EQ(map.count(5), 1u);
map.erase(5);
EXPECT_FALSE(map.contains(5));
EXPECT_EQ(map.count(5), 0u);
map.clear();
EXPECT_EQ(map.size(), 0u);
}
} // namespace
|
[
"noreply@github.com"
] |
p-groarke.noreply@github.com
|
52532e5e77f9a82050c69df7124a6c19adb4c1ee
|
72f2992a3659ff746ba5ce65362acbe85a918df9
|
/apps-src/apps/librose/unit_frame.cpp
|
8f06c7a17f25bdc4ff28f6cd901aaf5e0c8c9d78
|
[
"BSD-2-Clause"
] |
permissive
|
chongtianfeiyu/Rose
|
4742f06ee9ecd55f9717ac6378084ccf8bb02a15
|
412175b57265ba2cda1e33dd2047a5a989246747
|
refs/heads/main
| 2023-05-23T14:03:08.095087
| 2021-06-19T13:23:58
| 2021-06-19T14:00:25
| 391,238,554
| 0
| 1
|
BSD-2-Clause
| 2021-07-31T02:39:25
| 2021-07-31T02:39:24
| null |
UTF-8
|
C++
| false
| false
| 17,077
|
cpp
|
/* $Id: unit_frame.cpp 47820 2010-12-05 18:08:51Z mordante $ */
/*
Copyright (C) 2006 - 2010 by Jeremy Rosen <jeremy.rosen@enst-bretagne.fr>
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.
See the COPYING file for more details.
*/
/** @file */
#include "global.hpp"
#include "display.hpp"
#include "serialization/string_utils.hpp"
#include "unit_frame.hpp"
progressive_string::progressive_string(const std::string& data,int duration) :
data_(),
input_(data)
{
const std::vector<std::string> first_pass = utils::split(data);
const int colons = (int)first_pass.size();
int total_explicit_time = 0, explicit_colon = 0;
std::vector<std::string>::const_iterator tmp;
for (tmp = first_pass.begin(); tmp != first_pass.end() ; ++ tmp) {
std::vector<std::string> second_pass = utils::split(*tmp, ':');
int explicit_time = (second_pass.size() > 1)? atoi(second_pass[1].c_str()): 0;
VALIDATE(explicit_time >= 0, null_str);
if (explicit_time) {
explicit_colon ++;
}
total_explicit_time += explicit_time;
data_.push_back(std::pair<std::string,int>(second_pass[0], explicit_time));
}
VALIDATE(total_explicit_time <= duration, null_str);
if (explicit_colon != colons) {
// 2. calculate average_time, and set it to no explicit itmes.
const int average_time = (duration - total_explicit_time) / (colons - explicit_colon);
for (std::vector<std::pair<std::string, int> >::iterator it = data_.begin(); it != data_.end(); ++ it) {
if (!it->second) {
it->second = average_time;
}
}
}
}
int progressive_string::duration() const
{
int total =0;
std::vector<std::pair<std::string,int> >::const_iterator cur_halo;
for(cur_halo = data_.begin() ; cur_halo != data_.end() ; ++cur_halo) {
total += cur_halo->second;
}
return total;
}
const std::string& progressive_string::get_current_element(int current_time)const
{
int time = 0;
unsigned int sub_halo = 0;
if(data_.empty()) return null_str;
while(time < current_time&& sub_halo < data_.size()) {
time += data_[sub_halo].second;
++sub_halo;
}
if(sub_halo) sub_halo--;
return data_[sub_halo].first;
}
template <class T>
progressive_<T>::progressive_(const std::string &data, int duration) :
data_(),
input_(data)
{
int split_flag = utils::REMOVE_EMPTY; // useless to strip spaces
const std::vector<std::string> comma_split = utils::split(data,',',split_flag);
const int colons = (int)comma_split.size();
// 1. calculate total_explicit, item's time that no explicit set to 0.
int total_explicit_time = 0, explicit_colon = 0;
std::vector<std::string>::const_iterator com_it = comma_split.begin();
for (; com_it != comma_split.end(); ++com_it) {
std::vector<std::string> colon_split = utils::split(*com_it,':',split_flag);
int explicit_time = (colon_split.size() > 1)? atoi(colon_split[1].c_str()): 0;
VALIDATE(explicit_time >= 0, null_str);
if (explicit_time) {
explicit_colon ++;
}
total_explicit_time += explicit_time;
std::vector<std::string> range = utils::split(colon_split[0],'~',split_flag);
T range0 = lexical_cast<T>(range[0]);
T range1 = (range.size() > 1) ? lexical_cast<T>(range[1]) : range0;
typedef std::pair<T,T> range_pair;
data_.push_back(std::pair<range_pair,int>(range_pair(range0, range1), explicit_time));
}
VALIDATE(total_explicit_time <= duration, null_str);
if (explicit_colon != colons) {
// 2. calculate average_time, and set it to no explicit itmes.
const int average_time = (duration - total_explicit_time) / (colons - explicit_colon);
for (typename std::vector<std::pair<std::pair<T, T>, int> >::iterator it = data_.begin(); it != data_.end(); ++ it) {
if (!it->second) {
it->second = average_time;
}
}
}
}
template <class T>
const T progressive_<T>::get_current_element(int current_time, T default_val) const
{
int time = 0;
unsigned int sub_halo = 0;
int searched_time = current_time;
if(searched_time < 0) searched_time = 0;
if(searched_time > duration()) searched_time = duration();
if(data_.empty()) return default_val;
while(time < searched_time&& sub_halo < data_.size()) {
time += data_[sub_halo].second;
++sub_halo;
}
if(sub_halo != 0) {
sub_halo--;
time -= data_[sub_halo].second;
}
const T first = data_[sub_halo].first.first;
const T second = data_[sub_halo].first.second;
return T((static_cast<double>(searched_time - time) /
static_cast<double>(data_[sub_halo].second)) *
(second - first) + first);
}
template<class T>
int progressive_<T>::duration() const
{
int total = 0;
typename std::vector<std::pair<std::pair<T, T>, int> >::const_iterator cur_halo;
for(cur_halo = data_.begin() ; cur_halo != data_.end() ; ++cur_halo) {
total += cur_halo->second;
}
return total;
}
template <class T>
bool progressive_<T>::does_not_change() const
{
return data_.empty() ||
( data_.size() == 1 && data_[0].first.first == data_[0].first.second);
}
// Force compilation of the following template instantiations
template class progressive_<int>;
template class progressive_<double>;
frame_parameters frame_parameters::null_param;
const int frame_parameters::default_text_color = 0xFFDDDDDD; // equal font::NORMAL_COLOR
frame_parameters::frame_parameters() :
duration(0),
image(),
image_diagonal(),
image_horizontal(),
image_mod(""),
stext(""),
halo(""),
sound(""),
text(""),
text_color(0),
font_size(0),
blend_with(0),
blend_ratio(0.0),
highlight_ratio(1.0),
offset_x(0),
offset_y(0),
submerge(0.0),
x(0),
y(0),
directional_x(0),
directional_y(0),
auto_vflip(t_unset),
auto_hflip(t_unset),
primary_frame(t_unset),
drawing_layer(display::LAYER_UNIT_DEFAULT - display::LAYER_UNIT_FIRST),
area_mode(false),
sound_filter()
{}
frame_parsed_parameters::frame_parsed_parameters(const config& cfg, const std::string& frame_string, int override_duration)
: duration_(override_duration? override_duration: cfg[frame_string + "duration"].to_int(1))
, image_(cfg[frame_string + "image"])
, image_diagonal_(cfg[frame_string + "image_diagonal"])
, image_horizontal_(cfg[frame_string + "image_horizontal"])
, image_mod_(cfg[frame_string + "image_mod"])
, stext_(cfg[frame_string + "stext"])
, halo_(cfg[frame_string + "halo"], duration_)
, sound_(cfg[frame_string + "sound"])
, text_(cfg[frame_string + "text"])
, text_color_(frame_parameters::default_text_color)
, font_size_(cfg[frame_string + "font_size"].to_int(0))
, blend_with_(0)
, blend_ratio_(cfg[frame_string + "blend_ratio"], duration_)
, highlight_ratio_(cfg[frame_string + "alpha"], duration_)
, offset_x_(cfg[frame_string + "offset_x"], duration_)
, offset_y_(cfg[frame_string + "offset_y"], duration_)
, submerge_(cfg[frame_string + "submerge"], duration_)
, x_(cfg[frame_string + "x"], duration_)
, y_(cfg[frame_string + "y"], duration_)
, directional_x_(cfg[frame_string + "directional_x"], duration_)
, directional_y_(cfg[frame_string + "directional_y"], duration_)
, auto_vflip_(t_unset)
, auto_hflip_(t_unset)
, primary_frame_(t_unset)
, drawing_layer_(cfg[frame_string + "layer"], duration_)
{
if (!frame_string.empty()) {
// not support define duration out of [xxx_frame]. must be additive using these [xxx_frame].
VALIDATE(!cfg.has_attribute(frame_string + "duration"), null_str);
}
if (!cfg.has_attribute(frame_string + "auto_vflip")) {
auto_vflip_ = t_unset;
} else if(cfg[frame_string + "auto_vflip"].to_bool()) {
auto_vflip_ = t_true;
} else {
auto_vflip_ = t_false;
}
if(!cfg.has_attribute(frame_string + "auto_hflip")) {
auto_hflip_ = t_unset;
} else if(cfg[frame_string + "auto_hflip"].to_bool()) {
auto_hflip_ = t_true;
} else {
auto_hflip_ = t_false;
}
if(!cfg.has_attribute(frame_string + "primary")) {
primary_frame_ = t_unset;
} else if(cfg[frame_string + "primary"].to_bool()) {
primary_frame_ = t_true;
} else {
primary_frame_ = t_false;
}
std::vector<std::string> color = utils::split(cfg[frame_string + "text_color"]);
if (color.size() == 4) {
text_color_ = display::rgb(atoi(color[1].c_str()), atoi(color[2].c_str()), atoi(color[3].c_str()));
text_color_ &= 0xffffffff;
}
color = utils::split(cfg[frame_string + "blend_color"]);
if (color.size() == 3) {
blend_with_ = display::rgb(atoi(color[0].c_str()), atoi(color[1].c_str()), atoi(color[2].c_str()));
}
}
bool frame_parsed_parameters::does_not_change() const
{
return halo_.does_not_change() &&
blend_ratio_.does_not_change() &&
highlight_ratio_.does_not_change() &&
offset_x_.does_not_change() &&
offset_y_.does_not_change() &&
submerge_.does_not_change() &&
x_.does_not_change() &&
y_.does_not_change() &&
directional_x_.does_not_change() &&
directional_y_.does_not_change() &&
drawing_layer_.does_not_change() &&
stext_.empty();
}
bool frame_parsed_parameters::need_update() const
{
if(!halo_.does_not_change() ||
!blend_ratio_.does_not_change() ||
!highlight_ratio_.does_not_change() ||
!offset_x_.does_not_change() ||
!offset_y_.does_not_change() ||
!submerge_.does_not_change() ||
!x_.does_not_change() ||
!y_.does_not_change() ||
!directional_x_.does_not_change() ||
!directional_y_.does_not_change() ||
!drawing_layer_.does_not_change() ) {
return true;
}
return false;
}
const frame_parameters frame_parsed_parameters::parameters(int current_time) const
{
frame_parameters result;
result.duration = duration_;
result.image = image_;
result.image_diagonal = image_diagonal_;
result.image_horizontal = image_horizontal_;
result.image_mod = image_mod_;
result.stext = stext_;
result.halo = halo_.get_current_element(current_time);
result.sound = sound_;
result.text = text_;
result.text_color = text_color_;
result.font_size = font_size_;
result.blend_with = blend_with_;
result.blend_ratio = blend_ratio_.get_current_element(current_time);
result.highlight_ratio = highlight_ratio_.get_current_element(current_time,1.0);
result.offset_x = offset_x_.get_current_element(current_time,-1000);
result.offset_y = offset_y_.get_current_element(current_time,-1000);
result.submerge = submerge_.get_current_element(current_time);
result.x = x_.get_current_element(current_time);
result.y = y_.get_current_element(current_time);
result.directional_x = directional_x_.get_current_element(current_time);
result.directional_y = directional_y_.get_current_element(current_time);
result.auto_vflip = auto_vflip_;
result.auto_hflip = auto_hflip_;
result.primary_frame = primary_frame_;
result.drawing_layer = drawing_layer_.get_current_element(current_time,display::LAYER_UNIT_DEFAULT-display::LAYER_UNIT_FIRST);
return result;
}
void frame_parsed_parameters::override( int duration
, const std::string& highlight
, const std::string& blend_ratio
, Uint32 blend_color
, const std::string& offset
, const std::string& layer
, const std::string& modifiers)
{
if (!highlight.empty()) {
highlight_ratio_ = progressive_double(highlight,duration);
} else if (duration != duration_){
highlight_ratio_ = progressive_double(highlight_ratio_.get_original(),duration);
}
if (!offset.empty()) {
offset_x_= progressive_double(offset,duration);
} else if (duration != duration_){
offset_x_ = progressive_double(offset_x_.get_original(),duration);
}
if (!offset.empty()) {
offset_y_ = progressive_double(offset,duration);
} else if (duration != duration_){
offset_y_ = progressive_double(offset_y_.get_original(),duration);
}
if (!blend_ratio.empty()) {
blend_ratio_ = progressive_double(blend_ratio,duration);
blend_with_ = blend_color;
} else if (duration != duration_){
blend_ratio_ = progressive_double(blend_ratio_.get_original(),duration);
}
if (!layer.empty()) {
drawing_layer_ = progressive_int(layer,duration);
} else if (duration != duration_){
drawing_layer_ = progressive_int(drawing_layer_.get_original(),duration);
}
if (!modifiers.empty()) {
image_mod_ += modifiers;
}
if (duration != duration_) {
halo_ = progressive_string(halo_.get_original(), duration);
submerge_=progressive_double(submerge_.get_original(), duration);
x_=progressive_int(x_.get_original(), duration);
y_=progressive_int(y_.get_original(), duration);
directional_x_=progressive_int(directional_x_.get_original(), duration);
directional_y_=progressive_int(directional_y_.get_original(), duration);
duration_ = duration;
}
}
frame_parsed_parameters& frame_parsed_parameters::image(const std::string& image ,const std::string & image_mod)
{
image_ = image;
image_mod_ = image_mod;
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::image_diagonal(const image::locator& image_diagonal,const std::string& image_mod)
{
image_diagonal_ = image_diagonal;
image_mod_ = image_mod;
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::image_horizontal(const image::locator& image_horizontal,const std::string& image_mod)
{
image_horizontal_ = image_horizontal;
image_mod_ = image_mod;
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::sound(const std::string& sound)
{
sound_=sound;
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::text(const std::string& text,const Uint32 text_color)
{
text_=text;
text_color_=text_color;
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::halo(const std::string &halo, const std::string &x, const std::string& y,const std::string & mod)
{
halo_ = progressive_string(halo, duration_);
x_ = progressive_int(x, duration_);
y_ = progressive_int(y, duration_);
image_mod_= mod;
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::duration(const int duration)
{
if (duration != duration_) {
halo_ = progressive_string(halo_.get_original(), duration);
blend_ratio_ = progressive_double(blend_ratio_.get_original(), duration);
highlight_ratio_ = progressive_double(highlight_ratio_.get_original(), duration);
offset_x_ = progressive_double(offset_x_.get_original(), duration);
offset_y_ = progressive_double(offset_y_.get_original(), duration);
submerge_=progressive_double(submerge_.get_original(), duration);
x_=progressive_int(x_.get_original(), duration);
y_=progressive_int(y_.get_original(), duration);
directional_x_=progressive_int(directional_x_.get_original(), duration);
directional_y_=progressive_int(directional_y_.get_original(), duration);
drawing_layer_=progressive_int(drawing_layer_.get_original(), duration);
duration_ = duration;
}
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::blend(const std::string& blend_ratio,const Uint32 blend_color)
{
blend_with_ = blend_color;
blend_ratio_ = progressive_double(blend_ratio, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::highlight(const std::string& highlight)
{
highlight_ratio_ = progressive_double(highlight, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::offset(const std::string& offset)
{
offset_x_ = progressive_double(offset, duration_);
offset_y_ = progressive_double(offset, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::offset(const std::string& offset_x, const std::string& offset_y)
{
offset_x_ = progressive_double(offset_x, duration_);
offset_y_ = progressive_double(offset_y, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::submerge(const std::string& submerge)
{
submerge_ = progressive_double(submerge, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::x(const std::string& x)
{
x_ = progressive_int(x, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::y(const std::string& y)
{
y_ = progressive_int(y, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::directional_x(const std::string& directional_x)
{
directional_x_ = progressive_int(directional_x, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::directional_y(const std::string& directional_y)
{
directional_y_ = progressive_int(directional_y, duration_);
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::auto_vflip(const bool auto_vflip)
{
if (auto_vflip) {
auto_vflip_ = t_true;
} else {
auto_vflip_ = t_false;
}
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::auto_hflip(const bool auto_hflip)
{
if (auto_hflip) {
auto_hflip_ = t_true;
} else {
auto_hflip_ = t_false;
}
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::primary_frame(const bool primary_frame)
{
if (primary_frame) {
primary_frame_ = t_true;
} else {
primary_frame_ = t_false;
}
return *this;
}
frame_parsed_parameters& frame_parsed_parameters::drawing_layer(const std::string& drawing_layer)
{
drawing_layer_ = progressive_int(drawing_layer, duration_);
return *this;
}
|
[
"service@leagor.com"
] |
service@leagor.com
|
ee840cc26d4f18d6f5d3951ba6a76c380eb8d508
|
69e2689bcfc9c876595b742d12013657662a6f65
|
/Codigo/WEMOS/Capбtulo 10/MQTTReleTemperatura/MQTTReleTemperatura.ino
|
b53fe3c2b214ae9e769c5358af42c01b9e5a9e12
|
[] |
no_license
|
Marcombo/Processing-interfaces-de-usuario-aplicaciones-de-vision-artificial-IoT-Arduino-ESP8266
|
91ea44a1a1cb66d49c6a2bae9bf9ecd1fdcdcd9a
|
e54960281f387de5d09b4005650d6ee872205a7b
|
refs/heads/main
| 2023-02-17T05:35:52.555093
| 2021-01-11T10:08:06
| 2021-01-11T10:08:06
| 328,616,518
| 1
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,525
|
ino
|
#include <SimpleDHT.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "*************"; // SSID de la red WIFI a la que desea conectarse
const char* password = "*******************"; // contraseña de dicha red
const char* mqtt_server = "test.mosquitto.org";
const char* tema = "marcombo_iot_mqtt_panel";
WiFiClient clienteWIFI;
PubSubClient clienteMQTT(clienteWIFI);
int pinRele = 13;
int pinDHT11 = 12;
SimpleDHT11 dht11;
byte temperatura = 0;
byte humedad = 0;
unsigned int tiempoAnterior;
int intervaloEnviotemperatura = 2000;
void setup() {
pinMode(pinRele, OUTPUT);
digitalWrite(pinRele, LOW);
pinMode(pinDHT11, INPUT);
Serial.begin(115200);
//Inicializa la conexión WiFI
Serial.print("Conectando a " + String(ssid) + " ");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" Conectado");
//Establecerá el broker que se utilizará
clienteMQTT.setServer(mqtt_server, 1883);
//Establecerá la función a la que se va a llamar cuando llegue un mensaje del broker
clienteMQTT.setCallback(callback);
}
void callback(char* tema_recibido, byte* contenido, unsigned int longitudContenido) {
String mensaje = "";
Serial.print("Ha llegado un mensaje con el tema: ");
Serial.print(tema_recibido);
Serial.print(" y el contenido: ");
for (int i = 0; i < longitudContenido; i++) {
mensaje = mensaje + (char)contenido[i];
Serial.print((char)contenido[i]);
}
Serial.println();
//Activa o desactiva el rele
if (mensaje == "ON"){
digitalWrite(pinRele, HIGH);
clienteMQTT.publish(tema, "ON_CONFIRMADO", true);
}
else if (mensaje == "OFF"){
digitalWrite(pinRele, LOW);
clienteMQTT.publish(tema, "OFF_CONFIRMADO", true);
}
}
void loop() {
//Establecerá la conexión con el broker
while (!clienteMQTT.connected()) {
Serial.print("Conectando al broker ...");
if (clienteMQTT.connect("wemos")) {
Serial.println("Conectado al broker.");
clienteMQTT.subscribe(tema);
} else delay(5000);
}
if(millis() - tiempoAnterior > intervaloEnviotemperatura){
dht11.read(pinDHT11, &temperatura, &humedad, NULL);
if (!isnan(temperatura)){
Serial.print((int)temperatura); Serial.println(" ºC, ");
char tmp[4];
dtostrf((int)temperatura,0, 0, tmp);
clienteMQTT.publish(tema, tmp, true);
}
tiempoAnterior = millis();
}
// Cliente escuchando
clienteMQTT.loop();
}
|
[
"ferri.fc@gmail.com"
] |
ferri.fc@gmail.com
|
49faf70bbeef6e7075e98a8e9b733a8c68289c57
|
f6858055f3f619400ba432ec3c2f2e585c244f83
|
/Source/ProjectOglowia/Private/CommonUtils.cpp
|
95c29ca440f476f22612f1bf2faa4691b467a295
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
mrG7/peacenet-ue
|
87e2253bc5566f30061e2cf269b2dd3c59088a6b
|
a865ea26983dc2930b39a377745210b9d38e9936
|
refs/heads/master
| 2020-03-31T16:23:24.605729
| 2018-10-08T20:42:09
| 2018-10-08T20:42:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,156
|
cpp
|
// Copyright (c) 2018 The Peacenet & Alkaline Thunder.
#include "CommonUtils.h"
FText UCommonUtils::GetFriendlyFilesystemStatusCode(const EFilesystemStatusCode InStatusCode)
{
switch (InStatusCode)
{
case EFilesystemStatusCode::OK:
return FText();
case EFilesystemStatusCode::DirectoryNotEmpty:
return NSLOCTEXT("Peacegate", "DirectoryNotEmpty", "Directory not empty.");
case EFilesystemStatusCode::FileOrDirectoryExists:
return NSLOCTEXT("Peacegate", "FileOrDirectoryExists", "File or directory exists.");
case EFilesystemStatusCode::FileOrDirectoryNotFound:
return NSLOCTEXT("Peacegate", "FileOrDirectoryNotFound", "File or directory not found.");
case EFilesystemStatusCode::PermissionDenied:
return NSLOCTEXT("Peacegate", "PermissionDenied", "Permission denied.");
default:
return NSLOCTEXT("Peacegate", "UnknownError", "An unknown error has occurred.");
}
}
UPeacegateFileSystem * UCommonUtils::CreateFilesystem(UPARAM(Ref)TScriptInterface<IFolderRepository> InFolderRepo, int InUserID)
{
UPeacegateFileSystem* FS = NewObject<UPeacegateFileSystem>();
FS->FolderRepo = InFolderRepo;
FS->Initialize(InUserID);
return FS;
}
|
[
"31224503+TheFuzzyRiolu@users.noreply.github.com"
] |
31224503+TheFuzzyRiolu@users.noreply.github.com
|
cbf191b4fc613a5a31ec9b9c6f2934fbb7a87e22
|
a453c287a016b1bb43163be667daa4a7b03c42f2
|
/main.cpp
|
7cf9b615eaec03acbd1555b439816e5f3c80af21
|
[] |
no_license
|
kolisergej/parentheses
|
acc56b867efedaede25428f85994a2bcca9b7de9
|
399ed964edda61779d5e8a46a35f0ad552066e27
|
refs/heads/main
| 2023-03-13T23:11:56.921272
| 2021-03-07T13:13:43
| 2021-03-07T13:13:43
| 345,350,828
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,162
|
cpp
|
#include <cassert>
#include <iostream>
#include <stack>
#include <string>
#include <unordered_set>
#include <unordered_map>
using namespace std;
const string kInfinite{"Infinite"};
const unordered_map<char, char> kDict = {
{'{', '}'},
{'(', ')'},
{'[', ']'}
};
const unordered_set<char> kValues{'}', ')', ']'};
bool check_infinite(const string& input) {
size_t first_open_idx = 0;
while (first_open_idx < input.size() && !kDict.count(input[first_open_idx])) {
++first_open_idx;
}
stack<char> st;
const auto check_ch = [&st, &input](size_t i) {
const auto ch = input[i];
if (kDict.count(input[i])) {
st.push(ch);
return true;
}
if (!kValues.count(ch)) {
return true;
}
if (!st.empty() && kDict.at(st.top()) == ch) {
st.pop();
return true;
}
return false;
};
for (size_t i = first_open_idx; i < input.size(); ++i) {
if (!check_ch(i)) {
return false;
}
}
for (size_t i = 0; i < first_open_idx; ++i) {
if (!check_ch(i)) {
return false;
}
}
return st.empty();
}
string process_letters_only(const string& input) {
string result;
int start{-1};
size_t current_length{0};
for (size_t i = 0; i < input.size(); i++) {
const auto ch = input[i];
if (kDict.count(ch) || kValues.count(ch)) {
if (start != -1 && current_length > result.size()) {
result = input.substr(start, current_length);
}
current_length = 0;
start = -1;
continue;
}
if (start == -1) {
start = i;
}
++current_length;
}
if (start != -1 && current_length > result.size()) {
result = input.substr(start, current_length);
}
return result;
}
string process_with_parrs(const string& input) {
int start{0};
int end{0};
stack<pair<char, int>> st;
for (int i = 0; i < input.size(); ++i) {
const auto ch = input[i];
if (kDict.count(ch)) {
st.push(make_pair(ch, i));
} else if (kValues.count(ch)) {
if (st.empty()) {
continue;
}
const auto top = st.top();
if (kDict.at(top.first) == ch) {
st.pop();
if (end == top.second) {
end = i+1;
} else if (top.second < start) {
start = top.second;
end = i+1;
} else if (end - start < i - top.second) {
start = top.second;
end = i+1;
}
} else {
stack<pair<char, int>>().swap(st);
}
} else if (i == end) {
++end;
}
}
return input.substr(start, end-start);
}
string run(const string& input) {
if (check_infinite(input)) {
return kInfinite;
}
const string double_input = input + input;
const string letters_only_max = process_letters_only(double_input);
const string max_with_parrs = process_with_parrs(double_input);
const string result = (letters_only_max.size() > max_with_parrs.size()) ? letters_only_max : max_with_parrs;
// cout << "result: " << result << endl;
return result;
}
int main() {
assert(run("") == kInfinite);
assert(run("aabbcc") == kInfinite);
assert(run("[]") == kInfinite);
assert(run("(){}") == kInfinite);
assert(run("]h({hdb}b)[") == kInfinite);
assert(run("[[b[aa]]]") == kInfinite);
assert(run("]][[b[aa]") == kInfinite);
assert(run("aaaa)((aaa)") == kInfinite);
assert(run("]})") == "");
assert(run("[)") == "");
assert(run("())") == "()");
assert(run("((aa)") == "(aa)");
assert(run("[[]") == "[]");
assert(run("[[])") == "[]");
assert(run("}](){") == "(){}");
assert(run("aa)((aaaaa") == "(aaaaaaa)");
assert(run("((aaa)((aa)") == "(aaa)");
assert(run("aaaaaaa)") == "aaaaaaa");
assert(run("(aaaaaaa") == "aaaaaaa");
assert(run("((aa)(aa)") == "(aa)(aa)");
assert(run("(aa(aa)a(aa)a))") == "(aa(aa)a(aa)a)");
assert(run("((aa(aa)a(aa)a)") == "(aa(aa)a(aa)a)");
assert(run("(aa)aa(aa))") == "(aa)aa(aa)");
assert(run("(aa(aa)aa(aa)))") == "(aa(aa)aa(aa))");
assert(run("((aa)((aa)") == "(aa)");
assert(run("((aa)(aa)((aa)") == "(aa)(aa)");
assert(run("(aa))(aa))") == "(aa)");
assert(run("(aba))(aa))") == "(aba)");
assert(run("(aa)(aa))") == "(aa)(aa)");
assert(run("((a{a}bb)))") == "((a{a}bb))");
assert(run("sh(dh)}") == "sh(dh)");
assert(run("[[b[aa]]") == "[b[aa]]");
assert(run("[[b[aa]]]]") == "[[b[aa]]]");
assert(run("[[b[aa]]}") == "[b[aa]]");
assert(run("]h({hhh(b})b)[") == "[]h");
assert(run("]h({h(bb})b)[") == "[]h");
assert(run("]h({h(bbbb})b)[") == "bbbb");
assert(run("]h({hdd(b})b)[") == "[]h");
assert(run("[{({][)][)[{{]])])]])([)]{((}}[") == "");
assert(run(")[{({][)][)[{{]])])]])([)]{((}}[(") == "()");
return 0;
}
|
[
"kolisergej@yandex.ru"
] |
kolisergej@yandex.ru
|
aba2db8b417c1c0aa04e272085db37056dcb3ed4
|
042983c6b28fd12d37652bc90390b0e59ee71c4d
|
/source/tools/new_triangulation/LinearAlgebra/SparseMatrix.ipp
|
bf7742ae6f3990f6730b4aa79dd996134f50980e
|
[] |
no_license
|
cigarfish/latticeCollagen
|
26718aae8cb5a9c6ade428d1e6fd47abe3b71348
|
74ac165a2e63f8f0aa7501ce8c6568ac8a407d9e
|
refs/heads/master
| 2020-03-21T23:07:33.057342
| 2018-10-11T16:03:01
| 2018-10-11T16:03:01
| 139,167,691
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,538
|
ipp
|
/*
* SparseMatrix.tcc
*
* Created on: Oct 27, 2010
* Author: jagiella
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
//#include "Mathematix.h"
#include "SparseMatrix.hpp"
#ifndef NULL
#define NULL 0
#endif
template <class T> SparseMatrix<T>::SparseMatrix( int m, int n)
{
A = (SparseVector<T>**) malloc( m * sizeof(SparseVector<T>**)); // values
assert( A);
for( int i=0; i<m; i++){
A[i] = new SparseVector<T>( n); // values
assert( A[i]);
}
this->m = m;
this->n = n;
}
template <class T> SparseMatrix<T>::~SparseMatrix()
{
for( int i=0; i<m; i++){
delete A[i];
}
free( A);
}
template <class T> T SparseMatrix<T>::get( int i, int j)
{
return A[i]->get( j);
}
template <class T> T& SparseMatrix<T>::getNonZero( int i, int jj)
{
return A[i]->getNonZero( jj);
}
template <class T> int SparseMatrix<T>::getNonZeroIndex( int i, int jj)
{
return A[i]->getNonZeroIndex( jj);
}
template <class T> void SparseMatrix<T>::resetRow( int i)
{
A[i]->reset();
}
template <class T> void SparseMatrix<T>::setLast( int i, int j, T value)
{
if( value == 0.) return;
A[i]->set( j, value);
}
template <class T> void SparseMatrix<T>::set( int i, int j, T value)
{
A[i]->set(j, value);
}
template <class T> void SparseMatrix<T>::setNonZero( int i, int jj, T value)
{
A[i]->setNonZero(jj, value);
}
template <class T> void SparseMatrix<T>::add( int i, int j, T value)
{
A[i]->add( j, value);
}
template <class T> void SparseMatrix<T>::MatrixVectorProduct( SparseMatrix<T> *A, T *b, T *x)
{
//x = A*b
// (n x m) * (m x p) = (n x p)
// (i x j) * (j x 1) = (i x 1)
for( int i=0; i<A->m; i++){
x[i] = 0.;
for( int jj=0; jj<A->A[i]->lengthNonZero(); jj++){
int j = A->A[i]->getNonZeroIndex(jj);
x[i] += A->A[i]->getNonZero(jj) * b[j];
}
}
}
template <class T> void SparseMatrix<T>::VectorMatrixProduct( T *b, SparseMatrix<T> *A, T *x)
{
//x = b*A
// (n x m) * (m x p) = (n x p)
// (1 x i) * (i x j) = (1 x j)
//int jj = 0;
for( int j=0; j<A->dimI; j++)
x[j] = 0.;
for( int i=0; i<A->dimI; i++){
for( int jj=0; jj<A->sizeA[i]; jj++){
int j = A->JA[i][jj];
x[j] += b[i] * A->A[i][jj];
/*
#if DEBUG > 0
if( isnan(x[j])){
fprintf( stderr, "nan occures in vectorsparseMatrixProduct\n");
fprintf( stderr, "vector b[%i] = %lf\n", i, b[i]);
for( int jj=0; jj<sA->sizeA[i]; jj++){
j = sA->JA[i][jj];
fprintf( stderr, "matrix A[%i][%i] = %lf\n", i, j, sA->A[i][jj]);
}
exit( 0);
}
#endif
*/
}
}
}
template <class T> void SparseMatrix<T>::printMatrix( const char* name, const char* format)
{
fprintf( stderr, "\"%s\" = [\n", name);
for( int i=0; i<m; i++)
{
for( int j=0; j<n; j++)
{
fprintf( stderr, format, this->get(i,j));
}
fprintf( stderr, "\n");
}
fprintf( stderr, "]\n");
}
template <class T> int SparseMatrix<T>::columns()
{
return n;
}
template <class T> int SparseMatrix<T>::columnsNonZero( int i)
{
return A[i]->lengthNonZero();
}
template <class T> int SparseMatrix<T>::rows()
{
return m;
}
template <class T>
T& SparseMatrix<T>::operator() ( int i, int j)
{
return (*A[i])(j);//this->get( i, j);
}
template <class T> void SparseMatrix<T>::operator() ( int i, int j, T value)
{
this->set( i, j, value);
}
template <class T> SparseMatrix<T>* SparseMatrix<T>::copy()
{
SparseMatrix<T>* copy = new SparseMatrix<T>( m, n);
for( int i=0; i<m; i++)
for( int jj=0; jj<A[i]->lengthNonZero(); jj++){
copy->setLast( i, A[i]->getNonZeroIndex(jj), A[i]->getNonZero(jj));
}
return copy;
}
|
[
"zhaojielingzjl@yahoo.com"
] |
zhaojielingzjl@yahoo.com
|
72b19656e8a6959dbd15f273f3531a52203e599b
|
d7784cb9ce174ec5091d327b21ebcf4c6c507388
|
/yukicoder/349_352/349.cpp
|
82680ccd77b63f120194d7217da11346e8eb0f09
|
[] |
no_license
|
mmxsrup/procon
|
3a349b10c852ad593ecedcdd1c9fdb93cb8d8f3b
|
af059cc3f6786db71f0077d1ec5d902171b9860a
|
refs/heads/master
| 2021-01-17T15:05:05.580007
| 2017-12-06T07:52:53
| 2017-12-06T07:52:53
| 84,103,106
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,414
|
cpp
|
/*
一番多い者に着目すればいける
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <bitset>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
typedef pair<int,int> pint;
typedef vector<int> vint;
typedef vector<pint> vpint;
#define mp make_pair
#define fi first
#define se second
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
int dx[4] = {1, 0, 0, -1};
int dy[4] = {0, 1, -1, 0};
int main(void){
int n;
char eto[51][51];
char eto_template[15][15] = {"ne", "ushi", "tora", "u", "tatsu", "mi", "uma", "hitsuji", "saru", "tori", "inu", "i"};
int eto_num[12] = {0};
scanf("%d", &n);
rep(i, n){
scanf("%s", eto[i]);
rep(j, 12){
/*if (eto[i] == eto_template[j])
eto_num[j]++;*/
if (strcmp(eto[i], eto_template[j]) == 0) //同じなら0を返す
{
eto_num[j]++;
}
}
}
//かぶりが一番多いものを探す
int max_num = 0;
rep(i, 12)
max_num = max(max_num, eto_num[i]);
if (n - max_num >= max_num - 1) //かぶりがいちばん多い者を並べて、その間に他のものをいれられるだけ干支が残っていればいい
printf("YES\n");
else
printf("NO\n");
return 0;
}
|
[
"mmxsrup@yahoo.co.jp"
] |
mmxsrup@yahoo.co.jp
|
3e853920e96631cb90faf26277adcb7cbd5fbf4c
|
9889e7fd73314382fb2f9e8f63d92cf3254b75fb
|
/ThirdParty/NairnMPMFEA/Common/System/LinkedObject.hpp
|
9299a6cb0be0d35913ee273c7f8eaeeed6e1bdb0
|
[] |
no_license
|
bbanerjee/ParSim
|
0b05f43cff8e878658dc179b4a604eabd873f594
|
87f87816b146f40013a5e6648dfe20f6d2d002bb
|
refs/heads/master
| 2023-04-27T11:30:36.252023
| 2023-04-13T22:04:50
| 2023-04-13T22:04:50
| 13,608,512
| 16
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 607
|
hpp
|
/********************************************************************************
LinkedObject.hpp
NairnFEA
Created by John Nairn on 6/22/05.
Copyright (c) 2005 John A. Nairn, All rights reserved.
Dependencies
none
********************************************************************************/
#ifndef _LINKEDOBJECT_
#define _LINKEDOBJECT_
class LinkedObject
{
public:
LinkedObject *nextObject;
// Constructors and Destructor
LinkedObject();
// methods
void SetNextObject(LinkedObject *);
LinkedObject *GetNextObject(void) const;
};
#endif
|
[
"b.banerjee.nz@gmail.com"
] |
b.banerjee.nz@gmail.com
|
ae235273052a5ff7fbd3c765bf645fcb09c0e075
|
3435446327127f8dff815c1af5223f3d58c5243a
|
/Source/Voxel/VoxelHUD.h
|
ee41c18127eb81db645abfb8abd6e941ae658fa0
|
[] |
no_license
|
azy2/UEVoxel
|
83b5d2b45fde3db26d89e3d27873a0b950e6d570
|
01869ede5d0d1e18cf448539f1e16a54248bef6b
|
refs/heads/master
| 2021-05-08T00:44:41.692418
| 2017-10-23T14:26:54
| 2017-10-23T14:26:54
| 107,699,590
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 401
|
h
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/HUD.h"
#include "VoxelHUD.generated.h"
UCLASS()
class AVoxelHUD : public AHUD
{
GENERATED_BODY()
public:
AVoxelHUD();
/** Primary draw call for the HUD */
virtual void DrawHUD() override;
private:
/** Crosshair asset pointer */
class UTexture2D* CrosshairTex;
};
|
[
"Ben Lambeth"
] |
Ben Lambeth
|
ae20ea2e94bdd85b887e88ec150ed1058fbd2257
|
efc803ff1268ac0660b3357f68e7d36f2df6359b
|
/ConsolCommands.h
|
ac88e81b2e9256c7b0cb28f5b363be1ad9d6a64d
|
[] |
no_license
|
OlegOliinyk/Student_test
|
7e9bddb842ad40aa4d77e8902864d30a1bac106d
|
698d3243b91adfd602bdc8ffddeacfe4d72a3e12
|
refs/heads/master
| 2023-08-19T04:28:33.735020
| 2021-10-01T18:18:47
| 2021-10-01T18:18:47
| 412,538,074
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 189
|
h
|
#pragma once
#include <iostream>
#include <Windows.h>
using namespace std;
class ConsolCommands {
protected:
void cursorPosition(int x, int y);
void stringCls(int x, int y, int n);
};
|
[
"topufcmma@gmail.com"
] |
topufcmma@gmail.com
|
60a862c9f4049304dec405447d1da4d23345255d
|
7c5343b302eda9b52e1c34723fc9578c893d8fcf
|
/Userland/Libraries/LibWeb/WebContentClient.h
|
15664fb8196b1170bf29e792705094ff4a024da2
|
[
"BSD-2-Clause"
] |
permissive
|
1player/serenity
|
7ac6e70cf6616f27b7d2c658f4494d8113210852
|
b639bf64f283d4ffc8d6d8ccc44c599acd08683e
|
refs/heads/master
| 2023-05-13T06:35:09.138089
| 2021-06-09T22:28:59
| 2021-06-09T22:46:37
| 375,615,810
| 1
| 0
|
BSD-2-Clause
| 2021-06-10T07:52:11
| 2021-06-10T07:52:11
| null |
UTF-8
|
C++
| false
| false
| 2,821
|
h
|
/*
* Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/HashMap.h>
#include <LibIPC/ServerConnection.h>
#include <LibWeb/Cookie/ParsedCookie.h>
#include <WebContent/WebContentClientEndpoint.h>
#include <WebContent/WebContentServerEndpoint.h>
namespace Web {
class OutOfProcessWebView;
class WebContentClient final
: public IPC::ServerConnection<WebContentClientEndpoint, WebContentServerEndpoint>
, public WebContentClientEndpoint {
C_OBJECT(WebContentClient);
public:
Function<void()> on_web_content_process_crash;
private:
WebContentClient(OutOfProcessWebView&);
virtual void die() override;
virtual void did_paint(Gfx::IntRect const&, i32) override;
virtual void did_finish_loading(URL const&) override;
virtual void did_invalidate_content_rect(Gfx::IntRect const&) override;
virtual void did_change_selection() override;
virtual void did_request_cursor_change(i32) override;
virtual void did_layout(Gfx::IntSize const&) override;
virtual void did_change_title(String const&) override;
virtual void did_request_scroll(int) override;
virtual void did_request_scroll_into_view(Gfx::IntRect const&) override;
virtual void did_enter_tooltip_area(Gfx::IntPoint const&, String const&) override;
virtual void did_leave_tooltip_area() override;
virtual void did_hover_link(URL const&) override;
virtual void did_unhover_link() override;
virtual void did_click_link(URL const&, String const&, unsigned) override;
virtual void did_middle_click_link(URL const&, String const&, unsigned) override;
virtual void did_start_loading(URL const&) override;
virtual void did_request_context_menu(Gfx::IntPoint const&) override;
virtual void did_request_link_context_menu(Gfx::IntPoint const&, URL const&, String const&, unsigned) override;
virtual void did_request_image_context_menu(Gfx::IntPoint const&, URL const&, String const&, unsigned, Gfx::ShareableBitmap const&) override;
virtual void did_get_source(URL const&, String const&) override;
virtual void did_js_console_output(String const&, String const&) override;
virtual void did_change_favicon(Gfx::ShareableBitmap const&) override;
virtual void did_request_alert(String const&) override;
virtual Messages::WebContentClient::DidRequestConfirmResponse did_request_confirm(String const&) override;
virtual Messages::WebContentClient::DidRequestPromptResponse did_request_prompt(String const&, String const&) override;
virtual Messages::WebContentClient::DidRequestCookieResponse did_request_cookie(URL const&, u8) override;
virtual void did_set_cookie(URL const&, Web::Cookie::ParsedCookie const&, u8) override;
OutOfProcessWebView& m_view;
};
}
|
[
"kling@serenityos.org"
] |
kling@serenityos.org
|
4d68711f36a2aa98a686188398cd19bad7294a26
|
f5cd4aa57470c77530f83ae0fdad58c9ceb865b4
|
/tests/core_tests/chain_split_1.h
|
87e0545e67ea52f3265220ed6476463b5d1dfcc6
|
[
"BSD-3-Clause"
] |
permissive
|
weirdboy79/fonero
|
4ff23ddeb4b53cb8f4d5029e85b31ee07685648d
|
80d5aa64b4a7329222954d504e5d99e3fdd48159
|
refs/heads/master
| 2020-03-10T07:38:57.850114
| 2018-04-11T15:31:50
| 2018-04-11T15:31:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,120
|
h
|
// Copyright (c) 2017-2018, The Fonero Project.
// Copyright (c) 2014-2017 The Fonero Project.
// Portions Copyright (c) 2012-2013 The Cryptonote developers.
//
// 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 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#pragma once
#include "chaingen.h"
/************************************************************************/
/* */
/************************************************************************/
class gen_simple_chain_split_1 : public test_chain_unit_base
{
public:
gen_simple_chain_split_1();
bool generate(std::vector<test_event_entry> &events) const;
bool check_split_not_switched(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_split_not_switched2(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_split_switched(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_split_not_switched_back(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_split_switched_back_1(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_split_switched_back_2(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_mempool_1(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_mempool_2(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
/*bool check_orphaned_chain_1(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_switched_to_alternative(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_chain_2(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_switched_to_main(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_chain_38(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_chain_39(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_chain_40(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events);
bool check_orphaned_chain_41(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events); */
private:
};
|
[
"dev@fonero.org"
] |
dev@fonero.org
|
8fcd5b8e974b6e07b21891115ff4aa7b0a3ae2d7
|
4da239317dbe41bdfd2e1982d2564c12b5a757f4
|
/单一深度图/单一深度图/main.cpp
|
b9a7738f5936b0ec67ae513ffe755ec797d65d5b
|
[] |
no_license
|
Vincent-2017/Kinect2.0
|
6433bc6913ded7e57a53e4c46da9668d479025a6
|
d1a921db58b4d3219bb3f4681931e1f8b7734115
|
refs/heads/master
| 2021-01-01T06:09:04.851453
| 2017-08-02T12:19:03
| 2017-08-02T12:19:03
| 97,370,573
| 3
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,328
|
cpp
|
#include <Kinect.h> //Kinect的头文件
#include <iostream>
#include <opencv2\imgproc.hpp> //opencv头文件
#include <opencv2\calib3d.hpp>
#include <opencv2\highgui.hpp>
using namespace std;
using namespace cv;
//获得某点像素值
int get_pixel(Mat & img, Point pt) {
int width = img.cols; //图片宽度
int height = img.rows; //图片宽度t;//图片高度
uchar* ptr = (uchar*)img.data + pt.y * width; //获得灰度值数据指针
int intensity = ptr[pt.x];
return intensity;
}
int main(void)
{
IKinectSensor* KinectSensor = nullptr;
GetDefaultKinectSensor(&KinectSensor); //获取感应器
KinectSensor->Open(); //打开感应器
cout << "打开Kinect传感器" << endl;
cout << endl;
IDepthFrameSource * DepthSource = nullptr; //取得深度数据
KinectSensor->get_DepthFrameSource(&DepthSource);
int height = 0, width = 0;
IFrameDescription * myDescription = nullptr; //取得深度数据的分辨率
DepthSource->get_FrameDescription(&myDescription);
myDescription->get_Height(&height);
myDescription->get_Width(&width);
cout <<"深度图像大小是:"<< height << " * " << width << endl;
myDescription->Release();
IDepthFrameReader * DepthReader = nullptr;
DepthSource->OpenReader(&DepthReader); //打开深度数据的Reader
IDepthFrame * myFrame = nullptr;
Mat temp(height, width, CV_16UC1); //建立图像矩阵
Mat img(height, width, CV_8UC1);
while (1)
{
if (DepthReader->AcquireLatestFrame(&myFrame) == S_OK) //通过Reader尝试获取最新的一帧深度数据,放入深度帧中,并判断是否成功获取
{
//原始UINT16 深度图像不适合用来显示,所以需要砍成8位的就可以了
myFrame->CopyFrameDataToArray(height * width, (UINT16 *)temp.data); //先把数据存入16位的图像矩阵中
temp.convertTo(img, CV_8UC1, 255.0 / 4500); //再把16位转换为8位
cout << get_pixel(img, Point(200, 200)) << endl;
imshow("Depth", img);
myFrame->Release();
}
//POINT pt;
//GetCursorPos(&pt);
//cout << "当前的鼠标坐标为:" << pt.x << "," << pt.y << endl;
if (waitKey(30) == VK_ESCAPE)
break;
}
DepthReader->Release(); //释放不用的变量并且关闭感应器
DepthSource->Release();
KinectSensor->Close();
KinectSensor->Release();
return 0;
}
|
[
"1156767986@qq.com"
] |
1156767986@qq.com
|
58e61bfcc84e28cdbfcccf1fbfff6d23fd62587f
|
b02dfd153360607a5260c13e48b5a84a866c5353
|
/include/suic/Framework/Controls/Popup.h
|
f0f2b7e40f4388d81e52250b259812b685ee1828
|
[] |
no_license
|
15831944/MPF
|
7fb54842612a91c4c05cb555c0b065512830f8c9
|
21e6169b5d1797dfbdfd46ff5a832221ba86b61e
|
refs/heads/master
| 2022-03-26T16:32:23.562737
| 2016-11-12T01:34:41
| 2016-11-12T01:34:41
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 5,754
|
h
|
// 华勤科技版权所有 2010-2011
//
// 文件名:Popup.h
// 功 能:实现标准的弹出窗口(无焦点)。
//
// 作 者:MPF开发组
// 时 间:2010-07-02
//
// ============================================================================
#ifndef _UIPOPUP_H_
#define _UIPOPUP_H_
#include <Framework/Controls/Content.h>
namespace suic
{
enum PlacementMode
{
pmLeft,
pmTop,
pmRight,
pmBottom,
pmCenter,
pmMouse,
pmMousePoint,
pmCustom,
};
struct SUICORE_API PlacementModeBox
{
static Integer* LeftBox;
static Integer* TopBox;
static Integer* RightBox;
static Integer* BottomBox;
static Integer* CenterBox;
static Integer* MouseBox;
static Integer* MousePointBox;
static Integer* CustomBox;
static Integer* From(int index);
};
struct PositionInfo
{
int x;
int y;
fSize ChildSize;
Rect MouseRect;
};
class SUICORE_API PopupRoot : public FrameworkElement
{
public:
PopupRoot();
~PopupRoot();
RTTIOfClass(PopupRoot)
Element* GetChild();
void SetChild(Element* elem);
int GetVisualChildrenCount();
Element* GetVisualChild(int index);
Element* GetLogicalChild(int index);
int GetLogicalChildrenCount();
protected:
void OnTextInput(KeyboardEventArg* e);
void OnKeyDown(KeyboardEventArg* e);
void OnKeyUp(KeyboardEventArg* e);
void SetupLayoutBindings(Popup* popup);
fSize ComputeChildDesiredSize(fSize restrictedSize);
fSize ComputePopupSizeRestrictions(Popup* popup, fSize desiredSize, bool& bWidth, bool& bHeight);
friend class Popup;
public:
fSize OnMeasure(const fSize& constraintSize);
void OnArrange(const fSize& arrangeSize);
private:
Element* _child;
};
class OpeningEventArg : public EventArg
{
public:
OpeningEventArg(HwndParam* hp)
: _hp(hp)
{
}
HwndParam* GetHwndParam() const
{
return _hp;
}
private:
HwndParam* _hp;
};
typedef delegate<void(Object*, OpeningEventArg*), suic::UnrefObj> OpeningEventHandler;
class SUICORE_API Popup : public FrameworkElement, public IAddChild
{
public:
EventHandler Closed;
EventHandler Opened;
EventHandler Closing;
OpeningEventHandler Opening;
static DpProperty* ChildProperty;
static DpProperty* IsOpenProperty;
static DpProperty* CoercedPosProperty;
static DpProperty* PlacementProperty;
static DpProperty* PlacementRectangleProperty;
static DpProperty* PlacementTargetProperty;
static DpProperty* VerticalOffsetProperty;
static DpProperty* HorizontalOffsetProperty;
static DpProperty* AllowsTransparencyProperty;
static bool StaticInit();
static void CreateRootPopup(Popup* popup, Element* child);
static void OnChildPropChanged(DpObject* d, DpPropChangedEventArg* e);
static void OnIsOpenPropChanged(DpObject* d, DpPropChangedEventArg* e);
static void OnPlacementPropChanged(DpObject* d, DpPropChangedEventArg* e);
static void OnOffsetPropChanged(DpObject* d, DpPropChangedEventArg* e);
static void OnPlacementTargetPropChanged(DpObject* d, DpPropChangedEventArg* e);
static void OnAllowsTransparencyPropChanged(DpObject* d, DpPropChangedEventArg* e);
Popup();
~Popup();
RTTIOfClass(Popup)
void Hide();
void Show(Point pt);
void Close();
void AsyncClose();
bool IsClosing();
PopupRoot* GetPopupRoot();
PositionInfo* GetPositionInfo();
Element* GetChild();
void SetChild(Element* elem);
void InvalidatePopupRoot();
void TrackingPopup(MessageHook& hook=MessageHook());
bool IsOpen();
void SetIsOpen(bool val);
bool GetCoercedPos();
void SetCoercedPos(bool val);
PlacementMode GetPlacement();
void SetPlacement(PlacementMode val);
Rect GetPlacementRectangle();
void GetPlacementRectangle(Rect val);
Element* GetPlacementTarget();
void SetPlacementTarget(Element* target);
int GetVerticalOffset();
void SetVerticalOffset(int val);
int GetHorizontalOffset();
void SetHorizontalOffset(int val);
bool AllowsTransparency();
void SetAllowsTransparency(bool val);
bool IsChildPopup();
void SetChildPopup(bool value);
Popup* GetParentPopup();
void SetParentPopup(Popup* val);
public:
void AddChild(Object* obj);
void AddText(String val);
void RemoveChild(Object* child);
virtual void OnClosing(CancelEventArg& e);
virtual void OnClosed(EventArg* e);
virtual void OnOpened(EventArg* e);
virtual bool OnShowingWindow();
virtual void OnShowWindow();
virtual void OnHideWindow();
virtual bool OnFilterMessage(Object* sender, MessageParam* mp, bool& interrupt);
virtual bool OnSysFilterMessage(Object* sender, MessageParam* mp, bool& interrupt);
protected:
fSize OnMeasure(const fSize& constratint);
void OnArrange(const fSize& arrangeSize);
void OnHitTest(HitResultEventArg* e);
void OnMouseWheel(MouseWheelEventArg* e);
void OnMouseLeftButtonDown(MouseButtonEventArg* e);
void OnMouseRightButtonDown(MouseButtonEventArg* e);
void OnTextInput(KeyboardEventArg* e);
void OnKeyDown(KeyboardEventArg* e);
void OnKeyUp(KeyboardEventArg* e);
protected:
Element* GetTarget();
void InternalClose(bool async);
int InternalCreate(int wid, int hei);
bool BlockVisualState();
void EnsurePopupRoot();
void ComputePosition(fSize desiredSize);
protected:
bool _onMouseIn;
bool _onTimer;
bool _onDownClose;
bool _isMouseIn;
bool _isClosing;
Popup* _parentPopup;
PopupRoot* _popupRoot;
AssignerFrame* _frame;
PositionInfo _positionInfo;
};
typedef shared<Popup> PopupPtr;
}
#endif
|
[
"china0851@foxmail.com"
] |
china0851@foxmail.com
|
d7f1cee2bc24ce7af551c3cabea8ffc429f56e2d
|
01acd836f3788aba78e9eeb97fba171f0eaa0128
|
/1 restart/new3.cpp
|
d8e2e2b6707759c40d9ff8bea59e941ba57d9ae2
|
[] |
no_license
|
bagilder/Nixie
|
ec170ee27584425806a054364323c82c92d62080
|
92bc18d2e535228f53f4ca8c690b4e9b36e15f34
|
refs/heads/master
| 2023-06-01T15:12:09.331828
| 2023-05-18T04:31:14
| 2023-05-18T04:31:14
| 122,246,237
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,553
|
cpp
|
/*
new3.cpp
brian gilder did a thing 22dec2016
this is a new attempt to nixie clock it up, this time with 60% more ions.
uses the time.h library and internal arduino oscillator
*/
/********** notes ***********
**can implement interrupts to set seconds etc. although if we're using time.h, it doesn't really
** matter how often we update our output registers since the internal timekeeping is still accurateish without
** needing our involvement. maybe we don't need interrupts at all.
**we could use interrupts to update the lamps using whatever is the current register set. so we have consistent timing
** on lighting them up. but since we are using time.h, we have nothing but free time. timekeeping is basically
** already finished. we just have to update our registers and then animate the hours. this problem becomes pretty trivial. damn.
**perhaps the hourAnimate can use the interrupt. that way, we don't need to poll for a flag. now i just need to learn interrupts.
**
**
*****************************/
#include <time.h>
#include <TimerOne.h>
#include <stdio.h> //this isn't a thing in arduino is it?. arduino is meant to be io
//**********programmer defined***************
const digitLength = 6; //either 6 or 4 depending on whether there are seconds digits or not
const PowerMuxTop = 10; //number of pin at the top of the power mux series of output pins. should descend in number from here to use current sign scheme in setup loop
//*******************************************
int isSet = 0;
int hourAnimate = 0; // need to write the trigger for this. or get rid of it and assign an interrupt for that condition
int current_h = 0;
int current_m = 0;
int current_s = 0;
int disp_hHi = 0;
int disp_hLo = 0;
int disp_mHi = 0;
int disp_mLo = 0;
int disp_sHi = 0;
int disp_sLo = 0;
char portHax[5] = 0;
long time_t = 0;
// long t = 0; // does this need to exist? idk how the time.h library works
short portBin[9] = {B00000000,B00010000,B00100000,B00110000,B01000000,B01010000,B01100000,B01110000,B10000000,B10010000}; //reorganize depending on how we pin driver //might not use if we go with switchcase for porthax //can we use shorts to store B's? are those not considered letters? since it's for encoding schemes?
void setup() {
delay(500);
Serial.begin(9600);
/*for(int i = 0, i<digit_length; i++)
{ //did we determine whether loops were allowed in setup? if no, just powermuxtop - 1, - 2 etc
pinMode(PowerMuxTop - i, OUTPUT); //make + if going in different direction on port
}
*/
DDRD = DDRD | B11111100; //sets port D as outputs. erase this and uncomment above loop if not port haxing
}
void loop() {
/*
while(!isSet) // should we have the while at this level? atm there are two while loops
{
setBlink();
}
*/
time_t t = now(); //is time_t a thing in the time.h library? or does it need a type declaration? // is the t a straggler or is it supposed to be there? if so, instantiate it
current_h = hour(t);
current_m = minute(t);
current_s = second(t);
disp_hHi = current_h/10;
disp_hLo = current_h%10;
disp_mHi = current_m/10;
disp_mLo = current_m%10;
disp_sHi = current_s/10;
disp_sLo = current_s%10;
disp_send = {disp_hHi,disp_hLo,disp_mHi,disp_mLo,disp_sHi,disp_sLo};
displayUpdate();
}
void displayUpdate(){
if(hourAnimate) // can eliminate this flag poll (ha get it) if we use an interrupt for new hour condition
hourRoll();
else
{
for(int j = 0; j <s 6; i++)
{
// portHax[j] = //don't remember what i was doing here. maybe it's instead of the switchcase?
}
int q = 0;
for(int i = 0; i < digitLength; i++) //this immediately sets the output port binary for tube driver
{
/* //i'm an idiot. why else would i have portBin if not for this purpose. the indeces even work with the numbers
switch(disp_send[i])
{ //there is surely a more elegant way to do this /////SPOILERS THERE IS use portBin you dummy
case 0:
PORTD = B00000000;
break;
case 1:
PORTD = B00010000;
break;
case 2:
PORTD = B00100000;
break;
case 3:
PORTD = B00110000;
break;
case 4:
PORTD = B01000000;
break;
case 5:
PORTD = B01010000;
break;
case 6:
PORTD = B01100000;
break;
case 7:
PORTD = B01110000;
break;
case 8:
PORTD = B10000000;
break;
case 9:
PORTD = B10010000;
break;
}
*/
q = disp_send[i]; //goes through each position of disp_send and gets value for q
PORTD = portBin[q]; //sets port d to corresponding binary for q value i hope. index already matches values (convenient)
//will i need a delay here before toggling on? i think probably not if i'm port hacking. that's way faster than digital write
digitalWrite(PowerMuxTop - i, HIGH);
delay(muxDelay/2);
digitalWrite(PowerMuxTop - i, LOW);
delay(muxDelay/2);
}
}
}
// do we need to do what follows with pointers or can we return an array at the end?
// do we even need to do this or should we have a lookup table? i'll make a table anyway
// especially since this returns an array. would i need to concatinate it to make it a number again?
int dec2bin(int a) { //this is probably superfluous now that i've made the switchcase
int c, k, b[4];
for(c = 4; c>=0; c--)
{
k = a >> c;
if (k & 1)
b[c] = 1;
else
b[c] = 0;
}
return b;
}
// is itoa(value,outputstring,base) an actual thing? output string suggests more type conversion but w/e
void hourRoll() { //fancy hour animations
//use the old stuff from other versions. they mostly worked alright.
/* more ideas:
-could have them scroll out one side and then scroll in the other. (like a lame powerpoint transition)
-could have them roll, but one at a time. like secLow rolls through all 10 numbers, then stops, then secHi goes, etc down the line
-could have them flash randomish numbers until it lands on the correct one. either in series or randomly
*/
}
// setBlink should probably be eliminated in favor of flashing a string of 0s on and off until the
// time is set. that way, there isn't accidentally a 888888 starting point that is being adjusted
void setBlink() {
while(!is_set) // might be able just to use an interrupt to quit this loop /////YOU CAN!!!
{
disp_string = {0,0,0,0,0,0}; //have not defined disp_string before now. maybe use disp_send
delay(1000);
//some_phantom_button_check_or_something(); //use an interrupt if arduino can handle it /////IT CAN!
disp_string = {8,8,8,8,8,8};
delay(1000);
//some_phantom_button_check_or_something();
}
}
|
[
"bagilder@users.noreply.github.com"
] |
bagilder@users.noreply.github.com
|
0a1e74e8d185b287c30444189af8ed161c547db7
|
6202711eb80913389c9b038952fb32f9b1eb0392
|
/src/database/kernels/xgemv/xgemv_6464.hpp
|
b380e4409c534a5fecb7e02815dc9325c48dc1d8
|
[
"Apache-2.0"
] |
permissive
|
csicar/CLBlast
|
c6e982b5ad21a85bbc6d54bc0dc9579f140d5a9c
|
8e8607ec79108f7e50b5c4375db868dc3e8466e9
|
refs/heads/master
| 2023-06-30T05:44:28.754538
| 2021-07-31T01:03:43
| 2021-07-31T01:03:43
| 391,222,596
| 0
| 0
|
Apache-2.0
| 2021-07-31T01:00:38
| 2021-07-31T01:00:37
| null |
UTF-8
|
C++
| false
| false
| 8,423
|
hpp
|
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. It
// is auto-generated by the 'scripts/database/database.py' Python script.
//
// This file populates the database with best-found tuning parameters for the 'Xgemv6464' kernels.
//
// =================================================================================================
namespace clblast {
namespace database {
const DatabaseEntry XgemvComplexDouble = {
"Xgemv", Precision::kComplexDouble, {"WGS1", "WPT1"}, {
{ // AMD GPUs
kDeviceTypeGPU, "AMD", {
{ "Ellesmere", {
{ Name{"AMD Radeon RX 480 "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Fiji", {
{ Name{"AMD Radeon R9 Fury X "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"AMD Radeon R9 M370X Compute Engine "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Hawaii", {
{ Name{"AMD Radeon R9 290X "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Oland", {
{ Name{"Oland "}, Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Pitcairn", {
{ Name{"AMD Radeon R9 270X "}, Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Tahiti", {
{ Name{"AMD Radeon HD 7970 "}, Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Tonga", {
{ Name{"AMD Radeon R9 380 "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "default", {
{ Name{"AMD Radeon Pro 580 Compute Engine "}, Params{ 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // ARM GPUs
kDeviceTypeGPU, "ARM", {
{ "default", {
{ Name{"Mali-T760 "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // Intel CPUs
kDeviceTypeCPU, "Intel", {
{ "default", {
{ Name{"Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz "}, Params{ 64, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i5-4570 CPU @ 3.20GHz "}, Params{ 64, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i5-4590S CPU @ 3.00GHz "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz "}, Params{ 128, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz "}, Params{ 64, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz "}, Params{ 32, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Core(TM) i7-6770HQ CPU @ 2.60GHz "}, Params{ 128, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz "}, Params{ 32, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // Intel accelerators
kDeviceTypeAccelerator, "Intel", {
{ "default", {
{ Name{"Intel(R) Many Integrated Core Acceleration Card "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "SM2.0", {
{ Name{"GeForce GTX 480 "}, Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"GeForce GTX 580 "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "SM3.0", {
{ Name{"GRID K520 "}, Params{ 128, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"GeForce GTX 670 "}, Params{ 128, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"GeForce GTX 760 Ti OEM "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "SM5.2", {
{ Name{"GeForce GTX 970 "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "SM6.0", {
{ Name{"Tesla P100-PCIE-16GB "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "SM6.1", {
{ Name{"GeForce GTX 1070 Ti "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"GeForce GTX 1080 Ti "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "SM7.5", {
{ Name{"TITAN RTX "}, Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "default", {
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", {
{ kDeviceNameDefault , Params{ 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
}
};
} // namespace database
} // namespace clblast
|
[
"web@cedricnugteren.nl"
] |
web@cedricnugteren.nl
|
5bf6b19a2922734f0a0faa47c90bec422e42debc
|
0dfaf37e2a9e8be54e4a65971fe036f7dd3d1c63
|
/IO/IO.cpp
|
edb24668fb9c27f76e5df450afc1655c909f3437
|
[] |
no_license
|
18292677162/C
|
bca08314dee9cd79f550fa41b5278d613fbc8924
|
f400e906169cd69e81b5517c939bc60ce94762d3
|
refs/heads/master
| 2021-07-24T21:26:24.226395
| 2020-04-17T16:00:51
| 2020-04-17T16:00:51
| 149,634,741
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,512
|
cpp
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <fstream>
using namespace std;
struct ServerInfo
{
char _ip[32]; // ip
int _port; // 端口
};
struct ConfigManager
{
public:
ConfigManager(const char* configfile = "server.config")
:_configfile(configfile)
{}
void WriteBin(const ServerInfo& info)
{
// 使用二进制方式打开写
ofstream ofs(_configfile, ifstream::in | ifstream::binary);
ofs.write((const char*)&info, sizeof(ServerInfo));
ofs.close();
}
void ReadBin(ServerInfo& info)
{
// 使用二进制方式打开读
ifstream ifs(_configfile, ifstream::out | ifstream::binary);
ifs.read((char*)&info, sizeof(ServerInfo));
ifs.close();
}
void WriteText(const ServerInfo& info)
{
// C 语言得先把整形itoa再写
ofstream ofs(_configfile);
ofs << info._ip << endl;
ofs << info._port << endl;
ofs.close();
}
void ReadText(ServerInfo& info)
{
// C 语言得先读字符串,再atoi
ifstream ifs(_configfile);
ifs >> info._ip;
ifs >> info._port;
ifs.close();
}
private:
string _configfile; // 配置文件
};
int main()
{
ConfigManager cfgMgr;
ServerInfo wtinfo;
ServerInfo rdinfo;
strcpy(wtinfo._ip, "127.0.0.1");
wtinfo._port = 80;
// 二进制读写
cfgMgr.WriteBin(wtinfo);
cfgMgr.ReadBin(rdinfo);
cout << rdinfo._ip << endl;
cout << rdinfo._port << endl;
// 文本读写
cfgMgr.WriteText(wtinfo);
cfgMgr.ReadText(rdinfo);
cout << rdinfo._ip << endl;
cout << rdinfo._port << endl;
system("pause");
return 0;
}
|
[
"2254095453@qq.com"
] |
2254095453@qq.com
|
a46f7eed3f59928fb0c693cecca8a84bde0cb529
|
149b803d542a838dfa21c24fc533552224c63ce6
|
/AppView/IForm.cpp
|
6e0eb1aabf450fa5f06f05e6739f9ba30756efc1
|
[] |
no_license
|
Elikyu/PROYECTO_DELI_BD
|
9de99d741b27649c669f9c63a9f9639ce6fcf25f
|
55dd1f745b1cf32d93c1ca908a87e3944134887b
|
refs/heads/master
| 2023-06-15T03:32:03.176090
| 2021-07-09T00:47:34
| 2021-07-09T00:47:34
| 383,346,730
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20
|
cpp
|
#include "IForm.h"
|
[
"elizabeth_taipe.1001142@hotmail.com"
] |
elizabeth_taipe.1001142@hotmail.com
|
ef9f6f883092d303072536d9d8fdb3c04d82b219
|
dd80a584130ef1a0333429ba76c1cee0eb40df73
|
/external/chromium/webkit/glue/media/simple_data_source.h
|
2c4075af7e7bc562b54f68327f9b5787d438e0e9
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
karunmatharu/Android-4.4-Pay-by-Data
|
466f4e169ede13c5835424c78e8c30ce58f885c1
|
fcb778e92d4aad525ef7a995660580f948d40bc9
|
refs/heads/master
| 2021-03-24T13:33:01.721868
| 2017-02-18T17:48:49
| 2017-02-18T17:48:49
| 81,847,777
| 0
| 2
|
MIT
| 2020-03-09T00:02:12
| 2017-02-13T16:47:00
| null |
UTF-8
|
C++
| false
| false
| 4,926
|
h
|
// Copyright (c) 2011 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.
// An extremely simple implementation of DataSource that downloads the entire
// media resource into memory before signaling that initialization has finished.
// Primarily used to test <audio> and <video> with buffering/caching removed
// from the equation.
#ifndef WEBKIT_GLUE_MEDIA_SIMPLE_DATA_SOURCE_H_
#define WEBKIT_GLUE_MEDIA_SIMPLE_DATA_SOURCE_H_
#include <algorithm>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "media/base/filter_factories.h"
#include "media/base/filters.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoader.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLResponse.h"
#include "webkit/glue/media/web_data_source.h"
class MessageLoop;
class WebMediaPlayerDelegateImpl;
namespace webkit_glue {
class SimpleDataSource : public WebDataSource,
public WebKit::WebURLLoaderClient {
public:
// Creates a DataSourceFactory for building SimpleDataSource objects.
static media::DataSourceFactory* CreateFactory(
MessageLoop* render_loop,
WebKit::WebFrame* frame,
WebDataSourceBuildObserverHack* build_observer);
SimpleDataSource(MessageLoop* render_loop, WebKit::WebFrame* frame);
virtual ~SimpleDataSource();
// media::Filter implementation.
virtual void set_host(media::FilterHost* host);
virtual void Stop(media::FilterCallback* callback);
// media::DataSource implementation.
virtual const media::MediaFormat& media_format();
virtual void Read(int64 position, size_t size,
uint8* data, ReadCallback* read_callback);
virtual bool GetSize(int64* size_out);
virtual bool IsStreaming();
virtual void SetPreload(media::Preload preload);
// Used to inject a mock used for unittests.
virtual void SetURLLoaderForTest(WebKit::WebURLLoader* mock_loader);
// WebKit::WebURLLoaderClient implementations.
virtual void willSendRequest(
WebKit::WebURLLoader* loader,
WebKit::WebURLRequest& newRequest,
const WebKit::WebURLResponse& redirectResponse);
virtual void didSendData(
WebKit::WebURLLoader* loader,
unsigned long long bytesSent,
unsigned long long totalBytesToBeSent);
virtual void didReceiveResponse(
WebKit::WebURLLoader* loader,
const WebKit::WebURLResponse& response);
virtual void didDownloadData(
WebKit::WebURLLoader* loader,
int dataLength);
virtual void didReceiveData(
WebKit::WebURLLoader* loader,
const char* data,
int dataLength,
int encodedDataLength);
virtual void didReceiveCachedMetadata(
WebKit::WebURLLoader* loader,
const char* data, int dataLength);
virtual void didFinishLoading(
WebKit::WebURLLoader* loader,
double finishTime);
virtual void didFail(
WebKit::WebURLLoader* loader,
const WebKit::WebURLError&);
// webkit_glue::WebDataSource implementation.
virtual void Initialize(const std::string& url,
media::PipelineStatusCallback* callback);
virtual void CancelInitialize();
virtual bool HasSingleOrigin();
virtual void Abort();
private:
// Updates |url_| and |media_format_| with the given URL.
void SetURL(const GURL& url);
// Creates and starts the resource loading on the render thread.
void StartTask();
// Cancels and deletes the resource loading on the render thread.
void CancelTask();
// Perform initialization completion tasks under a lock.
void DoneInitialization_Locked(bool success);
// Update host() stats like total bytes & buffered bytes.
void UpdateHostState();
// Primarily used for asserting the bridge is loading on the render thread.
MessageLoop* render_loop_;
// A webframe for loading.
WebKit::WebFrame* frame_;
// Does the work of loading and sends data back to this client.
scoped_ptr<WebKit::WebURLLoader> url_loader_;
media::MediaFormat media_format_;
GURL url_;
std::string data_;
int64 size_;
bool single_origin_;
// Simple state tracking variable.
enum State {
UNINITIALIZED,
INITIALIZING,
INITIALIZED,
STOPPED,
};
State state_;
// Used for accessing |state_|.
base::Lock lock_;
// Filter callbacks.
scoped_ptr<media::PipelineStatusCallback> initialize_callback_;
// Used to ensure mocks for unittests are used instead of reset in Start().
bool keep_test_loader_;
DISALLOW_COPY_AND_ASSIGN(SimpleDataSource);
};
} // namespace webkit_glue
#endif // WEBKIT_GLUE_MEDIA_SIMPLE_DATA_SOURCE_H_
|
[
"karun.matharu@gmail.com"
] |
karun.matharu@gmail.com
|
e584b5e809a452c9697a258cef48c427c1f493c4
|
8e5202116dda09b2b43b6a87ea61265ed78e9dcf
|
/rmf_traffic/thirdparty/fcl/include/fcl/math/motion/taylor_model/taylor_matrix.h
|
c26f5330982daa37fc511d09ffb9ea04c19a5f5e
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
CLOBOT-Co-Ltd/rmf_traffic
|
2391c465f9d20dbc646eb519a99df76fb5e81df0
|
f1432d8db96db9d69246e10f4c1fe3593f2ed069
|
refs/heads/main
| 2023-08-19T14:29:29.265096
| 2021-09-02T06:18:37
| 2021-09-02T06:18:37
| 404,172,946
| 2
| 0
|
Apache-2.0
| 2021-09-14T06:59:09
| 2021-09-08T01:29:17
| null |
UTF-8
|
C++
| false
| false
| 4,845
|
h
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2014, Willow Garage, Inc.
* Copyright (c) 2014-2016, Open Source Robotics Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Open Source Robotics Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// This code is based on code developed by Stephane Redon at UNC and Inria for the CATCH library: http://graphics.ewha.ac.kr/CATCH/
/** @author Jia Pan */
#ifndef FCL_CCD_TAYLOR_MATRIX_H
#define FCL_CCD_TAYLOR_MATRIX_H
#include "fcl/math/motion/taylor_model/taylor_vector.h"
#include "fcl/math/motion/taylor_model/interval_matrix.h"
namespace fcl
{
template <typename S>
class FCL_EXPORT TMatrix3
{
TVector3<S> v_[3];
public:
TMatrix3();
TMatrix3(const std::shared_ptr<TimeInterval<S>>& time_interval);
TMatrix3(TaylorModel<S> m[3][3]);
TMatrix3(const TVector3<S>& v1, const TVector3<S>& v2, const TVector3<S>& v3);
TMatrix3(const Matrix3<S>& m, const std::shared_ptr<TimeInterval<S>>& time_interval);
TVector3<S> getColumn(size_t i) const;
const TVector3<S>& getRow(size_t i) const;
const TaylorModel<S>& operator () (size_t i, size_t j) const;
TaylorModel<S>& operator () (size_t i, size_t j);
TVector3<S> operator * (const Vector3<S>& v) const;
TVector3<S> operator * (const TVector3<S>& v) const;
TMatrix3 operator * (const Matrix3<S>& m) const;
TMatrix3 operator * (const TMatrix3& m) const;
TMatrix3 operator * (const TaylorModel<S>& d) const;
TMatrix3 operator * (S d) const;
TMatrix3& operator *= (const Matrix3<S>& m);
TMatrix3& operator *= (const TMatrix3& m);
TMatrix3& operator *= (const TaylorModel<S>& d);
TMatrix3& operator *= (S d);
TMatrix3 operator + (const TMatrix3& m) const;
TMatrix3& operator += (const TMatrix3& m);
TMatrix3 operator + (const Matrix3<S>& m) const;
TMatrix3& operator += (const Matrix3<S>& m);
TMatrix3 operator - (const TMatrix3& m) const;
TMatrix3& operator -= (const TMatrix3& m);
TMatrix3 operator - (const Matrix3<S>& m) const;
TMatrix3& operator -= (const Matrix3<S>& m);
TMatrix3 operator - () const;
IMatrix3<S> getBound() const;
IMatrix3<S> getBound(S l, S r) const;
IMatrix3<S> getBound(S t) const;
IMatrix3<S> getTightBound() const;
IMatrix3<S> getTightBound(S l, S r) const;
void print() const;
void setIdentity();
void setZero();
S diameter() const;
void setTimeInterval(const std::shared_ptr<TimeInterval<S>>& time_interval);
void setTimeInterval(S l, S r);
const std::shared_ptr<TimeInterval<S>>& getTimeInterval() const;
TMatrix3& rotationConstrain();
};
template <typename S>
FCL_EXPORT
TMatrix3<S> rotationConstrain(const TMatrix3<S>& m);
template <typename S>
FCL_EXPORT
TMatrix3<S> operator * (const Matrix3<S>& m, const TaylorModel<S>& a);
template <typename S>
FCL_EXPORT
TMatrix3<S> operator * (const TaylorModel<S>& a, const Matrix3<S>& m);
template <typename S>
FCL_EXPORT
TMatrix3<S> operator * (const TaylorModel<S>& a, const TMatrix3<S>& m);
template <typename S>
FCL_EXPORT
TMatrix3<S> operator * (S d, const TMatrix3<S>& m);
template <typename S>
FCL_EXPORT
TMatrix3<S> operator + (const Matrix3<S>& m1, const TMatrix3<S>& m2);
template <typename S>
FCL_EXPORT
TMatrix3<S> operator - (const Matrix3<S>& m1, const TMatrix3<S>& m2);
} // namespace fcl
#include "fcl/math/motion/taylor_model/taylor_matrix-inl.h"
#endif
|
[
"noreply@github.com"
] |
CLOBOT-Co-Ltd.noreply@github.com
|
4e8f688d44131f4c063c4d0b1532f6c61199165e
|
444a9480bce2035565332d4d4654244c0b5cd47b
|
/research/cv/StackedHourglass/infer/mxbase/src/Hourglass.h
|
e7771d2e39a2e98c67eff0b5e9c69458ce2d7973
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
mindspore-ai/models
|
7ede9c6454e77e995e674628204e1c6e76bd7b27
|
eab643f51336dbf7d711f02d27e6516e5affee59
|
refs/heads/master
| 2023-07-20T01:49:34.614616
| 2023-07-17T11:43:18
| 2023-07-17T11:43:18
| 417,393,380
| 301
| 92
|
Apache-2.0
| 2023-05-17T11:22:28
| 2021-10-15T06:38:37
|
Python
|
UTF-8
|
C++
| false
| false
| 2,262
|
h
|
/*
* Copyright 2022 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MXBASE_HOURGLASS_H
#define MXBASE_HOURGLASS_H
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <memory>
#include <opencv4/opencv2/core.hpp>
#include <opencv4/opencv2/opencv.hpp>
#include "MxBase/DeviceManager/DeviceManager.h"
#include "MxBase/ModelInfer/ModelInferenceProcessor.h"
#include "MxBase/PostProcessBases/ObjectPostProcessBase.h"
#include "MxBase/Tensor/TensorContext/TensorContext.h"
struct InitParam {
uint32_t deviceId;
std::string modelPath;
bool checkTensor;
};
float* readCFromFile(std::string path);
float* readSFromFile(std::string path);
float* readNFromFile(std::string path);
cv::Mat readMatFromFile(std::string path);
cv::Mat readGtFromFile(std::string path);
cv::Mat transform_preds(const cv::Mat &cropped_preds, cv::Mat &mat, const float c[], const float s);
void eval();
class Hourglass {
public:
APP_ERROR Init(const InitParam &initParam);
APP_ERROR DeInit();
APP_ERROR ReadInputTensor(const std::string &fileName, MxBase::TensorBase &tensorBase);
APP_ERROR Inference(const std::vector<MxBase::TensorBase> &inputs, std::vector<MxBase::TensorBase> &outputs);
APP_ERROR Process(const std::string &inferPath, const std::string &fileName);
APP_ERROR WriteResult(const std::string &imageFile, std::vector<MxBase::TensorBase> &outputs);
APP_ERROR ParseTensor(MxBase::TensorBase &tensors, MxBase::TensorBase &tensors1);
private:
std::shared_ptr<MxBase::ModelInferenceProcessor> model_;
MxBase::ModelDesc modelDesc_;
uint32_t deviceId_ = 0;
double inferCostTimeMilliSec = 0.0;
};
#endif
|
[
"kangzhaoxiang2018@163.com"
] |
kangzhaoxiang2018@163.com
|
e083faffa5a50f9c0fdf241159dd09658c7ddab4
|
76afe494ac58c7328bbaf149599b99a80916b4eb
|
/problems/1237-find-positive-integer-solution-for-a-given-equation/main.cpp
|
f8bd5f13d2af18113ac46add368a9142a68e3ea3
|
[] |
no_license
|
sugyan/leetcode
|
0c75a1c3de8780f09f7ad89f494b6fc695f72751
|
51f4eda1d6cced76e9eda6110f5912850232ed79
|
refs/heads/master
| 2022-04-26T21:30:53.815814
| 2022-03-31T05:00:29
| 2022-03-31T05:00:31
| 178,538,668
| 12
| 1
| null | 2020-01-04T08:16:22
| 2019-03-30T09:31:57
|
C++
|
UTF-8
|
C++
| false
| false
| 1,688
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
// This is the custom function interface.
// You should not implement it, or speculate about its implementation
class CustomFunction {
public:
// Returns f(x, y) for any given positive integers x and y.
// Note that f(x, y) is increasing with respect to both x and y.
// i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
int f(int x, int y) {
switch (function_id) {
case 1:
return x + y;
case 2:
return x * y;
default:
break;
}
return 0;
}
CustomFunction(int id) {
function_id = id;
}
private:
int function_id = 0;
};
class Solution {
public:
vector<vector<int>> findSolution(CustomFunction& customfunction, int z) {
vector<vector<int>> answer;
int y = 1000;
for (int x = 1; x <= 1000; ++x) {
while (y > 0 && customfunction.f(x, y) > z) --y;
if (y < 1) break;
if (customfunction.f(x, y) == z) {
answer.push_back({ x, y });
}
}
return answer;
}
};
int main() {
vector<pair<CustomFunction, int>> inputs {
{ CustomFunction(1), 5 },
{ CustomFunction(2), 5 },
};
for (auto& input : inputs) {
vector<vector<int>> ret = Solution().findSolution(input.first, input.second);
vector<string> out;
transform(ret.begin(), ret.end(), back_inserter(out), [](vector<int> v) {
return "[" + to_string(v[0]) + ", " + to_string(v[1]) + "]";
});
copy(out.begin(), out.end(), ostream_iterator<string>(cout, ", "));
cout << endl;
}
}
|
[
"sugi1982@gmail.com"
] |
sugi1982@gmail.com
|
8b8ecf5ec576bceb222d35fc12b17740618169d5
|
bdbcd846ebf368ed201fa532a09ee07e0a49d6d1
|
/10579.cpp
|
1e192186125352ce7730c99827a30b63a7975d07
|
[] |
no_license
|
even-wei/uva-practice
|
06373ba5dd5df279020faf368fa3f88e5158bece
|
4cadf6a6102bf21bf6aad19ca787dd3eed2ecc9f
|
refs/heads/master
| 2022-03-27T03:19:35.906557
| 2020-01-14T09:01:00
| 2020-01-14T09:01:00
| 58,897,266
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,246
|
cpp
|
#include <cstdio>
#include <cstring>
using namespace std;
#define BASE 10000000000L
struct elem {
int len;
long digit[102];
};
elem list[100000];
static inline void add(int x)
{
int i;
memcpy(list + x, list + x - 1, sizeof(elem));
for (i = 0; i < list[x].len; ++i)
list[x].digit[i] += list[x - 2].digit[i];
for (i = 0; list[x].digit[i] > 0; ++i) {
list[x].digit[i + 1] += list[x].digit[i] / BASE;
list[x].digit[i] %= BASE;
}
list[x].len = i;
}
void cal(int x)
{
if (list[x - 1].len < 0) cal(x - 1);
add(x);
}
int main(void)
{
int i, n;
memset(list[1].digit, 0, sizeof(long) * 102);
memset(list[2].digit, 0, sizeof(long) * 102);
memset(list[3].digit, 0, sizeof(long) * 102);
list[1].len = 1;
list[1].digit[0] = 1;
list[2].len = 1;
list[2].digit[0] = 1;
list[3].len = 1;
list[3].digit[0] = 2;
for (i = 4; list[i].len < 100; ++i)
add(i);
while (scanf("%d", &n) != EOF) {
if (list[n].len < 0) cal(n);
printf("%ld", list[n].digit[list[n].len - 1]);
for (i = list[n].len - 2; i > -1; --i)
printf("%010ld", list[n].digit[i]);
printf("\n");
}
return 0;
}
|
[
"shinycockorach@gmail.com"
] |
shinycockorach@gmail.com
|
e3f0e0846d3cf50fb6aca5bd79bbf4ed5fa8570c
|
0bb3e9a3d01a9d9503f02bf214bf85932e77d821
|
/13991 - AdvanceNetwork/Random Early Detection/part3.cc
|
610a455b5a437ca9cc4e11f9896c7d0e2e3a3a2c
|
[] |
no_license
|
soheilziaei/academic-projects
|
9e97333d69ee11fc9ba724e78657a19ff296ff48
|
b29e61625a7038217ffb0cf50cc21e74185ca775
|
refs/heads/main
| 2023-08-11T11:08:30.963292
| 2021-09-24T14:05:08
| 2021-09-24T14:05:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,266
|
cc
|
/** Network topology
*
* 100Mb/s, 0.5ms 100Mb/s, 0.5ms
* n0---------------| |---------------n8
* | |
* | |
* 100Mb/s, 1ms | | 100Mb/s, 1ms
* n1---------------| |---------------n9
* | 1.5Mbps/s, 20ms 45Mb/s, 2ms 1.5Mbps/s, 20ms |
* n4-------------------n5-------------------n6-------------------n7
* 100Mb/s, 3ms | <--- Gateway A ----> <--- Gateway B ----> | 100Mb/s, 5ms
* n2---------------| |---------------n10
* | |
* | |
* 100Mb/s, 5ms | | 100Mb/s, 2ms
* n3---------------| |---------------n11
*
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/flow-monitor-helper.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/traffic-control-module.h"
using namespace ns3;
uint32_t checkTimes;
double avgQueueSizeA;
double avgQueueSizeB;
std::stringstream filePlotQueueA;
std::stringstream filePlotQueueAAvg;
std::stringstream filePlotQueueB;
std::stringstream filePlotQueueBAvg;
void
CheckQueueSize (Ptr<QueueDisc> queueA, Ptr<QueueDisc> queueB)
{
uint32_t qSizeA = queueA->GetCurrentSize ().GetValue ();
uint32_t qSizeB = queueB->GetCurrentSize ().GetValue ();
avgQueueSizeA += qSizeA;
avgQueueSizeB += qSizeB;
checkTimes++;
// check queue size every 1/100 of a second
Simulator::Schedule (Seconds (0.01), &CheckQueueSize, queueA, queueB);
std::ofstream fPlotQueueA (filePlotQueueA.str ().c_str (), std::ios::out|std::ios::app);
fPlotQueueA << Simulator::Now ().GetSeconds () << " " << qSizeA << std::endl;
fPlotQueueA.close ();
std::ofstream fPlotQueueAAvg (filePlotQueueAAvg.str ().c_str (), std::ios::out|std::ios::app);
fPlotQueueAAvg << Simulator::Now ().GetSeconds () << " " << avgQueueSizeA / checkTimes << std::endl;
fPlotQueueAAvg.close ();
std::ofstream fPlotQueueB (filePlotQueueB.str ().c_str (), std::ios::out|std::ios::app);
fPlotQueueB << Simulator::Now ().GetSeconds () << " " << qSizeB << std::endl;
fPlotQueueB.close ();
std::ofstream fPlotQueueBAvg (filePlotQueueBAvg.str ().c_str (), std::ios::out|std::ios::app);
fPlotQueueBAvg << Simulator::Now ().GetSeconds () << " " << avgQueueSizeB / checkTimes << std::endl;
fPlotQueueBAvg.close ();
}
int
main (int argc, char *argv[])
{
std::string redLinkDataRate = "1.5Mbps"; // Assumption
std::string redLinkDelay = "20ms"; // Assumption
uint32_t simDuration = 10.0;
std::string pathOut = "./results/part3";
bool writeForPlot = true;
bool writePcap = true;
bool flowMonitor = false;
bool printRedStats = true;
// Configuration and command line parameter parsing
// Will only save in the directory if enable opts below
CommandLine cmd (__FILE__);
cmd.AddValue ("simDuration", "Simulation duration", simDuration);
cmd.AddValue ("pathOut", "Path to save results from --writeForPlot/--writePcap/--writeFlowMonitor", pathOut);
cmd.AddValue ("writeForPlot", "<0/1> to write results for plot (gnuplot)", writeForPlot);
cmd.AddValue ("writePcap", "<0/1> to write results in pcapfile", writePcap);
cmd.AddValue ("writeFlowMonitor", "<0/1> to enable Flow Monitor and write their results", flowMonitor);
cmd.Parse (argc, argv);
SeedManager::SetSeed(1);
SeedManager::SetRun (0);
Time::SetResolution (Time::NS);
// Create nodes
NodeContainer nodes;
nodes.Create (12);
Config::SetDefault ("ns3::TcpL4Protocol::SocketType", StringValue ("ns3::TcpNewReno"));
// 42 = headers size
Config::SetDefault ("ns3::TcpSocket::SegmentSize", UintegerValue (1000 - 42));
Config::SetDefault ("ns3::TcpSocket::DelAckCount", UintegerValue (1));
GlobalValue::Bind ("ChecksumEnabled", BooleanValue (false));
uint32_t meanPktSize = 500;
// RED params
Config::SetDefault ("ns3::RedQueueDisc::MaxSize", StringValue ("1000p"));
Config::SetDefault ("ns3::RedQueueDisc::MeanPktSize", UintegerValue (meanPktSize));
Config::SetDefault ("ns3::RedQueueDisc::Wait", BooleanValue (true));
Config::SetDefault ("ns3::RedQueueDisc::Gentle", BooleanValue (true));
Config::SetDefault ("ns3::RedQueueDisc::LInterm", DoubleValue (0.02));
Config::SetDefault ("ns3::RedQueueDisc::QW", DoubleValue (0.002));
Config::SetDefault ("ns3::RedQueueDisc::MinTh", DoubleValue (5));
Config::SetDefault ("ns3::RedQueueDisc::MaxTh", DoubleValue (15));
// Install internet stack on all nodes
InternetStackHelper internet;
internet.Install (nodes);
TrafficControlHelper tchPfifo;
uint16_t handle = tchPfifo.SetRootQueueDisc ("ns3::PfifoFastQueueDisc");
tchPfifo.AddInternalQueues (handle, 3, "ns3::DropTailQueue", "MaxSize", StringValue ("1000p"));
TrafficControlHelper tchRed;
tchRed.SetRootQueueDisc ("ns3::RedQueueDisc", "LinkBandwidth", StringValue (redLinkDataRate),
"LinkDelay", StringValue (redLinkDelay));
// Create channels
PointToPointHelper p2p;
p2p.SetQueue ("ns3::DropTailQueue");
p2p.SetDeviceAttribute ("DataRate", StringValue ("100Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("0.5ms"));
NetDeviceContainer devn0n4 = p2p.Install (nodes.Get(0), nodes.Get(4));
tchPfifo.Install (devn0n4);
p2p.SetChannelAttribute ("Delay", StringValue ("1ms"));
NetDeviceContainer devn1n4 = p2p.Install (nodes.Get(1), nodes.Get(4));
tchPfifo.Install (devn1n4);
p2p.SetChannelAttribute ("Delay", StringValue ("3ms"));
NetDeviceContainer devn2n4 = p2p.Install (nodes.Get(2), nodes.Get(4));
tchPfifo.Install (devn2n4);
p2p.SetChannelAttribute ("Delay", StringValue ("5ms"));
NetDeviceContainer devn3n4 = p2p.Install (nodes.Get(3), nodes.Get(4));
tchPfifo.Install (devn3n4);
p2p.SetChannelAttribute ("Delay", StringValue ("0.5ms"));
NetDeviceContainer devn7n8 = p2p.Install (nodes.Get(7), nodes.Get(8));
tchPfifo.Install (devn7n8);
p2p.SetChannelAttribute ("Delay", StringValue ("1ms"));
NetDeviceContainer devn7n9 = p2p.Install (nodes.Get(7), nodes.Get(9));
tchPfifo.Install (devn7n9);
p2p.SetChannelAttribute ("Delay", StringValue ("5ms"));
NetDeviceContainer devn7n10 = p2p.Install (nodes.Get(7), nodes.Get(10));
tchPfifo.Install (devn7n10);
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devn7n11 = p2p.Install (nodes.Get(7), nodes.Get(11));
tchPfifo.Install (devn7n11);
p2p.SetDeviceAttribute ("DataRate", StringValue ("45Mbps"));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devn5n6 = p2p.Install (nodes.Get(5), nodes.Get(6));
tchPfifo.Install (devn5n6);
p2p.SetQueue ("ns3::DropTailQueue");
p2p.SetDeviceAttribute ("DataRate", StringValue (redLinkDataRate));
p2p.SetChannelAttribute ("Delay", StringValue (redLinkDelay));
NetDeviceContainer devn4n5 = p2p.Install (nodes.Get(4), nodes.Get(5));
NetDeviceContainer devn6n7 = p2p.Install (nodes.Get(6), nodes.Get(7));
// only backbone link has RED queue disc
QueueDiscContainer queueDiscsA = tchRed.Install (devn4n5);
QueueDiscContainer queueDiscsB = tchRed.Install (devn6n7);
// Assign IP Addresses
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.0.0", "255.255.255.0");
Ipv4InterfaceContainer i0i4 = ipv4.Assign (devn0n4);
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer i1i4 = ipv4.Assign (devn1n4);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer i2i4 = ipv4.Assign (devn2n4);
ipv4.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i3i4 = ipv4.Assign (devn3n4);
ipv4.SetBase ("10.1.4.0", "255.255.255.0");
Ipv4InterfaceContainer i4i5 = ipv4.Assign (devn4n5);
ipv4.SetBase ("10.1.5.0", "255.255.255.0");
Ipv4InterfaceContainer i5i6 = ipv4.Assign (devn5n6);
ipv4.SetBase ("10.1.6.0", "255.255.255.0");
Ipv4InterfaceContainer i6i7 = ipv4.Assign (devn6n7);
ipv4.SetBase ("10.1.7.0", "255.255.255.0");
Ipv4InterfaceContainer i7i8 = ipv4.Assign (devn7n8);
ipv4.SetBase ("10.1.8.0", "255.255.255.0");
Ipv4InterfaceContainer i7i9 = ipv4.Assign (devn7n9);
ipv4.SetBase ("10.1.9.0", "255.255.255.0");
Ipv4InterfaceContainer i7i10 = ipv4.Assign (devn7n10);
ipv4.SetBase ("10.1.10.0", "255.255.255.0");
Ipv4InterfaceContainer i7i11 = ipv4.Assign (devn7n11);
// Set up the routing
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Create applications
// SINK is installed on n0, n1, n2, n3, n8, n9, n10, n11
uint16_t port = 50000;
ApplicationContainer sinkApp;
Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
PacketSinkHelper sinkHelper ("ns3::TcpSocketFactory", sinkLocalAddress);
sinkApp = sinkHelper.Install (nodes.Get(0));
sinkApp = sinkHelper.Install (nodes.Get(1));
sinkApp = sinkHelper.Install (nodes.Get(2));
sinkApp = sinkHelper.Install (nodes.Get(3));
sinkApp = sinkHelper.Install (nodes.Get(8));
sinkApp = sinkHelper.Install (nodes.Get(9));
sinkApp = sinkHelper.Install (nodes.Get(10));
sinkApp = sinkHelper.Install (nodes.Get(11));
// Sender is installed on n0, n1, n2, n3, n8, n9, n10, n11
ApplicationContainer sendApp;
BulkSendHelper bulkSend ("ns3::TcpSocketFactory", Address ());
AddressValue remoteAddress
(InetSocketAddress (i7i8.GetAddress (1), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(0));
remoteAddress = AddressValue (InetSocketAddress (i7i9.GetAddress (1), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(1));
remoteAddress = AddressValue (InetSocketAddress (i7i10.GetAddress (1), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(2));
remoteAddress = AddressValue (InetSocketAddress (i7i11.GetAddress (1), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(3));
remoteAddress = AddressValue (InetSocketAddress (i0i4.GetAddress (0), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(8));
remoteAddress = AddressValue (InetSocketAddress (i1i4.GetAddress (0), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(9));
remoteAddress = AddressValue (InetSocketAddress (i2i4.GetAddress (0), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(10));
remoteAddress = AddressValue (InetSocketAddress (i3i4.GetAddress (0), port));
bulkSend.SetAttribute ("Remote", remoteAddress);
sendApp = bulkSend.Install (nodes.Get(11));
if (writePcap)
{
PointToPointHelper ptp;
std::stringstream stmp;
stmp << pathOut << "/red";
ptp.EnablePcapAll (stmp.str ().c_str ());
}
Ptr<FlowMonitor> flowmon;
if (flowMonitor)
{
FlowMonitorHelper flowmonHelper;
flowmon = flowmonHelper.InstallAll ();
}
if (writeForPlot)
{
filePlotQueueA << pathOut << "/" << "red-queue-A.plotme";
filePlotQueueAAvg << pathOut << "/" << "red-queue-A_avg.plotme";
remove (filePlotQueueA.str ().c_str ());
remove (filePlotQueueAAvg.str ().c_str ());
Ptr<QueueDisc> queueA = queueDiscsA.Get (0);
filePlotQueueB << pathOut << "/" << "red-queue-B.plotme";
filePlotQueueBAvg << pathOut << "/" << "red-queue-B_avg.plotme";
remove (filePlotQueueB.str ().c_str ());
remove (filePlotQueueBAvg.str ().c_str ());
Ptr<QueueDisc> queueB = queueDiscsB.Get (1);
Simulator::ScheduleNow (&CheckQueueSize, queueA, queueB);
}
Simulator::Stop (Seconds (simDuration));
Simulator::Run ();
if (flowMonitor)
{
std::stringstream stmp;
stmp << pathOut << "/red.flowmon";
flowmon->SerializeToXmlFile (stmp.str ().c_str (), false, false);
}
if (printRedStats)
{
QueueDisc::Stats st = queueDiscsA.Get (0)->GetStats ();
std::cout << "*** RED stats from Node 4 queue disc ***" << std::endl;
std::cout << st << std::endl;
st = queueDiscsA.Get (1)->GetStats ();
std::cout << "*** RED stats from Node 5 queue disc ***" << std::endl;
std::cout << st << std::endl;
st = queueDiscsB.Get (0)->GetStats ();
std::cout << "*** RED stats from Node 6 queue disc ***" << std::endl;
std::cout << st << std::endl;
st = queueDiscsB.Get (1)->GetStats ();
std::cout << "*** RED stats from Node 7 queue disc ***" << std::endl;
std::cout << st << std::endl;
}
Simulator::Destroy ();
return 0;
}
|
[
"noreply@github.com"
] |
soheilziaei.noreply@github.com
|
8598ed6b41eaf3672156933d315f600aef287b33
|
bcfa4542685ec72508b7f005f8cb910f497b7ef1
|
/src/menus/menu_main_info.h
|
23251d2902f1becfa2d65605c94e19aecccd04a3
|
[] |
no_license
|
proconsule/pplay
|
207997b7bf729b2abd15f63880551712c9d52ddd
|
258428e3d703a208c3c0852a905144faacd3d7a6
|
refs/heads/master
| 2023-08-19T14:14:39.137188
| 2021-10-18T08:53:40
| 2021-10-18T08:53:40
| 414,898,630
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 448
|
h
|
//
// Created by proconsule on 12/10/21.
//
#ifndef PPLAY_MENU_MAIN_INFO_H
#define PPLAY_MENU_MAIN_INFO_H
#include "menu.h"
class MenuMainInfo : public Menu {
public:
MenuMainInfo(Main *main, const c2d::FloatRect &rect, const std::vector<MenuItem> &items);
private:
bool onInput(c2d::Input::Player *players) override;
void onOptionSelection(MenuItem *item) override;
};
#endif //PPLAY_MENU_MAIN_INFO_H
|
[
"34319995+proconsule@users.noreply.github.com"
] |
34319995+proconsule@users.noreply.github.com
|
84dcdf7c4dfbcdc7c98c163ce783039b0d8e92db
|
5b4da825e536f570a464ae9f5d7f377fc16e12b7
|
/externals/wasm-compiler/llvm/lib/Target/Hexagon/HexagonSubtarget.cpp
|
8c23a2465dd6328c542eaf26696675e44866b58c
|
[
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"NCSA"
] |
permissive
|
JaminChan/eos_win
|
9ecb3fe7d1fbb52340e7b8df42b2d3d6695930a6
|
c03e57151cfe152d0d3120abb13226f4df74f37e
|
refs/heads/master
| 2020-03-24T20:38:49.539494
| 2018-09-06T10:13:16
| 2018-09-06T10:13:16
| 142,989,586
| 0
| 0
|
MIT
| 2018-09-04T06:49:10
| 2018-07-31T09:02:44
|
C++
|
UTF-8
|
C++
| false
| false
| 13,009
|
cpp
|
//===-- HexagonSubtarget.cpp - Hexagon Subtarget Information --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Hexagon specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "HexagonSubtarget.h"
#include "Hexagon.h"
#include "HexagonRegisterInfo.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/CodeGen/ScheduleDAGInstrs.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include <map>
using namespace llvm;
#define DEBUG_TYPE "hexagon-subtarget"
#define GET_SUBTARGETINFO_CTOR
#define GET_SUBTARGETINFO_TARGET_DESC
#include "HexagonGenSubtargetInfo.inc"
static cl::opt<bool> EnableMemOps("enable-hexagon-memops",
cl::Hidden, cl::ZeroOrMore, cl::ValueDisallowed, cl::init(true),
cl::desc("Generate V4 MEMOP in code generation for Hexagon target"));
static cl::opt<bool> DisableMemOps("disable-hexagon-memops",
cl::Hidden, cl::ZeroOrMore, cl::ValueDisallowed, cl::init(false),
cl::desc("Do not generate V4 MEMOP in code generation for Hexagon target"));
static cl::opt<bool> EnableIEEERndNear("enable-hexagon-ieee-rnd-near",
cl::Hidden, cl::ZeroOrMore, cl::init(false),
cl::desc("Generate non-chopped conversion from fp to int."));
static cl::opt<bool> EnableBSBSched("enable-bsb-sched",
cl::Hidden, cl::ZeroOrMore, cl::init(true));
static cl::opt<bool> EnableHexagonHVXDouble("enable-hexagon-hvx-double",
cl::Hidden, cl::ZeroOrMore, cl::init(false),
cl::desc("Enable Hexagon Double Vector eXtensions"));
static cl::opt<bool> EnableHexagonHVX("enable-hexagon-hvx",
cl::Hidden, cl::ZeroOrMore, cl::init(false),
cl::desc("Enable Hexagon Vector eXtensions"));
static cl::opt<bool> EnableTCLatencySched("enable-tc-latency-sched",
cl::Hidden, cl::ZeroOrMore, cl::init(false));
static cl::opt<bool> EnableDotCurSched("enable-cur-sched",
cl::Hidden, cl::ZeroOrMore, cl::init(true),
cl::desc("Enable the scheduler to generate .cur"));
static cl::opt<bool> EnableVecFrwdSched("enable-evec-frwd-sched",
cl::Hidden, cl::ZeroOrMore, cl::init(true));
static cl::opt<bool> DisableHexagonMISched("disable-hexagon-misched",
cl::Hidden, cl::ZeroOrMore, cl::init(false),
cl::desc("Disable Hexagon MI Scheduling"));
static cl::opt<bool> EnableSubregLiveness("hexagon-subreg-liveness",
cl::Hidden, cl::ZeroOrMore, cl::init(true),
cl::desc("Enable subregister liveness tracking for Hexagon"));
static cl::opt<bool> OverrideLongCalls("hexagon-long-calls",
cl::Hidden, cl::ZeroOrMore, cl::init(false),
cl::desc("If present, forces/disables the use of long calls"));
void HexagonSubtarget::initializeEnvironment() {
UseMemOps = false;
ModeIEEERndNear = false;
UseBSBScheduling = false;
}
HexagonSubtarget &
HexagonSubtarget::initializeSubtargetDependencies(StringRef CPU, StringRef FS) {
CPUString = Hexagon_MC::selectHexagonCPU(getTargetTriple(), CPU);
static std::map<StringRef, HexagonArchEnum> CpuTable {
{ "hexagonv4", V4 },
{ "hexagonv5", V5 },
{ "hexagonv55", V55 },
{ "hexagonv60", V60 },
};
auto foundIt = CpuTable.find(CPUString);
if (foundIt != CpuTable.end())
HexagonArchVersion = foundIt->second;
else
llvm_unreachable("Unrecognized Hexagon processor version");
UseHVXOps = false;
UseHVXDblOps = false;
UseLongCalls = false;
ParseSubtargetFeatures(CPUString, FS);
if (EnableHexagonHVX.getPosition())
UseHVXOps = EnableHexagonHVX;
if (EnableHexagonHVXDouble.getPosition())
UseHVXDblOps = EnableHexagonHVXDouble;
if (OverrideLongCalls.getPosition())
UseLongCalls = OverrideLongCalls;
return *this;
}
HexagonSubtarget::HexagonSubtarget(const Triple &TT, StringRef CPU,
StringRef FS, const TargetMachine &TM)
: HexagonGenSubtargetInfo(TT, CPU, FS), CPUString(CPU),
InstrInfo(initializeSubtargetDependencies(CPU, FS)), TLInfo(TM, *this),
FrameLowering() {
initializeEnvironment();
// Initialize scheduling itinerary for the specified CPU.
InstrItins = getInstrItineraryForCPU(CPUString);
// UseMemOps on by default unless disabled explicitly
if (DisableMemOps)
UseMemOps = false;
else if (EnableMemOps)
UseMemOps = true;
else
UseMemOps = false;
if (EnableIEEERndNear)
ModeIEEERndNear = true;
else
ModeIEEERndNear = false;
UseBSBScheduling = hasV60TOps() && EnableBSBSched;
}
void HexagonSubtarget::HexagonDAGMutation::apply(ScheduleDAGInstrs *DAG) {
for (auto &SU : DAG->SUnits) {
if (!SU.isInstr())
continue;
SmallVector<SDep, 4> Erase;
for (auto &D : SU.Preds)
if (D.getKind() == SDep::Output && D.getReg() == Hexagon::USR_OVF)
Erase.push_back(D);
for (auto &E : Erase)
SU.removePred(E);
}
for (auto &SU : DAG->SUnits) {
// Update the latency of chain edges between v60 vector load or store
// instructions to be 1. These instructions cannot be scheduled in the
// same packet.
MachineInstr &MI1 = *SU.getInstr();
auto *QII = static_cast<const HexagonInstrInfo*>(DAG->TII);
bool IsStoreMI1 = MI1.mayStore();
bool IsLoadMI1 = MI1.mayLoad();
if (!QII->isV60VectorInstruction(MI1) || !(IsStoreMI1 || IsLoadMI1))
continue;
for (auto &SI : SU.Succs) {
if (SI.getKind() != SDep::Order || SI.getLatency() != 0)
continue;
MachineInstr &MI2 = *SI.getSUnit()->getInstr();
if (!QII->isV60VectorInstruction(MI2))
continue;
if ((IsStoreMI1 && MI2.mayStore()) || (IsLoadMI1 && MI2.mayLoad())) {
SI.setLatency(1);
SU.setHeightDirty();
// Change the dependence in the opposite direction too.
for (auto &PI : SI.getSUnit()->Preds) {
if (PI.getSUnit() != &SU || PI.getKind() != SDep::Order)
continue;
PI.setLatency(1);
SI.getSUnit()->setDepthDirty();
}
}
}
}
}
void HexagonSubtarget::getPostRAMutations(
std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
Mutations.push_back(make_unique<HexagonSubtarget::HexagonDAGMutation>());
}
void HexagonSubtarget::getSMSMutations(
std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
Mutations.push_back(make_unique<HexagonSubtarget::HexagonDAGMutation>());
}
// Pin the vtable to this file.
void HexagonSubtarget::anchor() {}
bool HexagonSubtarget::enableMachineScheduler() const {
if (DisableHexagonMISched.getNumOccurrences())
return !DisableHexagonMISched;
return true;
}
bool HexagonSubtarget::enableSubRegLiveness() const {
return EnableSubregLiveness;
}
// This helper function is responsible for increasing the latency only.
void HexagonSubtarget::updateLatency(MachineInstr &SrcInst,
MachineInstr &DstInst, SDep &Dep) const {
if (!hasV60TOps())
return;
auto &QII = static_cast<const HexagonInstrInfo&>(*getInstrInfo());
if (EnableVecFrwdSched && QII.addLatencyToSchedule(SrcInst, DstInst)) {
// Vec frwd scheduling.
Dep.setLatency(Dep.getLatency() + 1);
} else if (useBSBScheduling() &&
QII.isLateInstrFeedsEarlyInstr(SrcInst, DstInst)) {
// BSB scheduling.
Dep.setLatency(Dep.getLatency() + 1);
} else if (EnableTCLatencySched) {
// TClass latency scheduling.
// Check if SrcInst produces in 2C an operand of DstInst taken in stage 2B.
if (QII.isTC1(SrcInst) || QII.isTC2(SrcInst))
if (!QII.isTC1(DstInst) && !QII.isTC2(DstInst))
Dep.setLatency(Dep.getLatency() + 1);
}
}
/// If the SUnit has a zero latency edge, return the other SUnit.
static SUnit *getZeroLatency(SUnit *N, SmallVector<SDep, 4> &Deps) {
for (auto &I : Deps)
if (I.isAssignedRegDep() && I.getLatency() == 0 &&
!I.getSUnit()->getInstr()->isPseudo())
return I.getSUnit();
return nullptr;
}
/// Change the latency between the two SUnits.
void HexagonSubtarget::changeLatency(SUnit *Src, SmallVector<SDep, 4> &Deps,
SUnit *Dst, unsigned Lat) const {
MachineInstr &SrcI = *Src->getInstr();
for (auto &I : Deps) {
if (I.getSUnit() != Dst)
continue;
I.setLatency(Lat);
SUnit *UpdateDst = I.getSUnit();
updateLatency(SrcI, *UpdateDst->getInstr(), I);
// Update the latency of opposite edge too.
for (auto &PI : UpdateDst->Preds) {
if (PI.getSUnit() != Src || !PI.isAssignedRegDep())
continue;
PI.setLatency(Lat);
updateLatency(SrcI, *UpdateDst->getInstr(), PI);
}
}
}
// Return true if these are the best two instructions to schedule
// together with a zero latency. Only one dependence should have a zero
// latency. If there are multiple choices, choose the best, and change
// ther others, if needed.
bool HexagonSubtarget::isBestZeroLatency(SUnit *Src, SUnit *Dst,
const HexagonInstrInfo *TII) const {
MachineInstr &SrcInst = *Src->getInstr();
MachineInstr &DstInst = *Dst->getInstr();
// Ignore Boundary SU nodes as these have null instructions.
if (Dst->isBoundaryNode())
return false;
if (SrcInst.isPHI() || DstInst.isPHI())
return false;
// Check if the Dst instruction is the best candidate first.
SUnit *Best = nullptr;
SUnit *DstBest = nullptr;
SUnit *SrcBest = getZeroLatency(Dst, Dst->Preds);
if (SrcBest == nullptr || Src->NodeNum >= SrcBest->NodeNum) {
// Check that Src doesn't have a better candidate.
DstBest = getZeroLatency(Src, Src->Succs);
if (DstBest == nullptr || Dst->NodeNum <= DstBest->NodeNum)
Best = Dst;
}
if (Best != Dst)
return false;
// The caller frequents adds the same dependence twice. If so, then
// return true for this case too.
if (Src == SrcBest && Dst == DstBest)
return true;
// Reassign the latency for the previous bests, which requires setting
// the dependence edge in both directions.
if (SrcBest != nullptr)
changeLatency(SrcBest, SrcBest->Succs, Dst, 1);
if (DstBest != nullptr)
changeLatency(Src, Src->Succs, DstBest, 1);
// If there is an edge from SrcBest to DstBst, then try to change that
// to 0 now.
if (SrcBest && DstBest)
changeLatency(SrcBest, SrcBest->Succs, DstBest, 0);
return true;
}
// Update the latency of a Phi when the Phi bridges two instructions that
// require a multi-cycle latency.
void HexagonSubtarget::changePhiLatency(MachineInstr &SrcInst, SUnit *Dst,
SDep &Dep) const {
if (!SrcInst.isPHI() || Dst->NumPreds == 0 || Dep.getLatency() != 0)
return;
for (const SDep &PI : Dst->Preds) {
if (PI.getLatency() != 0)
continue;
Dep.setLatency(2);
break;
}
}
/// \brief Perform target specific adjustments to the latency of a schedule
/// dependency.
void HexagonSubtarget::adjustSchedDependency(SUnit *Src, SUnit *Dst,
SDep &Dep) const {
MachineInstr *SrcInst = Src->getInstr();
MachineInstr *DstInst = Dst->getInstr();
if (!Src->isInstr() || !Dst->isInstr())
return;
const HexagonInstrInfo *QII = static_cast<const HexagonInstrInfo *>(getInstrInfo());
// Instructions with .new operands have zero latency.
if (QII->canExecuteInBundle(*SrcInst, *DstInst) &&
isBestZeroLatency(Src, Dst, QII)) {
Dep.setLatency(0);
return;
}
if (!hasV60TOps())
return;
// Don't adjust the latency of post-increment part of the instruction.
if (QII->isPostIncrement(*SrcInst) && Dep.isAssignedRegDep()) {
if (SrcInst->mayStore())
return;
if (Dep.getReg() != SrcInst->getOperand(0).getReg())
return;
} else if (QII->isPostIncrement(*DstInst) && Dep.getKind() == SDep::Anti) {
if (DstInst->mayStore())
return;
if (Dep.getReg() != DstInst->getOperand(0).getReg())
return;
} else if (QII->isPostIncrement(*DstInst) && DstInst->mayStore() &&
Dep.isAssignedRegDep()) {
MachineOperand &Op = DstInst->getOperand(DstInst->getNumOperands() - 1);
if (Op.isReg() && Dep.getReg() != Op.getReg())
return;
}
// Check if we need to change any the latency values when Phis are added.
if (useBSBScheduling() && SrcInst->isPHI()) {
changePhiLatency(*SrcInst, Dst, Dep);
return;
}
// If it's a REG_SEQUENCE, use its destination instruction to determine
// the correct latency.
if (DstInst->isRegSequence() && Dst->NumSuccs == 1)
DstInst = Dst->Succs[0].getSUnit()->getInstr();
// Try to schedule uses near definitions to generate .cur.
if (EnableDotCurSched && QII->isToBeScheduledASAP(*SrcInst, *DstInst) &&
isBestZeroLatency(Src, Dst, QII)) {
Dep.setLatency(0);
return;
}
updateLatency(*SrcInst, *DstInst, Dep);
}
unsigned HexagonSubtarget::getL1CacheLineSize() const {
return 32;
}
unsigned HexagonSubtarget::getL1PrefetchDistance() const {
return 32;
}
|
[
"349683504@qq.com"
] |
349683504@qq.com
|
caeb3de663872d3dcfe4204558c80b329dde2767
|
3bc3f080f46a6897c6d88f036c784c63b3673979
|
/src/mame/includes/gng.h
|
f50286d0c001b33ce4b142d267b21ca435e9f74f
|
[] |
no_license
|
vikke/mame_0145
|
bec0f81aba918c8ca5579a13f72e3c8efc7d0065
|
e9b4636543b017c2a6cdd6cddeab4afc02740241
|
refs/heads/master
| 2021-07-04T03:00:14.861010
| 2021-06-02T10:07:17
| 2021-06-02T10:07:17
| 4,586,522
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,130
|
h
|
/*************************************************************************
Ghosts'n Goblins
*************************************************************************/
class gng_state : public driver_device
{
public:
gng_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag) { }
/* memory pointers */
UINT8 * m_bgvideoram;
UINT8 * m_fgvideoram;
// UINT8 * m_paletteram; // currently this uses generic palette handling
// UINT8 * m_paletteram2; // currently this uses generic palette handling
// UINT8 * m_spriteram; // currently this uses generic buffered spriteram
/* video-related */
tilemap_t *m_bg_tilemap;
tilemap_t *m_fg_tilemap;
UINT8 m_scrollx[2];
UINT8 m_scrolly[2];
};
/*----------- defined in video/gng.c -----------*/
WRITE8_HANDLER( gng_fgvideoram_w );
WRITE8_HANDLER( gng_bgvideoram_w );
WRITE8_HANDLER( gng_bgscrollx_w );
WRITE8_HANDLER( gng_bgscrolly_w );
WRITE8_HANDLER( gng_flipscreen_w );
VIDEO_START( gng );
SCREEN_UPDATE_IND16( gng );
SCREEN_VBLANK( gng );
|
[
"vikke.bsd@gmail.com"
] |
vikke.bsd@gmail.com
|
1a1b95059b8b1e1bc2e2c12081ff13998d292814
|
71cae6e39c666be24a1e5c55e110a15a0d65faed
|
/Max Sum k/max sum k/max sum k/main.cpp
|
a3b7fe9447188e3d853f64715149df47f3083377
|
[] |
no_license
|
crazyjerryh/Practice
|
18bb7a885e7652ba867fbbe8cf844d56cf19eb29
|
e8862083d37066dac1a395c652e2f36793ab48e3
|
refs/heads/master
| 2021-01-18T13:57:26.490761
| 2015-10-29T14:08:45
| 2015-10-29T14:08:45
| 33,871,665
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 995
|
cpp
|
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define maxn 100010
#define inf 0x3f3f3f3f
int tcase;
int a[maxn],q[maxn];
int sum[maxn];
int n,k;
int main(void){
freopen("debug.txt","r",stdin);
scanf("%d",&tcase);
while(tcase--){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(int i=n+1;i<n+k;i++){
a[i]=a[i-n];
}
sum[1]=0;
for(int i=2;i<n+k;i++){
sum[i]=sum[i-1]+a[i-1];
}
int front,last;
front=last=0;
int ans=-inf,first,second;
int l,r;
for(int i=1;i<n+k;i++){
r=i;
while(front<last&&sum[q[last-1]]>sum[i]) last--;
q[last++]=i;
l=q[front];
int t=r-l+1;
while(t>k){
l=q[++front];
t=r-l+1;
}
if(t<=k){
int tmp;
if((tmp=sum[r]+a[r]-sum[q[front]])>ans){
ans=tmp;
first=q[front],second=r;
}
}
}
if(first>n) first=first%n;
if(second>n) second=second%n;
printf("%d %d %d\n",ans,first,second);
}
return 0;
}
|
[
"maggiexxqhh@163.com"
] |
maggiexxqhh@163.com
|
dea5960fc7a1f24955a3605f4d09651ba154c1fa
|
1b6b94ecbd7f8882ca0609c39bcfb09affc9bb77
|
/CH13/13-1.cpp
|
7e9104b9146363106adda29ae606a9eefe4dc367
|
[] |
no_license
|
NLGRF/Course_Cpp
|
112bd9ed50e7d67b3a8c9b4627add0c8a46d65fe
|
6acd21aba9fce805bd530d1234554783f710ff3b
|
refs/heads/master
| 2020-03-21T05:46:16.328372
| 2018-06-21T14:11:33
| 2018-06-21T14:11:33
| 138,178,836
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,057
|
cpp
|
#include <iostream>
using namespace std;
class Shape
{
protected:
float width;
float height;
float radius;
public:
virtual float getArea() = 0;
void setWH(float w,float h){
width = w;
height = h;
}
void setR(float r){
radius = r;
}
};
class Rectangle: public Shape
{
public:
float getArea(){
return (width * height);
}
};
class Triangle: public Shape
{
public:
float getArea(){
return (width * height)/2;
}
};
class Circle: public Shape {
public:
float getArea(){
return (3.14*radius*radius);
}
};
int main()
{
Rectangle Rect;
Triangle Tri;
Circle Cir;
float w, h, r;
cout << " Enter width : ";
cin >> w;
cout << " Enter height : ";
cin >> h;
cout << " Enter radius : ";
cin >> r;
Rect.setWH(w, h);
cout << " Rectangle area: " << Rect.getArea() << endl;
Tri.setWH(w, h);
cout << " Triangle area: " << Tri.getArea() << endl;
Cir.setR(r);
cout << " Circle area: " << Cir.getArea() << endl;
return 0;
}
|
[
"non.devtech@gmail.com"
] |
non.devtech@gmail.com
|
64f5576a575e7cda0ddac9c481115cc4a7fc2adb
|
770ac2dd33e1a0c8030be06cfcb26a6d89a3f01f
|
/lab 11/prob1/main.cpp
|
ae8a9678d22d2ceabf608d0003d3c7bfb340b605
|
[] |
no_license
|
yashvanjani/MA253-Data-Structures-Lab
|
837edcad40687dfb98c9ae60a1009fc8eea30a22
|
e2ab6d328a0089b5ade9118e4589f6e72037140a
|
refs/heads/master
| 2021-01-21T12:59:07.311927
| 2016-04-16T17:50:37
| 2016-04-16T17:50:37
| 54,201,834
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 682
|
cpp
|
#include <iostream>
#include "lis.h"
using namespace std;
int main(int argc, char *argv[])
{
int n, *A, i,j;
cout<<"Enter length of sequence\n";
cin>>n; A = new int[n];
cout<<"Enter "<<n<<" integers\n";
for(i=0;i<n;i++) cin>>A[i];
int m, *B;
lis(n,A,m,B);
if(argc>1)
{
cout<<"m = "<<m<<endl;
for(i=0,j=0;i<n;i++)
{
cout<<"A["<<i<<"]="<<A[i];
if(i==B[j]) {cout<<"\tB["<<j<<"]="<<i;j++;}
cout<<endl;
}
}
for(i=1;i<m;i++)
{
if(B[i]<=B[i-1]) {cout<<"Error: B[i]<=B[i-1] for i="<<i<<"B["<<i<<"]="<<B[i]<<",B["<<(i-1)<<"]="<<B[i-1];return 1;}
if(B[i]<B[i-1]) {cout<<"Error: B[i]<B[i-1] for i="<<i;return 2;}
}
cout<<"Length of LIS is "<<m<<endl;
}
|
[
"yashvanjani@hotmail.com"
] |
yashvanjani@hotmail.com
|
43cf64c14d9b7a8fc1def3bedade5a3b19b95f3e
|
1cbb1d2395055800942011b81a4629a59a342176
|
/CODE_dizzys/refreshDIZZYS_2015_10_23/lan2/dizzysNewInfec/src/adapSEIRNewInfec.cpp
|
3bf9c22671c17e4c1f9f5c41b6deb4a860adfd03
|
[] |
no_license
|
ttcgiang/THESE_GitHub
|
e783f4de184b8abc350c740e9dab83c2c493c6b4
|
c13af9dfc6bfcb6270ec2fa1230dca5893ade185
|
refs/heads/master
| 2020-04-06T06:58:35.019224
| 2017-06-01T11:05:36
| 2017-06-01T11:05:36
| 38,418,770
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 66,739
|
cpp
|
/*
$Id: seir_adaptivetau.cpp$
Created by TRAN Thi Cam Giang
--------------------------------------------------------------------------
Here, we model the SIR and SEIR models. This is a C++ implementation of the "adaptive tau-leaping"
algorithm described by Cao Y, Gillespie DT, Petzold LR. The Journal of Chemical Physics (2007).
This programme interchanges C++ and R.
If building library outside of R package (i.e. for debugging):
R CMD SHLIB adaptivetau.cpp
--------------------------------------------------------------------------
*/
//libraries of R
#include <iostream>
#include <vector>
#include <limits>
#include <sstream>
#include <stdexcept>
#include "stoSEIRNewInfec.h"
#include "index.h"
#include <R.h>
#include <Rdefines.h>
#include <Rinternals.h>
#include <R_ext/Rdynload.h>
#include <R_ext/Lapack.h>
#include <Rmath.h>
#include "Rwrappers.h"
using namespace std;
enum EStepType {
eExact = 0,
eExplicit,
eImplicit
};
const bool debug = false;
//use below rather than R's "error" directly (which will not free memory, etc.)
#ifdef throwError
#undef throwError
#endif
#define throwError(e) { ostringstream s; s << e; throw runtime_error(s.str()); }
// Call R function without responding to user interrupts (or other, I
// suppose). This lets use catch them and free memory in the heap.
// Unfortunately, R_interrupts_suspended is not directly part of the R
// API (although it is used by the BEGIN/END_SUSPEND_INTERRUPTS macros
// in R_ext/GraphicsDevice.h)
extern "C" { LibExtern Rboolean R_interrupts_suspended;}
SEXP evalWithoutInterrupts(SEXP expr) {
//R_interrupts_suspended = TRUE;
SEXP res = eval(expr, NULL);
// R_interrupts_suspended = FALSE;
return res;
}
/************************************************************/
// CODE of TRAN THI CAM GIANG that are added in the c++ codes of the package "adaptive tau"
extern "C" {
/****/
/*
Goal: calculating the propensity functions for all subpopulation.
Used for SIR model
*/
double* seirratefunc(double* x,int nbVilles,double** arr_probVISITER,double** arr_probVENIRk,double** arr_probINFECTER,
double** arr_nbCONTACT0,double** arr_nbCONTACT1,
double periDISE, double m_T,double *phi,double** arr_nbCONTACTFORCING,double mu,double sigma, double gamma){
// 4 variables (S, I, R, N) and 6 events
int nbVarSEIRN=6, nevent=8;
//Initializing
double *lamda = new double[nbVilles];
for(int i = 0; i< nbVilles ; i++) lamda[i]=0.0;
//Converting 1D vector to 2D vector **y
unsigned long **y;
y = new unsigned long *[nbVilles];
for (int i = 0; i<nbVilles; i++)
{
y[i] = new unsigned long [nbVarSEIRN];
y[i][iS] = (unsigned long)x[0*nbVilles+i];//iS
y[i][iE] = (unsigned long)x[1*nbVilles+i];//iE
y[i][iI] = (unsigned long)x[2*nbVilles+i];//iI
y[i][iR] = (unsigned long)x[3*nbVilles+i];//iR
y[i][iN] = y[i][iS]+y[i][iE]+y[i][iI]+y[i][iR];//iN
}
// recalculating the matrix "COME from the city k
calculerProbVENIRk(nbVilles,y,arr_probVISITER,arr_probVENIRk);
//recalculing the nbCONATCT forcing
/*
//calculateNbCONTACTForcing(nbVilles,arr_nbCONTACT0,arr_nbCONTACT1,periDISE,m_T,phi,arr_nbCONTACTFORCING);
cout<<"DDDD "<<m_T<<" "<<arr_nbCONTACTFORCING[0][0]<<endl;
//Calculating Value of \lamda at time t
for (int i = 0; i<nbVilles; i++){
for(int j=0;j<nbVarSEIRN;j++)
cout<<"yyyy"<<i<<j<<" =="<<y[i][j]<<endl;
}
*/
calLamdaNewInfec(nbVilles,arr_probVISITER,y,arr_nbCONTACTFORCING,arr_probINFECTER,arr_probVENIRk,lamda);
//Calculating the values of all propensity function
double **f;
f = new double*[nbVilles];
for (int i = 0; i < nbVilles; i++)
{
f[i] = new double[nevent];
for(int j = 0; j< nevent ; j++) f[i][j] = 0.0;
}
for(int i=0; i< nbVilles;i++){
//S born
f[i][0] = mu*y[i][iN];
//S die
f[i][1] = mu*y[i][iS];
//E die
f[i][2] = mu*y[i][iE];
//I die
f[i][3] = mu*y[i][iI];
//R die
f[i][4] = mu*y[i][iR];
//S-> E
f[i][5] = lamda[i]*y[i][iS];
//E-> I
f[i][6] = sigma*y[i][iS];
//I->R
f[i][7] = gamma*y[i][iI];
}
// vector of result
vector<double> vecRes;
for(int j = 0; j< nevent ; j++)
{
for (int i = 0; i < nbVilles; i++)
vecRes.push_back(f[i][j]);
}
int nbvecRes=vecRes.size();
double *resRates = new double[nbvecRes];
for(int i=0; i<vecRes.size();i++){
resRates[i] = vecRes[i];
}
// Freeing the memory of all dynnamic pointers
delete []lamda;
for (int i = 0; i<nbVilles; i++)
{
delete []y[i];
delete []f[i];
}
delete []y; delete[]f;
return(resRates);
}
/****/
/*
Goal: calculating the propensity functions for all subpopulation.
Used for SIR model
*/
double* sirratefunc(double* x,int nbVilles,double** arr_probVISITER,double** arr_probVENIRk,double** arr_probINFECTER,
double** arr_nbCONTACT0,double** arr_nbCONTACT1,
double periDISE, double m_T,double *phi,double** arr_nbCONTACTFORCING, double mu,double gamma){
// 4 variables (S, I, R, N) and 6 events
int nbVarSIRN=5, nevent=6;
//Initializing
double *lamda = new double[nbVilles];
//Converting 1D vector to 2D vector **y
unsigned long **y;
y = new unsigned long *[nbVilles];
for (int i = 0; i<nbVilles; i++)
{
y[i] = new unsigned long [nbVarSIRN];
y[i][iS] = (unsigned long)x[0*nbVilles+i];//iS
y[i][iI] = (unsigned long)x[1*nbVilles+i];//iI
y[i][iR] = (unsigned long)x[2*nbVilles+i];//iR
y[i][iN] = y[i][iS]+y[i][iI]+y[i][iR];//iN
}
// recalculating the matrix "COME from the city k
calculerProbVENIRk(nbVilles,y,arr_probVISITER,arr_probVENIRk);
//recalculing the nbCONATCT forcing
//calculateNbCONTACTForcing(nbVilles,arr_nbCONTACT0,arr_nbCONTACT1,periDISE,m_T,phi,arr_nbCONTACTFORCING);
//Calculating Value of \lamda at time t
calLamdaNewInfec(nbVilles,arr_probVISITER,y,arr_nbCONTACTFORCING,arr_probINFECTER,arr_probVENIRk,lamda);
//Calculating the values of all propensity functions
double **f;
f = new double*[nbVilles];
for (int i = 0; i < nbVilles; i++)
{
f[i] = new double[nevent];
for(int j = 0; j< nevent ; j++) f[i][j] = 0.0;
}
for(int i=0; i< nbVilles;i++){
//S born
f[i][0] = mu*y[i][iN];
//S die
f[i][1] = mu*y[i][iS];
//I die
f[i][2] = mu*y[i][iI];
//R die
f[i][3] = mu*y[i][iR];
//S-> I
f[i][4] = lamda[i]*y[i][iS];
//I->R
f[i][5] = gamma*y[i][iI];
}
// vector of result
vector<double> vecRes;
for(int j = 0; j< nevent ; j++)
{
for (int i = 0; i < nbVilles; i++)
vecRes.push_back(f[i][j]);
}
int nbvecRes=vecRes.size();
double *resRates = new double[nbvecRes];
for(int i=0; i<vecRes.size();i++){
resRates[i] = vecRes[i];
}
// Freeing the memory of all dynnamic pointers
delete []lamda;
for (int i = 0; i<nbVilles; i++)
{
delete []y[i];
delete []f[i];
}
delete []y; delete[]f;
return(resRates);
}
/****/
}
/************** code TRAN Thi Cam Giang*****************/
///////////////////////////////////////////////////
class CStochasticEqns {
public:
CStochasticEqns(SEXP initVal, int *nu, unsigned int numTrans,
//
SEXP rateFunc, SEXP rateJacobianFunc,
// for model SEIR
int nbVilles,double sigma,double gamma,double mu,
// for metapopulation
double** arr_probVISITER,double** arr_nbCONTACT0,double** arr_nbCONTACT1, double** arr_probINFECTER, double** arr_probVENIRk,
double *phiPHASE,double periDISE,
//
double* changeBound, SEXP maxTauFunc, SEXP detTrans) {
// copy initial values into new vector (keeping in SEXP vector
// allows easy calling of R function to calculate rates)
m_NumStates = length(initVal);
SEXP x; double *x_copy;
PROTECT(x = NEW_NUMERIC(m_NumStates));
x_copy = NUMERIC_POINTER(x);
double *rinitVal = REAL(initVal);
double* cinitVal; create1D(m_NumStates,0.0,cinitVal);
for(int i=0; i<m_NumStates; i++) {cinitVal[i] = rinitVal[i];x_copy[i]=cinitVal[i];}
//copyVector(x, initVal);
//copyVector(x, coerceVector(initVal,REALSXP));
if (isNull(getAttrib(initVal, R_NamesSymbol))) {
m_VarNames = NULL;
} else {
SEXP initNames = getAttrib(initVal, R_NamesSymbol);
int m_NumNames=length(initNames);
PROTECT(m_VarNames = allocVector(STRSXP,m_NumNames));
for(int i=0; i<m_NumNames; i++) {
char* cnames=(char *) CHAR(STRING_ELT(initNames,i));
SET_STRING_ELT(m_VarNames, i,mkChar(cnames));
}
//copyVector(m_VarNames, initNames);
setAttrib(x, R_NamesSymbol,m_VarNames);
}
m_X = REAL(x);
// copy full-size Nu matrix into sparse matrix
m_Nu.resize(numTrans);
for (unsigned int i = 0; i < m_NumStates; ++i) {
for (unsigned int j = 0; j < numTrans; ++j) {
if (nu[j*m_NumStates + i] != 0) {
m_Nu[j].push_back(SChange(i, nu[j*m_NumStates + i]));
}
}
}
m_TransCats.resize(numTrans, eNoncritical);
// potentially flag some transitions as "deterministic"
if (detTrans && !isNull(detTrans)) {
x_SetDeterministic(LOGICAL(detTrans), length(detTrans));
}
// needed for ITL
x_IdentifyBalancedPairs();
x_IdentifyRealValuedVariables();
// prepare R function for evaluation by setting up arguments
// (current X values, parameters, current time)
SEXP s_time;
PROTECT(s_time = allocVector(REALSXP, 1));
m_T = REAL(s_time);
// TTCGIang: for SEIR and SIR models
GnbVilles=nbVilles; // number of subpopulations
//Model
Gsigma=sigma; Ggamma=gamma;Gmu=mu; GperiDISE=periDISE;
// for simulation
// for metapopulation
//1D
GphiPHASE=new double[GnbVilles];
for (int i = 0; i < GnbVilles; i++) GphiPHASE[i]=phiPHASE[i];
//2D
//Garr_nbCONTACTFORCING
Garr_probVISITER = new double*[GnbVilles];
Garr_nbCONTACT0 = new double*[GnbVilles];
Garr_nbCONTACT1 = new double*[GnbVilles];
Garr_probINFECTER = new double*[GnbVilles];
Garr_probVENIRk = new double*[GnbVilles];
Garr_nbCONTACTFORCING=new double*[GnbVilles];
for (int i = 0; i < GnbVilles; i++)
{
Garr_probVISITER[i] = new double[GnbVilles];
Garr_nbCONTACT0[i] = new double[GnbVilles];
Garr_nbCONTACT1[i] = new double[GnbVilles];
Garr_probINFECTER[i] = new double[GnbVilles];
Garr_probVENIRk[i] = new double[GnbVilles];
Garr_nbCONTACTFORCING[i]=new double[GnbVilles];
for(int j = 0; j< GnbVilles ; j++){
Garr_probVISITER[i][j] = arr_probVISITER[i][j];
Garr_nbCONTACT0[i][j] = arr_nbCONTACT0[i][j];
Garr_nbCONTACT1[i][j] = arr_nbCONTACT1[i][j];
Garr_probINFECTER[i][j] = arr_probINFECTER[i][j];
Garr_probVENIRk[i][j] = arr_probVENIRk[i][j];
Garr_nbCONTACTFORCING[i][j]=0.0;
}
}
//
calculateNbCONTACTForcing(GnbVilles,Garr_nbCONTACT0,Garr_nbCONTACT1,GperiDISE,0,GphiPHASE,Garr_nbCONTACTFORCING);
//
PROTECT(m_RateFunc);// = lang4(rateFunc, x, params, s_time));
if (!rateJacobianFunc || isNull(rateJacobianFunc)) {
m_RateJacobianFunc = NULL;
}/*
else {
PROTECT(m_RateJacobianFunc = lang4(rateJacobianFunc, x,params, s_time));
}*/
//Initializing the values for the flags of the variables SEIR
flagSEIR = TRUE;
if(Gsigma==INFINITY) flagSEIR=FALSE;
//
m_Rates = NULL;
//default parameters to adaptive tau leaping algorithm
m_Epsilon = 0.01;
m_Ncritical = 10;
m_Nstiff = 100;
m_ExactThreshold = 10;
m_Delta = 0.01;
m_NumExactSteps[eExact] = 100;
m_NumExactSteps[eExplicit] = 100;
m_NumExactSteps[eImplicit] = 10;
m_ITLConvergenceTol = 0.01;
m_MaxTau = numeric_limits<double>::infinity();
m_MaxSteps = 0; // special case 0 == no limit
//useful additional parameters
m_ExtraChecks = true;
m_RateChangeBound = changeBound;
if (!maxTauFunc || isNull(maxTauFunc)) {
m_MaxTauFunc = NULL;
}/*
else {
PROTECT(m_MaxTauFunc = lang4(maxTauFunc, x, params,s_time));
}*/
//check initial conditions to make sure legit
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_X[i] < 0) {
throwError("initial value for variable " << i+1 <<
" must be positive (currently " << m_X[i] << ")");
}
if (!m_RealValuedVariables[i] && (m_X[i] - trunc(m_X[i]) > 1e5)) {
throwError("initial value for variable " << i+1 <<
" must be an integer (currently " << m_X[i] << ")");
}
}
*m_T = 0;
m_PrevStepType = eExact;
GetRNGstate();
//Free pointers
//delete []x_copy;
//delete []cinitVal;
}
/********************************/
~CStochasticEqns(void) {
int cnt = 3;
if (m_RateJacobianFunc != NULL) {
++cnt;
}
if (m_Rates != NULL) {
++cnt;
}
if (m_MaxTauFunc != NULL) {
++cnt;
}
if (m_VarNames != NULL) {
++cnt;
}
UNPROTECT(cnt);
//delete []m_Rates;
//1D
delete []GphiPHASE;
//2D
for (int i = 0; i<GnbVilles; i++){
delete [] Garr_probVISITER[i];
delete [] Garr_nbCONTACT0[i];
delete [] Garr_nbCONTACT1[i];
delete [] Garr_probINFECTER[i];
delete [] Garr_probVENIRk[i];
delete [] Garr_nbCONTACTFORCING[i];
}
delete [] Garr_probVISITER; delete [] Garr_nbCONTACT0;
delete [] Garr_nbCONTACT1; delete [] Garr_probINFECTER;
delete [] Garr_probVENIRk; delete [] Garr_nbCONTACTFORCING;
}
void SetTLParams(SEXP list) {
SEXP names = getAttrib(list, R_NamesSymbol);
for (int i = 0; i < length(names); ++i) {
if (strcmp("epsilon", CHAR(STRING_PTR(names)[i])) == 0) {
if (!isReal(VECTOR_ELT(list, i)) ||
length(VECTOR_ELT(list, i)) != 1) {
throwError("invalid value for parameter '" <<
CHAR(STRING_PTR(names)[i]) << "'");
}
m_Epsilon = REAL(VECTOR_ELT(list, i))[0];
} else if (strcmp("delta", CHAR(STRING_PTR(names)[i])) == 0) {
if (!isReal(VECTOR_ELT(list, i)) ||
length(VECTOR_ELT(list, i)) != 1) {
throwError("invalid value for parameter '" <<
CHAR(STRING_PTR(names)[i]) << "'");
}
m_Delta = REAL(VECTOR_ELT(list, i))[0];
} else if (strcmp("maxtau", CHAR(STRING_PTR(names)[i])) == 0) {
if (!isReal(VECTOR_ELT(list, i)) ||
length(VECTOR_ELT(list, i)) != 1) {
throwError("invalid value for parameter '" <<
CHAR(STRING_PTR(names)[i]) << "'");
}
m_MaxTau = REAL(VECTOR_ELT(list, i))[0];
} else if (strcmp("extraChecks",
CHAR(STRING_PTR(names)[i])) == 0) {
if (!isLogical(VECTOR_ELT(list, i)) ||
length(VECTOR_ELT(list, i)) != 1) {
throwError("invalid value for parameter '" <<
CHAR(STRING_PTR(names)[i]) << "'");
}
m_ExtraChecks = LOGICAL(VECTOR_ELT(list, i))[0];
} else {
warning("ignoring unknown parameter '%s'",
CHAR(STRING_PTR(names)[i]));
}
}
}
// Functions below are a hack suggested by Simon Urbanek (although
// he "would not recommend for general use") to check if the user has
// asked to interrupt execution. The problem with calling
// R_CheckUserInterrupt directly is it longjmps and we don't have
// a chance to free memory from the heap.
// http://tolstoy.newcastle.edu.au/R/e13/devel/11/04/1049.html
static void chkIntFn(void*) { R_CheckUserInterrupt(); }
bool checkUserInterrupt(void) {
return (R_ToplevelExec(chkIntFn, NULL) == FALSE);
}
void EvaluateATLUntil(double tF) {
unsigned int c = 0;
//add initial conditions to time series
m_TimeSeries.push_back(STimePoint(0, m_X, m_NumStates));
//main loop
while (*m_T < tF && (m_MaxSteps == 0 || c < m_MaxSteps)) {
x_SingleStepATL(tF);
if (++c % 10 == 0 && checkUserInterrupt()) {
throwError("simulation interrupted by user at time " << *m_T
<< " after " << c << " time steps.");
}
}
//save RNG state back to R (could also do in destructor, but
//no harm in extra calls to PutRNGstate and avoids potential
//problems with PROTECTing return value from GetTimeSeriesSEXP
PutRNGstate();
}
void EvaluateExactUntil(double tF) {
unsigned int c = 0;
//add initial conditions to time series
m_TimeSeries.push_back(STimePoint(0, m_X, m_NumStates));
//main loop
while (*m_T < tF && (m_MaxSteps == 0 || c < m_MaxSteps)) {
x_UpdateRates();
x_SingleStepExact(tF);
m_TimeSeries.push_back(STimePoint(*m_T, m_X, m_NumStates));
if (++c % 10 == 0 && checkUserInterrupt()) {
throwError("simulation interrupted by user at time " << *m_T
<< " after " << c << " time steps.");
}
}
//save RNG state back to R (could also do in destructor, but
//no harm in extra calls to PutRNGstate and avoids potential
//problems with PROTECTing return value from GetTimeSeriesSEXP
PutRNGstate();
}
SEXP GetTimeSeriesSEXP(void) const {
SEXP res;
PROTECT(res = allocMatrix(REALSXP, m_TimeSeries.size(), m_NumStates+1));
double *rvals = REAL(res);
for (unsigned int t = 0; t < m_TimeSeries.size(); ++t) {
rvals[t] = m_TimeSeries[t].m_T;
for (unsigned int i = 0; i < m_NumStates; ++i) {
rvals[(i+1) * m_TimeSeries.size() + t] = m_TimeSeries[t].m_X[i];
}
}
SEXP dimnames, colnames;
PROTECT(dimnames = allocVector(VECSXP, 2));
PROTECT(colnames = allocVector(VECSXP, m_NumStates+1));
SET_VECTOR_ELT(dimnames, 1, colnames);
SET_VECTOR_ELT(colnames, 0, mkChar("time"));
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_VarNames && (unsigned int)length(m_VarNames) > i) {
SET_VECTOR_ELT(colnames, i+1,
STRING_PTR(m_VarNames)[i]);
} else {
char name[10];
snprintf(name, 10, "x%i", i+1);
SET_VECTOR_ELT(colnames, i+1, mkChar(name));
}
}
setAttrib(res, R_DimNamesSymbol, dimnames);
UNPROTECT(3);
return res;
}
protected:
enum ETransCat {
eCritical,
eNoncritical,
eDeterministic
};
typedef vector<ETransCat> TTransCats;
typedef vector<pair<unsigned int, unsigned int> > TBalancedPairs;
typedef vector<bool> TBools;
typedef double* TStates;
typedef double* TRates;
struct SChange {
SChange(short int s, short int m) : m_State(s), m_Mag(m) {}
short int m_State;
short int m_Mag;
};
typedef vector< vector<SChange> > TTransitions;
struct STimePoint {
STimePoint(double t, double *x, int n) {
m_T = t;
m_X = new double[n];
memcpy(m_X, x, n*sizeof(*x));
}
double m_T;
double *m_X;
};
class CTimeSeries : public vector<STimePoint> {
public:
~CTimeSeries(void) {
for (iterator i = begin(); i != end(); ++i) {
delete[] i->m_X; i->m_X = NULL;
}
}
};
protected:
void x_IdentifyBalancedPairs(void);
void x_IdentifyRealValuedVariables(void);
void x_SetDeterministic(int *det, unsigned int n);
void x_AdvanceDeterministic(double deltaT, bool clamp = false);
void x_SingleStepExact(double tf);
bool x_SingleStepETL(double tau);
bool x_SingleStepITL(double tau);
void x_SingleStepATL(double tf);
void x_UpdateRates(void) {
if (m_ExtraChecks) {
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_X[i] < 0) {
cout<<"i="<<i<<endl;
cout<<"m_X[i]==="<<m_X[i]<<endl;
throwError("negative variable: " << i+1 << " is " <<
m_X[i] << " (check rate function "
"and/or transition matrix)");
} else if (isnan(m_X[i])) {
throwError("NaN variable: " << i+1 << " is " <<
m_X[i] << " (check rate function "
"and/or transition matrix)");
}
}
}
//not sure if this protect/unprotect block is necessary, but
//seems better to err on the safe side
if (m_Rates != NULL) {
UNPROTECT(1);
}
SEXP res;// = evalWithoutInterrupts(m_RateFunc);
PROTECT(res);
//TTCGiang for the SEIR and SIR models
// Here, we call the function 'seirratefunc' that calculates the propensity functions
if(flagSEIR){//SEIR model
/*
FILE *pFile; char line[255] = "";
pFile = fopen("forcing.txt","a+");
for(int i=0;i<GnbVilles;i++){
for(int j=0;j<GnbVilles;j++){
cout<<" "<<*m_T<<" "<<Garr_nbCONTACTFORCING[i][j]<<endl;
sprintf(line, "%.3f\t\t%.3f \n",*m_T ,Garr_nbCONTACTFORCING[i][j]);
}
fputs (line,pFile);
fclose (pFile);
}*/
calculateNbCONTACTForcing(GnbVilles,Garr_nbCONTACT0,Garr_nbCONTACT1,GperiDISE,*m_T,GphiPHASE,Garr_nbCONTACTFORCING);
m_Rates = seirratefunc(m_X,GnbVilles,Garr_probVISITER,Garr_probVENIRk,Garr_probINFECTER,
Garr_nbCONTACT0,Garr_nbCONTACT1,GperiDISE,*m_T,GphiPHASE,Garr_nbCONTACTFORCING,Gmu,Gsigma,Ggamma);
}
else{//SIR model
calculateNbCONTACTForcing(GnbVilles,Garr_nbCONTACT0,Garr_nbCONTACT1,GperiDISE,*m_T,GphiPHASE,Garr_nbCONTACTFORCING);
m_Rates = sirratefunc(m_X,GnbVilles,Garr_probVISITER,Garr_probVENIRk,Garr_probINFECTER,
Garr_nbCONTACT0,Garr_nbCONTACT1,GperiDISE,*m_T,GphiPHASE,Garr_nbCONTACTFORCING,Gmu,Ggamma);
// for(int i=0; i<6; i++) cout <<"ZZZZ = "<<m_Rates[i]<<endl;
//cout<<"m_T=="<<*m_T<<endl;
}
if (m_ExtraChecks) {
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (isnan(m_Rates[j])) {
cout<<"j ="<<j<<endl;
cout<<"m_Rates[j]==="<<m_Rates[j]<<endl;
throwError("invalid rate function -- rate for transition "
<< j+1 << "is not a number (NA/NaN)! (check "
"for divison by zero or similar)");
}
if (m_Rates[j] < 0) {
throwError("invalid rate function -- rate for transition "
<< j+1 << "is negative!");
}
}
}
}
/********************************/
double* x_CalcJacobian(void) {
SEXP res = evalWithoutInterrupts(m_RateJacobianFunc);
if (!isMatrix(res)) {
throwError("invalid Jacobian function -- should return a " <<
m_NumStates << " by " << m_Nu.size() << " matrix");
}
unsigned int nrow = INTEGER(getAttrib(res, R_DimSymbol))[0];
unsigned int ncol = INTEGER(getAttrib(res, R_DimSymbol))[1];
if (nrow != m_NumStates || ncol != m_Nu.size()) {
throwError ("invalid Jacobian function -- returned a " << nrow
<< " by " << ncol << " matrix instead of the expected "
<< m_NumStates << " by " << m_Nu.size() <<
" (variables by transitions)");
}
return REAL(res);
}
/********************************/
double x_CalcUserMaxTau(void) {
if (!m_MaxTauFunc) { throwError("logic error at line " << __LINE__) }
SEXP res = evalWithoutInterrupts(m_MaxTauFunc);
if (length(res) != 1 || !isReal(res)) {
throwError("invalid return value from maxTau function (should be "
"a single real number)");
}
return REAL(res)[0];
}
/********************************/
unsigned int x_PickCritical(double prCrit) const;
double x_TauEx(void) const {
double tau = numeric_limits<double>::infinity();
vector <double> mu(m_NumStates, 0);
vector <double> sigma(m_NumStates, 0);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] != eCritical) {
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
const SChange &c = m_Nu[j][i];
mu[c.m_State] += c.m_Mag * m_Rates[j];
sigma[c.m_State] += c.m_Mag * c.m_Mag * m_Rates[j];
}
}
}
//cerr << "-=| mu:";
for (unsigned int i = 0; i < m_NumStates; ++i) {
//cerr << "\t" << mu[i];
double val = max(m_Epsilon * m_X[i] / m_RateChangeBound[i],
1.)/fabs(mu[i]);
//cerr << "/" << val;
if (val < tau) {
tau = val;
if (tau < 0) {
throwError("tried to select tau < 0; most likely means "
"your rate function generated a negative rate");
}
}
val = pow(max(m_Epsilon * m_X[i] / m_RateChangeBound[i],
1.),2) / sigma[i];
if (val < tau) {
tau = val;
if (tau < 0) {
throwError("tried to select tau < 0; most likely means "
"your rate function generated a negative rate");
}
}
}
//cerr << endl;
return tau;
}
/********************************/
double x_TauIm(void) const {
if (!m_RateJacobianFunc) {
return 0;
}
vector<bool> equil(m_TransCats.size(), false);
for (TBalancedPairs::const_iterator i = m_BalancedPairs.begin();
i != m_BalancedPairs.end(); ++i) {
if (fabs(m_Rates[i->first] - m_Rates[i->second]) <=
m_Delta * min(m_Rates[i->first], m_Rates[i->second])) {
equil[i->first] = true;
equil[i->second] = true;
}
}
vector<double> mu(m_NumStates, 0);
vector<double> sigma(m_NumStates, 0);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] != eCritical && !equil[j]) {
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
const SChange &c = m_Nu[j][i];
mu[c.m_State] += c.m_Mag * m_Rates[j];
sigma[c.m_State] += c.m_Mag * c.m_Mag * m_Rates[j];
}
}
}
double tau = numeric_limits<double>::infinity();
for (unsigned int i = 0; i < m_NumStates; ++i) {
double val = max(m_Epsilon * m_X[i] / m_RateChangeBound[i],
1.)/fabs(mu[i]);
if (val < tau) {
tau = val;
}
val = pow(max(m_Epsilon * m_X[i] / m_RateChangeBound[i],
1.),2) / sigma[i];
if (val < tau) {
tau = val;
}
}
return tau;
}
/********************************/
private:
bool m_ExtraChecks; //turns on extra checks on rates returned by
//user-supplied rate function. Slower, but if
//the rate function does have a bug, this will
//give a more meaningful error message.
unsigned int m_Ncritical;
double m_Nstiff;
double m_Epsilon;
double m_ExactThreshold;
double m_Delta;
unsigned int m_NumExactSteps[3];
double m_ITLConvergenceTol;
double m_MaxTau;
unsigned int m_MaxSteps;
TRates m_Rates; // *current* rates (must be updated if m_X changes!)
bool flagSEIR; // current flag for the SIER model
double *m_T; // *current* time
int GnbVilles; // number of subpopulations
double GT;
//Model
double Gsigma, Ggamma, Gmu;
double GperiDISE;
double ** Garr_nbCONTACTFORCING;
// for simulation
// for metapopulation
double** Garr_probVISITER;
double** Garr_nbCONTACT0;
double** Garr_nbCONTACT1;
double** Garr_probINFECTER;
double** Garr_probVENIRk;
double* GphiPHASE;
TBalancedPairs m_BalancedPairs;
TBools m_RealValuedVariables;
EStepType m_PrevStepType;
TStates m_X; //current state
unsigned int m_NumStates; //total number of states
SEXP m_VarNames; //variable names (if any)
TTransitions m_Nu; //state changes caused by transition
TTransCats m_TransCats; //inc. whether transition is deterministic
SEXP m_RateFunc; //R function to calculate rates as f(m_X)
SEXP m_RateJacobianFunc; //R function to calculate Jacobian of rates as f(m_X) [optional!]
double *m_RateChangeBound; //see Cao (2006) for details
SEXP m_MaxTauFunc; //R function to calculate maximum leap given curr. state
CTimeSeries m_TimeSeries;
};
/*---------------------------------------------------------------------------*/
// PRE : m_Nu initialized
// POST: all balanced pairs of transitions identified & saved
void CStochasticEqns::x_IdentifyBalancedPairs(void) {
for (unsigned int j1 = 0; j1 < m_Nu.size(); ++j1) {
for (unsigned int j2 = j1 + 1; j2 < m_Nu.size(); ++j2) {
if (m_Nu[j1].size() != m_Nu[j2].size()) {
continue;
}
unsigned int i;
for (i = 0; i < m_Nu[j1].size() &&
m_Nu[j1][i].m_State == m_Nu[j2][i].m_State &&
m_Nu[j1][i].m_Mag == -m_Nu[j2][i].m_Mag; ++i);
if (i == m_Nu[j1].size()) {
m_BalancedPairs.push_back(TBalancedPairs::value_type(j1, j2));
if (debug) {
cerr << "balanced pair " << j1 << " and " << j2 << endl;
}
}
}
}
}
/*---------------------------------------------------------------------------*/
// PRE : m_Nu initialized, boolean vector flagging transitions as
// deterministic or not (could be just FALSE and n=1)
// POST: deterministic flag set where appropriate
void CStochasticEqns::x_SetDeterministic(int *det, unsigned int n) {
if (n != m_Nu.size() && n > 1) {
throwError("mismatch between length of logical vector specifying "
"deterministic transitions and total number of transitions");
}
bool atLeastOneStochastic = false;
for (unsigned int i = 0; i < n; ++i) {
if (det[i]) {
m_TransCats[i] = eDeterministic;
} else {
atLeastOneStochastic = true;
}
}
if (!atLeastOneStochastic) {
throwError("At least one transition must be stochastic (all "
"transitions are currently flagged as deterministic).");
}
x_IdentifyRealValuedVariables();
}
/*---------------------------------------------------------------------------*/
// PRE : m_Nu initialized, deterministic transition set (if any)
// POST: all variables identified will take real values
// (i.e. either non-integer nu or modified by a deterministic transition)
void CStochasticEqns::x_IdentifyRealValuedVariables(void) {
m_RealValuedVariables.clear();
m_RealValuedVariables.resize(m_NumStates, false);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eDeterministic) {
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_RealValuedVariables[m_Nu[j][i].m_State] = true;
}
} else {
//code below not used since m_Nu matrix is forced to be integers
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
if (m_Nu[j][i].m_Mag - trunc(m_Nu[j][i].m_Mag) > 1e-5) {
m_RealValuedVariables[m_Nu[j][i].m_State] = true;
}
}
}
}
}
/*---------------------------------------------------------------------------*/
// PRE : list of critical transitions & their total rate
// POST: one picked according to probability
unsigned int CStochasticEqns::x_PickCritical(double critRate) const {
double r = runif(0,1);
double d = 0;
unsigned int j;
for (j = 0; j < m_Nu.size() && d < r; ++j) {
if (m_TransCats[j] == eCritical) {
d += m_Rates[j]/critRate;
}
}
if (!(d >= r)) { throwError("logic error at line " << __LINE__) }
return j-1;
}
/*---------------------------------------------------------------------------*/
// PRE : time period to step; whether to clamp variables at 0
// POST: all determinisitic transitions updated by the expected amount
// (i.e. Euler method); if clamping, then negative variables set to 0.
void CStochasticEqns::x_AdvanceDeterministic(double deltaT, bool clamp) {
if (clamp) {
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eDeterministic) {
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_X[m_Nu[j][i].m_State] += m_Nu[j][i].m_Mag * m_Rates[j] *
deltaT;
//clamp at zero if specified
if (m_X[m_Nu[j][i].m_State] < 0) {
m_X[m_Nu[j][i].m_State] = 0;
}
}
}
}
} else {
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eDeterministic) {
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_X[m_Nu[j][i].m_State] += m_Nu[j][i].m_Mag * m_Rates[j] *
deltaT;
}
}
}
}
}
/*---------------------------------------------------------------------------*/
// PRE : simulation end time; **transition rates already updated**
// POST: a *single* transition taken (no approximation necessary)
void CStochasticEqns::x_SingleStepExact(double tf) {
double stochRate = 0;
double detRate = 0;
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] != eDeterministic) {
stochRate += m_Rates[j];
} else {
detRate += m_Rates[j];
}
}
if (stochRate == 0) {
if (detRate == 0) {
*m_T = numeric_limits<double>::infinity();
} else {
double tau = min(1/detRate, tf-*m_T);
x_AdvanceDeterministic(tau, true);
*m_T += tau;
}
return;
}
double tau = rexp(1./stochRate);
if (tau > tf - *m_T) {
tau = tf - *m_T;
} else { // only take step if don't go off end
double r = runif(0,1);
double d = 0;
unsigned int j;
for (j = 0; j < m_Nu.size() && d < r; ++j) {
if (m_TransCats[j] != eDeterministic) {
d += m_Rates[j]/stochRate;
}
}
if (!(d >= r)) { throwError("logic error at line " << __LINE__) }
--j;
//take transition "j"
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_X[m_Nu[j][i].m_State] += m_Nu[j][i].m_Mag;
}
}
//clamp deterministic at 0, assuming that it is unreasonable to
//take a smaller step then exact.
x_AdvanceDeterministic(tau, true);
*m_T += tau;
}
/*---------------------------------------------------------------------------*/
// PRE : tau value to use for step, list of "critical" transitions
// POST: whether single IMPLICIT tau step was successfully taken (m_X
// updated if so)
// NOTE: See equation (7) in Cao et al. (2007)
bool CStochasticEqns::x_SingleStepITL(double tau) {
if (!m_RateJacobianFunc) { throwError("logic error at line " << __LINE__) }
double *origX = new double[m_NumStates];
double *origRates = new double[m_NumStates];
memcpy(origX, m_X, sizeof(double)*m_NumStates);
memcpy(origRates, m_Rates, sizeof(double)*m_NumStates);
if (debug) {
cerr << " origX: ";
for (unsigned int i =0; i < m_NumStates; ++i) {
cerr << origX[i] << "\t";
}
cerr << endl;
}
// draw (stochastic) number of times each transition will occur
vector<int> numTransitions(m_Nu.size(), 0);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eNoncritical) {
if (m_Rates[j]*tau > 1e8) {
//for high rate, use normal to approx poisson.
//should basically never yield negative, but just to
//be sure, cap at 0
numTransitions[j] = max(0.,floor(rnorm(m_Rates[j]*tau, sqrt(m_Rates[j]*tau))));
} else {
numTransitions[j] = rpois(m_Rates[j]*tau);
//cerr << "nt[" << j << "] " << numTransitions[j] << endl;
}
}
}
// Calculate equation (7) terms not involving x[t+tau] and call this alpha:
// alpha = x + nu.(P - tau/2 R(x))
// Also initialize iterative search for x[t+tau] at expectation (reset m_X)
double* alpha = new double[m_NumStates];
memcpy(alpha, m_X, sizeof(double)*m_NumStates);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eNoncritical) {
for (unsigned int k = 0; k < m_Nu[j].size(); ++k) {
alpha[m_Nu[j][k].m_State] += m_Nu[j][k].m_Mag *
(numTransitions[j] - (tau/2)*m_Rates[j]);
//reset m_X to expectation as our initial guess
m_X[m_Nu[j][k].m_State] += m_Nu[j][k].m_Mag *
(tau/2)*m_Rates[j];
}
}
}
//expectations may send states negative; clamp!
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_X[i] < 0) {
m_X[i] = 0;
}
}
if (debug) {
cerr << " alpha:";
for (unsigned int i = 0; i < m_NumStates; ++i) {
cerr << " " << alpha[i];
}
cerr << endl;
cerr << "it " << 0 << " newX: ";
for (unsigned int i =0; i < m_NumStates; ++i) {
cerr << m_X[i] << "\t";
}
cerr << endl;
}
//a few variables needed by LAPACK
int N = m_NumStates;
int nrhs = 1;
int *ipiv = new int[m_NumStates];
int info;
double *matrixA = new double[m_NumStates*m_NumStates];
double *matrixB = new double[m_NumStates];
//Use Newton's method to solve implicit equation:
// Let Y = x[t+tau]
// F(Y) = Y - alpha - nu.((tau/2)*R(Y))
//Solve Jacobian(F(Y0)) Y1 = -F(Y0) for Y1 to iteratively approach solution
//This eqn expands to (I - nu.((tau/2)Jacobian(R(Y0)))) Y1 = -F(Y0) where
//the Jacobian of rates is supplied by the user. The term to the
//left of Y1 is called matrix A by LAPACK and the term on right is
//matrix B.
//
//Perhaps should adjust max # of iterations..
bool converged = false;
unsigned int c = 0;
while (++c <= 20 && !converged) {
// Check to make sure we haven't taken too big a step --
// i.e. no state variables should go negative
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_X[i] < 0) {
delete[] origRates;
delete[] alpha;
delete[] ipiv;
delete[] matrixA;
delete[] matrixB;
memcpy(m_X, origX, sizeof(double)*m_NumStates);
delete[] origX;
return false;
}
}
// define matrix A
double* rateJacobian = x_CalcJacobian();
memset(matrixA, 0, m_NumStates*m_NumStates*sizeof(double));
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eNoncritical) {
for (unsigned int k = 0; k < m_Nu[j].size(); ++k) {
for (unsigned int i = 0; i < m_NumStates; ++i) {
//R stores matrices column-wise
//LAPACK stores matrices row-wise
matrixA[i*m_NumStates + m_Nu[j][k].m_State] +=
m_Nu[j][k].m_Mag * rateJacobian[j*m_NumStates + i];
}
}
}
}
for (unsigned int i = 0; i < m_NumStates; ++i) {
for (unsigned int i2 = 0; i2 < m_NumStates; ++i2) {
matrixA[i*m_NumStates + i2] *= -tau/2;
}
matrixA[i*m_NumStates + i] += 1;
}
// define matrix B
// m_X is now our proposed x[t+tau]. Note that m_X has changed
// even in our first iteration (initialized to expected value).
x_UpdateRates();
for (unsigned int i = 0; i < m_NumStates; ++i) {
matrixB[i] = alpha[i] - m_X[i];
}
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eNoncritical) {
for (unsigned int k = 0; k < m_Nu[j].size(); ++k) {
matrixB[m_Nu[j][k].m_State] +=
m_Nu[j][k].m_Mag * (tau/2) * m_Rates[j];
}
}
}
if (debug) {
cerr << "A:" << endl;
for (unsigned int i = 0; i < m_NumStates; ++i) {
for (unsigned int i2 = 0; i2 < m_NumStates; ++i2) {
cerr << matrixA[i2*m_NumStates + i] << "\t";
}
cerr << endl;
}
cerr << "B:" << endl;
for (unsigned int i = 0; i < m_NumStates; ++i) {
cerr << matrixB[i] << "\t";
}
cerr << endl;
cerr << "a:" << endl;
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
cerr << m_Rates[j] << "\t";
}
cerr << endl;
}
//solve linear eqn
F77_NAME(dgesv)(&N, &nrhs, matrixA, &N, ipiv, matrixB, &N, &info);
if (info != 0) {
warning("warning: lapack ran into trouble solving implicit equation");
break;
}
//matrixB now contains solution (change in X)
double normDelta = 0, normX = 0;
for (unsigned int i = 0; i < m_NumStates; ++i) {
m_X[i] += matrixB[i];
normDelta += matrixB[i]*matrixB[i];
normX += m_X[i] * m_X[i];
}
//cerr << "\tNorms: " << normDelta << "\t" << normX << endl;
converged = (normDelta < normX * m_ITLConvergenceTol);
if (debug) {
/*
cerr << "Delta: ";
for (unsigned int i =0; i < m_NumStates; ++i) {
cerr << matrixB[i] << "\t";
}
cerr << endl;
*/
cerr << "it " << c << " newX: ";
for (unsigned int i =0; i < m_NumStates; ++i) {
cerr << m_X[i] << "\t";
}
cerr << endl;
/*
x_UpdateRates();
double t[m_NumStates];
memcpy(t, alpha, sizeof(double)*m_NumStates);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eNoncritical) {
for (unsigned int k = 0; k < m_Nu[j].size(); ++k) {
t[m_Nu[j][k].m_State] +=
m_Nu[j][k].m_Mag * (tau/2) * m_Rates[j];
}
}
}
cerr << " newX: ";
for (unsigned int i =0; i < m_NumStates; ++i) {
cerr << t[i] << "\t";
}
cerr << endl;
*/
}
} // end of iterating for Newton's method
if (!converged) {
warning("ITL solution did not converge!");
}
//restore original rates to execute deterministic transitions
memcpy(m_Rates, origRates, sizeof(double)*m_NumStates);
x_AdvanceDeterministic(tau);
delete[] origRates;
delete[] alpha;
delete[] ipiv;
delete[] matrixA;
delete[] matrixB;
bool tauTooBig = false;
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_X[i] < 0) {
tauTooBig = true;
break;
}
if (!m_RealValuedVariables[i]) {
m_X[i] = round(m_X[i]);
}
}
if (tauTooBig) {
memcpy(m_X, origX, sizeof(double)*m_NumStates);
delete[] origX;
return false;
}
delete[] origX;
*m_T += tau;
return true;
}
/*---------------------------------------------------------------------------*/
// PRE : tau value to use for step, list of "critical" transitions
// POST: whether single EXPLICIT tau step was successfully taken (m_X
// updated if so)
bool CStochasticEqns::x_SingleStepETL(double tau) {
double *origX = new double[m_NumStates];
memcpy(origX, m_X, sizeof(double)*m_NumStates);
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eNoncritical) {
double k;
if (m_Rates[j]*tau > 1e8) {
//for high rate, use normal to approx poisson.
//should basically never yield negative, but just to
//be sure, cap at 0
k = max(0.,floor(rnorm(m_Rates[j]*tau, sqrt(m_Rates[j]*tau))));
} else {
k = rpois(m_Rates[j]*tau);
}
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_X[m_Nu[j][i].m_State] += k * m_Nu[j][i].m_Mag;
}
} else if (m_TransCats[j] == eDeterministic) {
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_X[m_Nu[j][i].m_State] += m_Nu[j][i].m_Mag * m_Rates[j] *
tau;
}
}
}
bool tauTooBig = false;
for (unsigned int i = 0; i < m_NumStates; ++i) {
if (m_X[i] < 0) {
tauTooBig = true;
break;
}
}
if (tauTooBig) {
memcpy(m_X, origX, sizeof(double)*m_NumStates);
delete[] origX;
return false;
}
*m_T += tau;
delete[] origX;
return true;
}
/*---------------------------------------------------------------------------*/
// PRE : time at which to end simulation
// POST: single adaptive tau leaping step taken & time series updated.
// Implemented from Cao Y, Gillespie DT, Petzold LR. The Journal of Chemical
// Physics (2007).
void CStochasticEqns::x_SingleStepATL(double tf) {
x_UpdateRates();
EStepType stepType;
//identify "critical" transitions
double criticalRate = 0;
double noncritRate = 0;
{
for (unsigned int j = 0; j < m_Nu.size(); ++j) {
if (m_TransCats[j] == eDeterministic) {
noncritRate += m_Rates[j];
continue;
}
unsigned int minTimes = numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
if (m_Nu[j][i].m_Mag < 0 &&
m_X[m_Nu[j][i].m_State]/abs(m_Nu[j][i].m_Mag) < minTimes) {
minTimes = m_X[m_Nu[j][i].m_State]/abs(m_Nu[j][i].m_Mag);
}
}
if (minTimes < m_Ncritical) {
m_TransCats[j] = eCritical;
criticalRate += m_Rates[j];
} else {
m_TransCats[j] = eNoncritical;
noncritRate += m_Rates[j];
}
}
}
if (debug) {
cerr << "critical rate: " << criticalRate << "\t" << "noncrit rate: " << noncritRate << endl;
}
if (criticalRate + noncritRate == 0) {
*m_T = tf;//numeric_limits<double>::infinity();
m_TimeSeries.push_back(STimePoint(*m_T, m_X, m_NumStates));
return;
}
// calc explicit & implicit taus
double tau1, tau2;
double tauEx = x_TauEx();
double tauIm = x_TauIm();
if (debug) {
cerr << "tauEx: " << tauEx << " tauIm:" << tauIm << endl;
}
if (tauEx*m_Nstiff < tauIm) {
stepType = eImplicit;
tau1 = tauIm;
} else {
stepType = eExplicit;
tau1 = tauEx;
}
if (tau1 > tf - *m_T) { //cap at the final simulation time
tau1 = tf - *m_T;
}
if (tau1 > m_MaxTau) {
tau1 = m_MaxTauFunc ? min(tau1, x_CalcUserMaxTau()) : m_MaxTau;
if (debug) {
cerr << "maxtau: " << tau1 << " (" <<
(m_MaxTauFunc ? x_CalcUserMaxTau() : m_MaxTau) << ")" << endl;
}
}
bool tauTooBig;
do {
tauTooBig = false;
if (!(tau1 > 0)) { throwError("logic error at line " << __LINE__) }
if (tau1 < m_ExactThreshold / (criticalRate + noncritRate)) {
if (debug) {
cerr << "Taking exact steps.. (tau1 = " << tau1 << ")" << endl;
}
stepType = eExact;
for (unsigned int i = 0;
i < m_NumExactSteps[m_PrevStepType] && *m_T < tf; ++i) {
if (i > 0) {
x_UpdateRates();
}
x_SingleStepExact(tf);
if (*m_T == numeric_limits<double>::infinity()) {
//signal that rates = 0
*m_T = tf;
}
if (debug) {
cerr << *m_T << " -- ";
for (unsigned int i = 0; i < m_NumStates; ++i) {
cerr << m_X[i] << " ";
}
cerr << endl;
}
m_TimeSeries.push_back(STimePoint(*m_T, m_X, m_NumStates));
}
} else {
tau2 = (criticalRate == 0) ? numeric_limits<double>::infinity() :
rexp(1./criticalRate);
if (stepType == eExplicit ||
(tau1 > tau2 && stepType == eImplicit && tau2 <= tauEx)) {
if (debug) {
cerr << "going explicit w/ tau = " << min(tau1, tau2) << endl;
}
tauTooBig = !x_SingleStepETL(min(tau1, tau2));
} else {
if (debug) {
cerr << "going implicit w/ tau = " << tau1 << endl;
}
tauTooBig = !x_SingleStepITL(tau1);
}
if (!tauTooBig) {
if (tau1 > tau2) { //pick one critical transition
unsigned int j = x_PickCritical(criticalRate);
if (debug) {
cerr << "hittin' the critical (" << j << ")" << endl;
}
for (unsigned int i = 0; i < m_Nu[j].size(); ++i) {
m_X[m_Nu[j][i].m_State] += m_Nu[j][i].m_Mag;
if (m_X[m_Nu[j][i].m_State] < 0) {
throwError("variable " << m_Nu[j][i].m_State+1 <<
" went negative after executing "
"transition " << j+1 << ". Most likely "
"either your rate calculation or "
"transition matrix is flawed.");
}
}
}
m_TimeSeries.push_back(STimePoint(*m_T, m_X, m_NumStates));
}
if (debug) {
cerr << *m_T << " -- ";
for (unsigned int i = 0; i < m_NumStates; ++i) {
cerr << m_X[i] << " ";
}
cerr << endl;
}
}
if (tauTooBig) {
if (debug) {
cerr << "whoa.. knock that tau back down" << endl;
}
tau1 /= 2;
}
} while (tauTooBig);
m_PrevStepType = stepType;
}
/*---------------------------------------------------------------------------*/
// Exported C entrypoints for calling from R
extern "C" {
// Doing the event that occurs
// for the SEIR model
int* seirtransitions(int nbVilles){
//Initializing
//4 for number of states, 8 for number of events
int *transitions = new int[nbVilles*4*nbVilles*8];
for(int i=0; i<nbVilles*4*nbVilles*8;i++) transitions[i] =0;
for (unsigned int i = 0; i < nbVilles; ++i) {
//susceptible birth; S<- S+1
transitions[0*nbVilles*4*nbVilles + i*4*nbVilles+0*nbVilles+i] = 1;
//susceptible death : S <-S-1
transitions[1*nbVilles*4*nbVilles + i*4*nbVilles+0*nbVilles+i] = -1;
//exposed death : E <- E-1
transitions[2*nbVilles*4*nbVilles + i*4*nbVilles+1*nbVilles+i] = -1;
//infectious death : I<- I-1
transitions[3*nbVilles*4*nbVilles + i*4*nbVilles+2*nbVilles+i] = -1;
//recovered death : R<-R-1
transitions[4*nbVilles*4*nbVilles + i*4*nbVilles+3*nbVilles+i] = -1;
// infection : S <-S-1; E<- E+1
transitions[5*nbVilles*4*nbVilles + i*4*nbVilles+0*nbVilles+i] = -1;
transitions[5*nbVilles*4*nbVilles + i*4*nbVilles+1*nbVilles+i] = 1;
// becoming infectious: E<-E-1; I<-I+1
transitions[6*nbVilles*4*nbVilles + i*4*nbVilles+1*nbVilles+i] = -1;
transitions[6*nbVilles*4*nbVilles + i*4*nbVilles+2*nbVilles+i] = 1;
// recovery : I<- I-1; R <-R+1
transitions[7*nbVilles*4*nbVilles + i*4*nbVilles+2*nbVilles+i] = -1;
transitions[7*nbVilles*4*nbVilles + i*4*nbVilles+3*nbVilles+i] = 1;
}
// Printing the result on the screen to check the correction of the results
/*
for(int i=0; i<nbVilles*4*nbVilles*8;i++)
cout<<"i= "<<i<<" trans="<<transitions[i]<<" ";
cout<<endl;
*/
return(transitions);
}
//-------------------------------------------------------------//
// Transitions for the SEIR model
int* sirtransitions(int nbVilles){
//Initializing
// 3 for number of states, 6 for number of events
int *transitions = new int[nbVilles*3*nbVilles*6];
for(int i=0; i<nbVilles*3*nbVilles*6;i++) transitions[i] =0;
// event that occurs
for (unsigned int i = 0; i < nbVilles; ++i) {
//susceptible birth; S<- S+1
transitions[0*nbVilles*3*nbVilles + i*3*nbVilles+0*nbVilles+i] = 1;
//susceptible death : S <-S-1
transitions[1*nbVilles*3*nbVilles + i*3*nbVilles+0*nbVilles+i] = -1;
//infectious death : I<- I-1
transitions[2*nbVilles*3*nbVilles + i*3*nbVilles+1*nbVilles+i] = -1;
//recovered death : R<-R-1
transitions[3*nbVilles*3*nbVilles + i*3*nbVilles+2*nbVilles+i] = -1;
// infection : S <-S-1; I<- I+1
transitions[4*nbVilles*3*nbVilles + i*3*nbVilles+0*nbVilles+i] = -1;
transitions[4*nbVilles*3*nbVilles + i*3*nbVilles+1*nbVilles+i] = 1;
// recovery : I<- I-1; R <-R+1
transitions[5*nbVilles*3*nbVilles + i*3*nbVilles+1*nbVilles+i] = -1;
transitions[5*nbVilles*3*nbVilles + i*3*nbVilles+2*nbVilles+i] = 1;
}
// Printing the result on the screen to check the correction of the results
/*
for(int i=0; i<nbVilles*3*nbVilles*6;i++)
cout<<"i= "<<i<<" trans="<<transitions[i]<<" ";
cout<<endl;
*/
return(transitions);
}
//---------------------------------------------------------------//
/*
Doing stochastic simulation for the SEIR and SIR models
by using the "adaptive tau-leaping" algorithm described by Cao Y, Gillespie DT, Petzold LR. The Journal of Chemical Physics (2007)
and by integrating the R and the C++.
In order to the values of parameters and of variables from R.
Step 1: we get these values from R that are in the R type.
Step 2: we convert the values of the R type to these of the C++ type
*/
SEXP ssesAdaptiveTau(SEXP s_x0, // initial values of variables
SEXP s_f, SEXP s_fJacob,
// values of parameters
SEXP sigma, SEXP gamma,SEXP mu,
SEXP nbCONTACT0, SEXP nbCONTACT1, SEXP nbMulCONTACT,
SEXP phiPHASE, SEXP probVISITER, SEXP probINFECTER, SEXP nbVilles,
SEXP periDISE,SEXP tmax,// time of simulation
SEXP s_deterministic, SEXP s_changebound,
SEXP s_tlparams, SEXP s_fMaxtau) {
try{
if (!isVector(s_x0) || !isReal(s_x0)) {
error("invalid vector of initial values");
}
if (!isNull(s_fJacob) && !isFunction(s_fJacob)) {
error("invalid Jacobian function");
}
if (length(tmax) != 1) {
error("invalid final time");
}
if (!isVector(s_deterministic) || !isLogical(s_deterministic)) {
error("invalid deterministic parameter -- must be logical vector");
}
if (!isVector(s_changebound) || !isReal(s_changebound) || length(s_changebound) != length(s_x0)) {
error("invalid relratechange");
}
if (!isNull(s_tlparams) && !isVector(s_tlparams)) {
error("tl.params must be a list");
}
if (!isNull(s_fMaxtau) && !isFunction(s_fMaxtau)) {
error("invalid maxTau function");
}
//Getting the values of parameters and variables
//number of subpopulations
//Number of cities in the metapopulation
if(!isReal(nbVilles) || length(nbVilles)!=1)
error("invalid number of cities.");
int cnbVilles = INTEGER_VALUE(nbVilles);
//-gamma 0.2 //gamma
if (!isReal(gamma) || length(gamma)!=1) {
error("invalid parameter gamma");
}
double cgamma = NUMERIC_VALUE(gamma);
//-mu 0.000039 //mu
if (!isReal(mu) || length(mu) !=1) {
error("invalid parameter mu");
}
double cmu = NUMERIC_VALUE(mu);
//-nbCONTACT0 300
if (!isReal(nbCONTACT0) || length(nbCONTACT0) != 1) {
error("invalid value of nbCONTACT0,it should be a real number");
}
double cnbCONTACT0=NUMERIC_VALUE(nbCONTACT0);
//-nbCONTACT1 0.1
if (!isReal(nbCONTACT1) || length(nbCONTACT1) != 1) {
error("invalid value of nbCONTACT1,it should be a real number");
}
double cnbCONTACT1=NUMERIC_VALUE(nbCONTACT1);
//-nbMulCONTACT 1
if (!isReal(nbMulCONTACT) || length(nbMulCONTACT) != 1) {
error("invalid value of nbMulCONTACT,it should be a real number");
}
double cnbMulCONTACT=NUMERIC_VALUE(nbMulCONTACT);
//-phiPHASE is a vector of n elements
if (!isVector(phiPHASE) || !isReal(phiPHASE)) {
error("invalid vector of phase (phiPHASE)");
}
double *rphiPHASE = REAL(phiPHASE);
double* cphiPHASE; create1D(cnbVilles,0.0,cphiPHASE);
for(int i=0; i<cnbVilles; i++) cphiPHASE[i] = rphiPHASE[i];
//-probVISITER 0.01
if (!isReal(probVISITER) || length(probVISITER) != 1) {
error("invalid value of probVISITER,it should be a real number");
}
double cprobVISITER=NUMERIC_VALUE(probVISITER);
//-probINFECTER 0.01
if (!isReal(probINFECTER) || length(probINFECTER) != 1) {
error("invalid value of probINFECTER,it should be a real number");
}
double cprobINFECTER=NUMERIC_VALUE(probINFECTER);
//simulation time tmax
if (!isReal(tmax) || length(tmax) != 1) {
error("invalid value of simulation time,it should be a real number");
}
double ctmax=NUMERIC_VALUE(tmax);
// Disease period
if (!isReal(periDISE) || length(periDISE) != 1) {
error("invalid value of period, it should be a real number");
}
double cperiDISE=NUMERIC_VALUE(periDISE);
// for metapopulation
double ** arr_probVISITER = calculerProbVISITER(cnbVilles,cprobVISITER);
// xay dung ma tran INFECTER
double **arr_probINFECTER; create2D(cnbVilles,cnbVilles,cprobINFECTER,arr_probINFECTER);
double **arrNbCONTACT0 = calculerNbCONTACT(cnbVilles,cnbCONTACT0,1);
double **arrNbCONTACT1 = calculerNbCONTACT(cnbVilles,cnbCONTACT1,cnbMulCONTACT);
// xay dung ma tran VENIR de la ville k
// initialiser les valeurs des variables
//separate initial values of variables
unsigned int nbTotalVar= length(s_x0); //total number of states
double *rs_x0 = REAL(s_x0);
double* cs_x0; create1D(nbTotalVar,0.0,cs_x0);
for(int i=0; i<nbTotalVar; i++) { cs_x0[i] = rs_x0[i];}
int nvar= 6;
unsigned long **valSEIR0;
valSEIR0 = new unsigned long*[cnbVilles];
for (int i = 0; i < cnbVilles; i++)
{
valSEIR0[i] = new unsigned long[nvar];
valSEIR0[i][0]= 0;
valSEIR0[i][iS]= (unsigned long)cs_x0[0*cnbVilles+i];//iS
valSEIR0[i][iE]= (unsigned long)cs_x0[1*cnbVilles+i];//iE
valSEIR0[i][iI]= (unsigned long)cs_x0[2*cnbVilles+i];//iI
valSEIR0[i][iR]= (unsigned long)cs_x0[3*cnbVilles+i];//iR
valSEIR0[i][iN]= valSEIR0[i][iS]+ valSEIR0[i][iE]+ valSEIR0[i][iI]+valSEIR0[i][iR];
}
/*
cout<<"valSEIR0"<<endl;
for(int i=0; i<cnbVilles; i++){
for (int j=0; j<nvar; j++)
cout<<" " << valSEIR0[i][j];
cout<<endl;
}
cout<<"valSEIRAZZZZZZZ"<<endl;
*/
double **arr_probVENIRk; create2D(cnbVilles,cnbVilles,0, arr_probVENIRk);
calculerProbVENIRk(cnbVilles,valSEIR0,arr_probVISITER,arr_probVENIRk);
// vector of transitions (event occurs)
int* transitions;
unsigned int nbrate = 0;
// check here is SEIR model or SIR model
//-sigma 0.125 //sigma
if (!isReal(sigma) || length(sigma)!=1) {
error("invalid parameter sigma");
}
double csigma = NUMERIC_VALUE(sigma);
// select Model
bool flagSEIR=TRUE;
if(csigma==INFINITY) flagSEIR=FALSE;
// Doing simulation for SEIR/SIR models
if(flagSEIR){//SEIR model
transitions = seirtransitions(cnbVilles);
nbrate=cnbVilles*8; //number of events for all subpopulations
}
else{//SIR model
transitions = sirtransitions(cnbVilles);
nbrate=cnbVilles*6; //number of events for all subpopulations
}
// stochastic simulation
CStochasticEqns eqns(s_x0,transitions,nbrate,
s_f, s_fJacob,
//parameters
cnbVilles,csigma,cgamma,cmu,arr_probVISITER,arrNbCONTACT0,arrNbCONTACT1,
arr_probINFECTER,arr_probVENIRk,cphiPHASE,cperiDISE,
//
REAL(s_changebound),
s_fMaxtau, s_deterministic);
delete []transitions;
for (int i = 0; i < cnbVilles; i++){
delete []arr_probVISITER[i];
delete []arr_probINFECTER[i];
delete []arrNbCONTACT0[i];
delete []arrNbCONTACT1[i];
delete []valSEIR0[i];
delete []arr_probVENIRk[i];
}
delete []arr_probVISITER; delete[]arr_probINFECTER;delete []arrNbCONTACT0; delete[]arrNbCONTACT1;delete []valSEIR0;
delete []arr_probVENIRk;
delete []cphiPHASE; delete []cs_x0;
if (!isNull(s_tlparams)) {
eqns.SetTLParams(s_tlparams);
}
eqns.EvaluateATLUntil(REAL(tmax)[0]);
return eqns.GetTimeSeriesSEXP();
} catch (exception &e) {
error(e.what());
return R_NilValue;
}
}
}
//-----------------------------------------------------------------------//
|
[
"camgiang2010@gmail.com"
] |
camgiang2010@gmail.com
|
357613a25d74c3c9c9dd16183bf63c85142ad481
|
042aca5678fde215ab1272573fd4aceb3aa95fa1
|
/ILJA/STARDICT/SD_SRC/INSTALL/INDLG.H
|
327fb2492970849d2e93c72fb9c4c0cf7cac3659
|
[] |
no_license
|
bkmy43/stardict
|
738304d693e51c7c4f7d49ab66f923b22a9a7140
|
18583590d176d3b92efd331bde84293581c96175
|
refs/heads/master
| 2021-05-11T18:38:09.909266
| 2018-01-17T13:31:53
| 2018-01-17T13:31:53
| 117,832,577
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,222
|
h
|
/* ****************************************************************************
INDLG.H
v1.0
Содержит описания классов диалоговых окон для инсталлятора.
Классы:
TAskLangDialog.
**************************************************************************** */
#if !defined (_INDLG_H)
#define _INDLG_H
class TAskInfoDialog : public TBaseDialog {
public :
TAskInfoDialog(TWindow*, TResId, TExFont*, TResId bmp);
virtual void SetupWindow();
BOOL DiskLargeEnough();
void CmOk();
DECLARE_RESPONSE_TABLE(TAskInfoDialog);
};
class TAskLangDialog : public TBaseDialog {
public :
TAskLangDialog(TWindow*, TResId, TExFont*, TResId bmp);
virtual void SetupWindow();
void CmOk();
DECLARE_RESPONSE_TABLE(TAskLangDialog);
};
class TAskDriveLetterDialog : public TBaseDialog {
public :
TAskDriveLetterDialog(TWindow*, TResId, TExFont*, TResId bmp);
virtual void SetupWindow();
void CmOk();
DECLARE_RESPONSE_TABLE(TAskDriveLetterDialog);
};
#endif
|
[
"ilya.vladimirskiy@smartfrog.com"
] |
ilya.vladimirskiy@smartfrog.com
|
fec7c40784fc8940385ad770320fdceb20111b2e
|
9d57c253f8a503170a0e9ac5d2a48b646048fb71
|
/K_King_s_Task.cpp
|
68029b0e8ba2579b7dad55924aabd0106c734cae
|
[] |
no_license
|
tarundecipher/CompetitiveProgramming
|
4f2dfd3f77c2a1de0b56964650d5cad05e4258ab
|
466bdc6333ca2f14b3a8aef14063a1278523bb9c
|
refs/heads/master
| 2023-04-04T07:50:49.626690
| 2021-04-18T08:13:16
| 2021-04-18T08:13:16
| 359,052,986
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,027
|
cpp
|
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int check(int destination, int start, int n)
{
// cout << ind << endl;
queue<pair<int, int>> q;
q.push({start, 0});
bool visited[2 * n + 1];
memset(visited, false, sizeof(visited));
bool dist2[2 * n + 1];
// memset(dist2, 0, sizeof(dist2));
// dist2[ind] = 0;
int ans = -1;
while (!q.empty())
{
pair<int, int> node = q.front();
int ind2 = node.first;
int dist = node.second;
q.pop();
// cout << ind2 << " " << dist << endl;
visited[ind2] = true;
// dist2[ind2] = dist;
if (ind2 == destination)
{
ans = dist;
break;
}
if (ind2 >= n)
{
if (!visited[ind2 - n])
{
q.push({ind2 - n, dist + 1});
}
}
else
{
if (!visited[ind2 + n])
{
q.push({ind2 + n, dist + 1});
}
}
if (ind2 % 2 == 0)
{
if (!visited[ind2 + 1])
{
q.push({ind2 + 1, dist + 1});
}
}
else
{
if (!visited[ind2 - 1])
{
q.push({ind2 - 1, dist + 1});
}
}
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int a[2 * n];
int ind[2 * n];
for (int i = 0; i < 2 * n; i++)
{
cin >> a[i];
ind[a[i]] = i;
}
int distance[2 * n + 1];
for (int i = 1; i <= 2 * n; i++)
{
distance[i] = check(i - 1, ind[i], n);
}
set<int> st;
for (int i = 1; i <= 2 * n; i++)
{
st.insert(distance[i]);
}
if (st.size() > 1)
{
cout << -1 << endl;
}
else
{
cout << distance[1] << endl;
}
// cout << endl;
// cout << check(2, 0, n) << endl;
// cout << ans << endl;
}
|
[
"tarunyadav83333@gmail.com"
] |
tarunyadav83333@gmail.com
|
b62189209b0beab30a79974c1182dc8d34bcac6d
|
5722258ec3ce781cd5ec13e125d71064a67c41d4
|
/java/nio/file/WatchEvent_ModifierProxy.cpp
|
eea694761d44be49982943ca32c4d40c013375cd
|
[] |
no_license
|
ISTE-SQA/HamsterJNIPP
|
7312ef3e37c157b8656aa10f122cbdb510d53c2f
|
b29096d0baa9d93ec0aa21391b5a11b154928940
|
refs/heads/master
| 2022-03-19T11:27:03.765328
| 2019-10-24T15:06:26
| 2019-10-24T15:06:26
| 216,854,309
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,694
|
cpp
|
#include "net/sourceforge/jnipp/JNIEnvHelper.h"
#include "WatchEvent_ModifierProxy.h"
// includes for parameter and return type proxy classes
using namespace net::sourceforge::jnipp;
using namespace java::nio::file;
std::string WatchEvent_ModifierProxy::className = "java/nio/file/WatchEvent$Modifier";
jclass WatchEvent_ModifierProxy::objectClass = NULL;
jclass WatchEvent_ModifierProxy::_getObjectClass()
{
if ( objectClass == NULL )
objectClass = static_cast<jclass>( JNIEnvHelper::NewGlobalRef( JNIEnvHelper::FindClass( className.c_str() ) ) );
return objectClass;
}
WatchEvent_ModifierProxy::WatchEvent_ModifierProxy(void* unused)
{
}
jobject WatchEvent_ModifierProxy::_getPeerObject() const
{
return peerObject;
}
jclass WatchEvent_ModifierProxy::getObjectClass()
{
return _getObjectClass();
}
WatchEvent_ModifierProxy::operator jobject()
{
return _getPeerObject();
}
// constructors
WatchEvent_ModifierProxy::WatchEvent_ModifierProxy(jobject obj)
{
peerObject = JNIEnvHelper::NewGlobalRef( obj );
}
WatchEvent_ModifierProxy::~WatchEvent_ModifierProxy()
{
JNIEnvHelper::DeleteGlobalRef( peerObject );
}
WatchEvent_ModifierProxy& WatchEvent_ModifierProxy::operator=(const WatchEvent_ModifierProxy& rhs)
{
JNIEnvHelper::DeleteGlobalRef( peerObject );
peerObject = JNIEnvHelper::NewGlobalRef( rhs.peerObject );
return *this;
}
// methods
::net::sourceforge::jnipp::JStringHelper WatchEvent_ModifierProxy::name()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "name", "()Ljava/lang/String;" );
return ::net::sourceforge::jnipp::JStringHelper( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
|
[
"steffen.becker@informatik.uni-stuttgart.de"
] |
steffen.becker@informatik.uni-stuttgart.de
|
d0a9d6ac594b1e49686dcfb002f33d7d3c266b1c
|
66d59c42fc88270bed4ce6ab18e7b6b573b4cf1a
|
/264 ugly number II/main.cpp
|
b17408c24db71622eebe81e4de8bf486b8293cd3
|
[] |
no_license
|
bluebambu/Leetcode_cpp
|
0e749322c5081ee6b61191931c853ab0ce9094f9
|
7a21e391d7a6bde4c202e46047880c30195bb023
|
refs/heads/master
| 2022-05-28T13:11:06.991523
| 2020-05-03T00:36:13
| 2020-05-03T00:36:13
| 260,799,312
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,373
|
cpp
|
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <list>
#include <vector>
#include <algorithm> // std::for_each
#include <unordered_map>
#include <queue>
#include <stack>
using namespace std;
inline int exchg(int &a, int &b) {int c=a; a=b; b=c;}
inline int log2(int N){return log10(N)/log10(2);}
inline float min(float a, float b) {return a<b?a:b;}
class Solution
{
public:
int nthUglyNumber(int n) {
if(n==0) return 0;
vector<int> ugly(1, 1);
int p2=0, p3=0, p5=0;
while(ugly.size()<n){
int m2=ugly[p2]*2, m3=ugly[p3]*3, m5=ugly[p5]*5;
int minin=min(m2, min(m3, m5));
if(minin==m2) ++p2;
if(minin==m3) ++p3;
if(minin==m5) ++p5;
ugly.push_back(minin);
}
return ugly.back();
}
};
int main()
{
Solution a;
// TreeNode* tree = new TreeNode(6,new TreeNode(3, new TreeNode(1), new TreeNode(4)),new TreeNode(8, new TreeNode(7), new TreeNode(9)));
TreeNode* tree = new TreeNode(6,new TreeNode(3, new TreeNode(1),
new TreeNode(4)),
new TreeNode(8, new TreeNode(7),
new TreeNode(9)));
/* 6
3 8
1 4 7 9
*/
a.flatten(tree);
}
|
[
"electricitymouse@gmail.com"
] |
electricitymouse@gmail.com
|
9bb543a0e2b04f0a002bf8eb386df4512ed94425
|
0065cefdd3a4f163e92c6499c4f36feb584d99b7
|
/rogue/cheat/sdk/SDK/SlateCore_structs.h
|
69e2d64601384e4017517a377e6cdfebef158b32
|
[] |
no_license
|
YMY1666527646/Rogue_Company_hack
|
ecd8461fc6b25a0adca1a6ef09ee57e59181bc84
|
2a19c81c5bf25b6e245084c073ad7af895a696e4
|
refs/heads/main
| 2023-08-20T06:07:14.660871
| 2021-10-21T20:33:53
| 2021-10-21T20:33:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 64,208
|
h
|
#pragma once
// Name: roguecompany, Version: 425
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Enums
//---------------------------------------------------------------------------
// Enum SlateCore.EUINavigation
enum class SlateCore_EUINavigation : uint8_t
{
EUINavigation__Left = 0,
EUINavigation__Right = 1,
EUINavigation__Up = 2,
EUINavigation__Down = 3,
EUINavigation__Next = 4,
EUINavigation__Previous = 5,
EUINavigation__Num = 6,
EUINavigation__Invalid = 7,
EUINavigation__EUINavigation_MAX = 8,
};
// Enum SlateCore.ECheckBoxState
enum class SlateCore_ECheckBoxState : uint8_t
{
ECheckBoxState__Unchecked = 0,
ECheckBoxState__Checked = 1,
ECheckBoxState__Undetermined = 2,
ECheckBoxState__ECheckBoxState_MAX = 3,
};
// Enum SlateCore.EWidgetClipping
enum class SlateCore_EWidgetClipping : uint8_t
{
EWidgetClipping__Inherit = 0,
EWidgetClipping__ClipToBounds = 1,
EWidgetClipping__ClipToBoundsWithoutIntersecting = 2,
EWidgetClipping__ClipToBoundsAlways = 3,
EWidgetClipping__OnDemand = 4,
EWidgetClipping__EWidgetClipping_MAX = 5,
};
// Enum SlateCore.ESlateBrushImageType
enum class SlateCore_ESlateBrushImageType : uint8_t
{
ESlateBrushImageType__NoImage = 0,
ESlateBrushImageType__FullColor = 1,
ESlateBrushImageType__Linear = 2,
ESlateBrushImageType__ESlateBrushImageType_MAX = 3,
};
// Enum SlateCore.ESlateBrushMirrorType
enum class SlateCore_ESlateBrushMirrorType : uint8_t
{
ESlateBrushMirrorType__NoMirror = 0,
ESlateBrushMirrorType__Horizontal = 1,
ESlateBrushMirrorType__Vertical = 2,
ESlateBrushMirrorType__Both = 3,
ESlateBrushMirrorType__ESlateBrushMirrorType_MAX = 4,
};
// Enum SlateCore.ESlateBrushTileType
enum class SlateCore_ESlateBrushTileType : uint8_t
{
ESlateBrushTileType__NoTile = 0,
ESlateBrushTileType__Horizontal = 1,
ESlateBrushTileType__Vertical = 2,
ESlateBrushTileType__Both = 3,
ESlateBrushTileType__ESlateBrushTileType_MAX = 4,
};
// Enum SlateCore.ESlateBrushDrawType
enum class SlateCore_ESlateBrushDrawType : uint8_t
{
ESlateBrushDrawType__NoDrawType = 0,
ESlateBrushDrawType__Box = 1,
ESlateBrushDrawType__Border = 2,
ESlateBrushDrawType__Image = 3,
ESlateBrushDrawType__ESlateBrushDrawType_MAX = 4,
};
// Enum SlateCore.ESlateColorStylingMode
enum class SlateCore_ESlateColorStylingMode : uint8_t
{
ESlateColorStylingMode__UseColor_Specified = 0,
ESlateColorStylingMode__UseColor_Specified_Link = 1,
ESlateColorStylingMode__UseColor_Foreground = 2,
ESlateColorStylingMode__UseColor_Foreground_Subdued = 3,
ESlateColorStylingMode__UseColor_MAX = 4,
};
// Enum SlateCore.EUINavigationRule
enum class SlateCore_EUINavigationRule : uint8_t
{
EUINavigationRule__Escape = 0,
EUINavigationRule__Explicit = 1,
EUINavigationRule__Wrap = 2,
EUINavigationRule__Stop = 3,
EUINavigationRule__Custom = 4,
EUINavigationRule__CustomBoundary = 5,
EUINavigationRule__Invalid = 6,
EUINavigationRule__EUINavigationRule_MAX = 7,
};
// Enum SlateCore.EFlowDirectionPreference
enum class SlateCore_EFlowDirectionPreference : uint8_t
{
EFlowDirectionPreference__Inherit = 0,
EFlowDirectionPreference__Culture = 1,
EFlowDirectionPreference__LeftToRight = 2,
EFlowDirectionPreference__RightToLeft = 3,
EFlowDirectionPreference__EFlowDirectionPreference_MAX = 4,
};
// Enum SlateCore.EColorVisionDeficiency
enum class SlateCore_EColorVisionDeficiency : uint8_t
{
EColorVisionDeficiency__NormalVision = 0,
EColorVisionDeficiency__Deuteranope = 1,
EColorVisionDeficiency__Protanope = 2,
EColorVisionDeficiency__Tritanope = 3,
EColorVisionDeficiency__EColorVisionDeficiency_MAX = 4,
};
// Enum SlateCore.ESelectInfo
enum class SlateCore_ESelectInfo : uint8_t
{
ESelectInfo__OnKeyPress = 0,
ESelectInfo__OnNavigation = 1,
ESelectInfo__OnMouseClick = 2,
ESelectInfo__Direct = 3,
ESelectInfo__ESelectInfo_MAX = 4,
};
// Enum SlateCore.ETextCommit
enum class SlateCore_ETextCommit : uint8_t
{
ETextCommit__Default = 0,
ETextCommit__OnEnter = 1,
ETextCommit__OnUserMovedFocus = 2,
ETextCommit__OnCleared = 3,
ETextCommit__ETextCommit_MAX = 4,
};
// Enum SlateCore.ETextShapingMethod
enum class SlateCore_ETextShapingMethod : uint8_t
{
ETextShapingMethod__Auto = 0,
ETextShapingMethod__KerningOnly = 1,
ETextShapingMethod__FullShaping = 2,
ETextShapingMethod__ETextShapingMethod_MAX = 3,
};
// Enum SlateCore.EOrientation
enum class SlateCore_EOrientation : uint8_t
{
Orient_Horizontal = 0,
Orient_Vertical = 1,
Orient_MAX = 2,
};
// Enum SlateCore.EFontLayoutMethod
enum class SlateCore_EFontLayoutMethod : uint8_t
{
EFontLayoutMethod__Metrics = 0,
EFontLayoutMethod__BoundingBox = 1,
EFontLayoutMethod__EFontLayoutMethod_MAX = 2,
};
// Enum SlateCore.EFontLoadingPolicy
enum class SlateCore_EFontLoadingPolicy : uint8_t
{
EFontLoadingPolicy__LazyLoad = 0,
EFontLoadingPolicy__Stream = 1,
EFontLoadingPolicy__Inline = 2,
EFontLoadingPolicy__EFontLoadingPolicy_MAX = 3,
};
// Enum SlateCore.EFontHinting
enum class SlateCore_EFontHinting : uint8_t
{
EFontHinting__Default = 0,
EFontHinting__Auto = 1,
EFontHinting__AutoLight = 2,
EFontHinting__Monochrome = 3,
EFontHinting__None = 4,
EFontHinting__EFontHinting_MAX = 5,
};
// Enum SlateCore.EFocusCause
enum class SlateCore_EFocusCause : uint8_t
{
EFocusCause__Mouse = 0,
EFocusCause__Navigation = 1,
EFocusCause__SetDirectly = 2,
EFocusCause__Cleared = 3,
EFocusCause__OtherWidgetLostFocus = 4,
EFocusCause__WindowActivate = 5,
EFocusCause__EFocusCause_MAX = 6,
};
// Enum SlateCore.ESlateDebuggingFocusEvent
enum class SlateCore_ESlateDebuggingFocusEvent : uint8_t
{
ESlateDebuggingFocusEvent__FocusChanging = 0,
ESlateDebuggingFocusEvent__FocusLost = 1,
ESlateDebuggingFocusEvent__FocusReceived = 2,
ESlateDebuggingFocusEvent__ESlateDebuggingFocusEvent_MAX = 3,
};
// Enum SlateCore.ESlateDebuggingNavigationMethod
enum class SlateCore_ESlateDebuggingNavigationMethod : uint8_t
{
ESlateDebuggingNavigationMethod__Unknown = 0,
ESlateDebuggingNavigationMethod__Explicit = 1,
ESlateDebuggingNavigationMethod__CustomDelegateBound = 2,
ESlateDebuggingNavigationMethod__CustomDelegateUnbound = 3,
ESlateDebuggingNavigationMethod__NextOrPrevious = 4,
ESlateDebuggingNavigationMethod__HitTestGrid = 5,
ESlateDebuggingNavigationMethod__ESlateDebuggingNavigationMethod_MAX = 6,
};
// Enum SlateCore.ESlateDebuggingStateChangeEvent
enum class SlateCore_ESlateDebuggingStateChangeEvent : uint8_t
{
ESlateDebuggingStateChangeEvent__MouseCaptureGained = 0,
ESlateDebuggingStateChangeEvent__MouseCaptureLost = 1,
ESlateDebuggingStateChangeEvent__ESlateDebuggingStateChangeEvent_MAX = 2,
};
// Enum SlateCore.ESlateDebuggingInputEvent
enum class SlateCore_ESlateDebuggingInputEvent : uint8_t
{
ESlateDebuggingInputEvent__MouseMove = 0,
ESlateDebuggingInputEvent__MouseEnter = 1,
ESlateDebuggingInputEvent__MouseLeave = 2,
ESlateDebuggingInputEvent__MouseButtonDown = 3,
ESlateDebuggingInputEvent__MouseButtonUp = 4,
ESlateDebuggingInputEvent__MouseButtonDoubleClick = 5,
ESlateDebuggingInputEvent__MouseWheel = 6,
ESlateDebuggingInputEvent__TouchStart = 7,
ESlateDebuggingInputEvent__TouchEnd = 8,
ESlateDebuggingInputEvent__DragDetected = 9,
ESlateDebuggingInputEvent__DragEnter = 10,
ESlateDebuggingInputEvent__DragLeave = 11,
ESlateDebuggingInputEvent__DragOver = 12,
ESlateDebuggingInputEvent__DragDrop = 13,
ESlateDebuggingInputEvent__DropMessage = 14,
ESlateDebuggingInputEvent__KeyDown = 15,
ESlateDebuggingInputEvent__KeyUp = 16,
ESlateDebuggingInputEvent__KeyChar = 17,
ESlateDebuggingInputEvent__AnalogInput = 18,
ESlateDebuggingInputEvent__TouchGesture = 19,
ESlateDebuggingInputEvent__COUNT = 20,
ESlateDebuggingInputEvent__ESlateDebuggingInputEvent_MAX = 21,
};
// Enum SlateCore.EScrollDirection
enum class SlateCore_EScrollDirection : uint8_t
{
Scroll_Down = 0,
Scroll_Up = 1,
Scroll_MAX = 2,
};
// Enum SlateCore.EMenuPlacement
enum class SlateCore_EMenuPlacement : uint8_t
{
MenuPlacement_BelowAnchor = 0,
MenuPlacement_CenteredBelowAnchor = 1,
MenuPlacement_BelowRightAnchor = 2,
MenuPlacement_ComboBox = 3,
MenuPlacement_ComboBoxRight = 4,
MenuPlacement_MenuRight = 5,
MenuPlacement_AboveAnchor = 6,
MenuPlacement_CenteredAboveAnchor = 7,
MenuPlacement_AboveRightAnchor = 8,
MenuPlacement_MenuLeft = 9,
MenuPlacement_Center = 10,
MenuPlacement_RightLeftCenter = 11,
MenuPlacement_MatchBottomLeft = 12,
MenuPlacement_MAX = 13,
};
// Enum SlateCore.EVerticalAlignment
enum class SlateCore_EVerticalAlignment : uint8_t
{
VAlign_Fill = 0,
VAlign_Top = 1,
VAlign_Center = 2,
VAlign_Bottom = 3,
VAlign_MAX = 4,
};
// Enum SlateCore.EHorizontalAlignment
enum class SlateCore_EHorizontalAlignment : uint8_t
{
HAlign_Fill = 0,
HAlign_Left = 1,
HAlign_Center = 2,
HAlign_Right = 3,
HAlign_MAX = 4,
};
// Enum SlateCore.ENavigationGenesis
enum class SlateCore_ENavigationGenesis : uint8_t
{
ENavigationGenesis__Keyboard = 0,
ENavigationGenesis__Controller = 1,
ENavigationGenesis__User = 2,
ENavigationGenesis__ENavigationGenesis_MAX = 3,
};
// Enum SlateCore.ENavigationSource
enum class SlateCore_ENavigationSource : uint8_t
{
ENavigationSource__FocusedWidget = 0,
ENavigationSource__WidgetUnderCursor = 1,
ENavigationSource__ENavigationSource_MAX = 2,
};
// Enum SlateCore.EUINavigationAction
enum class SlateCore_EUINavigationAction : uint8_t
{
EUINavigationAction__Accept = 0,
EUINavigationAction__Back = 1,
EUINavigationAction__Num = 2,
EUINavigationAction__Invalid = 3,
EUINavigationAction__EUINavigationAction_MAX = 4,
};
// Enum SlateCore.EButtonPressMethod
enum class SlateCore_EButtonPressMethod : uint8_t
{
EButtonPressMethod__DownAndUp = 0,
EButtonPressMethod__ButtonPress = 1,
EButtonPressMethod__ButtonRelease = 2,
EButtonPressMethod__EButtonPressMethod_MAX = 3,
};
// Enum SlateCore.EButtonTouchMethod
enum class SlateCore_EButtonTouchMethod : uint8_t
{
EButtonTouchMethod__DownAndUp = 0,
EButtonTouchMethod__Down = 1,
EButtonTouchMethod__PreciseTap = 2,
EButtonTouchMethod__EButtonTouchMethod_MAX = 3,
};
// Enum SlateCore.EButtonClickMethod
enum class SlateCore_EButtonClickMethod : uint8_t
{
EButtonClickMethod__DownAndUp = 0,
EButtonClickMethod__MouseDown = 1,
EButtonClickMethod__MouseUp = 2,
EButtonClickMethod__PreciseClick = 3,
EButtonClickMethod__EButtonClickMethod_MAX = 4,
};
// Enum SlateCore.ESlateCheckBoxType
enum class SlateCore_ESlateCheckBoxType : uint8_t
{
ESlateCheckBoxType__CheckBox = 0,
ESlateCheckBoxType__ToggleButton = 1,
ESlateCheckBoxType__ESlateCheckBoxType_MAX = 2,
};
// Enum SlateCore.ESlateParentWindowSearchMethod
enum class SlateCore_ESlateParentWindowSearchMethod : uint8_t
{
ESlateParentWindowSearchMethod__ActiveWindow = 0,
ESlateParentWindowSearchMethod__MainWindow = 1,
ESlateParentWindowSearchMethod__ESlateParentWindowSearchMethod_MAX = 2,
};
// Enum SlateCore.EConsumeMouseWheel
enum class SlateCore_EConsumeMouseWheel : uint8_t
{
EConsumeMouseWheel__WhenScrollingPossible = 0,
EConsumeMouseWheel__Always = 1,
EConsumeMouseWheel__Never = 2,
EConsumeMouseWheel__EConsumeMouseWheel_MAX = 3,
};
//---------------------------------------------------------------------------
// Script Structs
//---------------------------------------------------------------------------
// ScriptStruct SlateCore.Geometry
// 0x0058
struct FGeometry
{
unsigned char UnknownData_XRW2[0x58]; // 0x0000(0x0058) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.Margin
// 0x0010
struct FMargin
{
float Left; // 0x0000(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float Top; // 0x0004(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float Right; // 0x0008(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float Bottom; // 0x000C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.SlateColor
// 0x0028
struct FSlateColor
{
struct FLinearColor SpecifiedColor; // 0x0000(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, Protected, HasGetValueTypeHash, NativeAccessSpecifierProtected)
TEnumAsByte<SlateCore_ESlateColorStylingMode> ColorUseRule; // 0x0010(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, Protected, HasGetValueTypeHash, NativeAccessSpecifierProtected)
unsigned char UnknownData_W3MQ[0x17]; // 0x0011(0x0017) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.SlateBrush
// 0x0088
struct FSlateBrush
{
unsigned char UnknownData_HCL7[0x8]; // 0x0000(0x0008) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FVector2D ImageSize; // 0x0008(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FMargin Margin; // 0x0010(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateColor TintColor; // 0x0020(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
class UObject* ResourceObject; // 0x0048(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPrivate)
struct FName ResourceName; // 0x0050(0x0008) (ZeroConstructor, IsPlainOldData, NoDestructor, Protected, HasGetValueTypeHash, NativeAccessSpecifierProtected)
struct FBox2D UVRegion; // 0x0058(0x0014) (ZeroConstructor, NoDestructor, Protected, NativeAccessSpecifierProtected)
TEnumAsByte<SlateCore_ESlateBrushDrawType> DrawAs; // 0x006C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<SlateCore_ESlateBrushTileType> Tiling; // 0x006D(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<SlateCore_ESlateBrushMirrorType> Mirroring; // 0x006E(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<SlateCore_ESlateBrushImageType> ImageType; // 0x006F(0x0001) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_7ILB[0x10]; // 0x0070(0x0010) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
unsigned char bIsDynamicallyLoaded : 1; // 0x0080(0x0001) BIT_FIELD (NoDestructor, Protected, HasGetValueTypeHash, NativeAccessSpecifierProtected)
unsigned char bHasUObject : 1; // 0x0080(0x0001) BIT_FIELD (Deprecated, NoDestructor, Protected, HasGetValueTypeHash, NativeAccessSpecifierProtected)
unsigned char UnknownData_8KE3[0x7]; // 0x0081(0x0007) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.InputEvent
// 0x0018
struct FInputEvent
{
unsigned char UnknownData_7S00[0x18]; // 0x0000(0x0018) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.PointerEvent
// 0x0058 (0x0070 - 0x0018)
struct FPointerEvent : public FInputEvent
{
unsigned char UnknownData_XZ58[0x58]; // 0x0018(0x0058) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.CharacterEvent
// 0x0008 (0x0020 - 0x0018)
struct FCharacterEvent : public FInputEvent
{
unsigned char UnknownData_BOBN[0x8]; // 0x0018(0x0008) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.KeyEvent
// 0x0020 (0x0038 - 0x0018)
struct FKeyEvent : public FInputEvent
{
unsigned char UnknownData_MJAD[0x20]; // 0x0018(0x0020) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.NavigationEvent
// 0x0008 (0x0020 - 0x0018)
struct FNavigationEvent : public FInputEvent
{
unsigned char UnknownData_02X6[0x8]; // 0x0018(0x0008) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.AnalogInputEvent
// 0x0008 (0x0040 - 0x0038)
struct FAnalogInputEvent : public FKeyEvent
{
unsigned char UnknownData_VKUX[0x8]; // 0x0038(0x0008) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.FontOutlineSettings
// 0x0020
struct FFontOutlineSettings
{
int OutlineSize; // 0x0000(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bSeparateFillAlpha; // 0x0004(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bApplyOutlineToDropShadows; // 0x0005(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_WM4H[0x2]; // 0x0006(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
class UObject* OutlineMaterial; // 0x0008(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FLinearColor OutlineColor; // 0x0010(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.SlateFontInfo
// 0x0050
struct FSlateFontInfo
{
class UObject* FontObject; // 0x0000(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UObject* FontMaterial; // 0x0008(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FFontOutlineSettings OutlineSettings; // 0x0010(0x0020) (Edit, BlueprintVisible, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_NVE5[0x10]; // 0x0030(0x0010) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FName TypefaceFontName; // 0x0040(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int Size; // 0x0048(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_NMF7[0x4]; // 0x004C(0x0004) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.SlateWidgetStyle
// 0x0008
struct FSlateWidgetStyle
{
unsigned char UnknownData_CCTQ[0x8]; // 0x0000(0x0008) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.TableRowStyle
// 0x07C0 (0x07C8 - 0x0008)
struct FTableRowStyle : public FSlateWidgetStyle
{
struct FSlateBrush SelectorFocusedBrush; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ActiveHoveredBrush; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ActiveBrush; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush InactiveHoveredBrush; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush InactiveBrush; // 0x0228(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush EvenRowBackgroundHoveredBrush; // 0x02B0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush EvenRowBackgroundBrush; // 0x0338(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush OddRowBackgroundHoveredBrush; // 0x03C0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush OddRowBackgroundBrush; // 0x0448(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor TextColor; // 0x04D0(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor SelectedTextColor; // 0x04F8(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DropIndicator_Above; // 0x0520(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DropIndicator_Onto; // 0x05A8(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DropIndicator_Below; // 0x0630(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ActiveHighlightedBrush; // 0x06B8(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush InactiveHighlightedBrush; // 0x0740(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.SlateSound
// 0x0018
struct FSlateSound
{
class UObject* ResourceObject; // 0x0000(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, Protected, HasGetValueTypeHash, NativeAccessSpecifierProtected)
unsigned char UnknownData_W8VZ[0x10]; // 0x0008(0x0010) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.ButtonStyle
// 0x0270 (0x0278 - 0x0008)
struct FButtonStyle : public FSlateWidgetStyle
{
struct FSlateBrush Normal; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush Hovered; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush Pressed; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush Disabled; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FMargin NormalPadding; // 0x0228(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FMargin PressedPadding; // 0x0238(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateSound PressedSlateSound; // 0x0248(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateSound HoveredSlateSound; // 0x0260(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.ComboButtonStyle
// 0x03B0 (0x03B8 - 0x0008)
struct FComboButtonStyle : public FSlateWidgetStyle
{
struct FButtonStyle ButtonStyle; // 0x0008(0x0278) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DownArrowImage; // 0x0280(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FVector2D ShadowOffset; // 0x0308(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FLinearColor ShadowColorAndOpacity; // 0x0310(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateBrush MenuBorderBrush; // 0x0320(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FMargin MenuBorderPadding; // 0x03A8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.ComboBoxStyle
// 0x03E8 (0x03F0 - 0x0008)
struct FComboBoxStyle : public FSlateWidgetStyle
{
struct FComboButtonStyle ComboButtonStyle; // 0x0008(0x03B8) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateSound PressedSlateSound; // 0x03C0(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateSound SelectionChangeSlateSound; // 0x03D8(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.EditableTextStyle
// 0x0210 (0x0218 - 0x0008)
struct FEditableTextStyle : public FSlateWidgetStyle
{
struct FSlateFontInfo Font; // 0x0008(0x0050) (Edit, BlueprintVisible, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateColor ColorAndOpacity; // 0x0058(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundImageSelected; // 0x0080(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundImageComposing; // 0x0108(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush CaretImage; // 0x0190(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.ScrollBarStyle
// 0x04C8 (0x04D0 - 0x0008)
struct FScrollBarStyle : public FSlateWidgetStyle
{
struct FSlateBrush HorizontalBackgroundImage; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush VerticalBackgroundImage; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush VerticalTopSlotImage; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HorizontalTopSlotImage; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush VerticalBottomSlotImage; // 0x0228(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HorizontalBottomSlotImage; // 0x02B0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush NormalThumbImage; // 0x0338(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HoveredThumbImage; // 0x03C0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DraggedThumbImage; // 0x0448(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.EditableTextBoxStyle
// 0x07E8 (0x07F0 - 0x0008)
struct FEditableTextBoxStyle : public FSlateWidgetStyle
{
struct FSlateBrush BackgroundImageNormal; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundImageHovered; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundImageFocused; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundImageReadOnly; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FMargin Padding; // 0x0228(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateFontInfo Font; // 0x0238(0x0050) (Edit, BlueprintVisible, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateColor ForegroundColor; // 0x0288(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor BackgroundColor; // 0x02B0(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor ReadOnlyForegroundColor; // 0x02D8(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FMargin HScrollBarPadding; // 0x0300(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FMargin VScrollBarPadding; // 0x0310(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FScrollBarStyle ScrollBarStyle; // 0x0320(0x04D0) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.TextBlockStyle
// 0x0260 (0x0268 - 0x0008)
struct FTextBlockStyle : public FSlateWidgetStyle
{
struct FSlateFontInfo Font; // 0x0008(0x0050) (Edit, BlueprintVisible, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateColor ColorAndOpacity; // 0x0058(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FVector2D ShadowOffset; // 0x0080(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FLinearColor ShadowColorAndOpacity; // 0x0088(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateColor SelectedBackgroundColor; // 0x0098(0x0028) (Edit, NativeAccessSpecifierPublic)
struct FLinearColor HighlightColor; // 0x00C0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateBrush HighlightShape; // 0x00D0(0x0088) (Edit, BlueprintVisible, AdvancedDisplay, NativeAccessSpecifierPublic)
struct FSlateBrush StrikeBrush; // 0x0158(0x0088) (Edit, BlueprintVisible, AdvancedDisplay, NativeAccessSpecifierPublic)
struct FSlateBrush UnderlineBrush; // 0x01E0(0x0088) (Edit, BlueprintVisible, AdvancedDisplay, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.SpinBoxStyle
// 0x02E0 (0x02E8 - 0x0008)
struct FSpinBoxStyle : public FSlateWidgetStyle
{
struct FSlateBrush BackgroundBrush; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HoveredBackgroundBrush; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ActiveFillBrush; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush InactiveFillBrush; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ArrowsImage; // 0x0228(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor ForegroundColor; // 0x02B0(0x0028) (NativeAccessSpecifierPublic)
struct FMargin TextPadding; // 0x02D8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.FocusEvent
// 0x0008
struct FFocusEvent
{
unsigned char UnknownData_CR3E[0x8]; // 0x0000(0x0008) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.MotionEvent
// 0x0030 (0x0048 - 0x0018)
struct FMotionEvent : public FInputEvent
{
unsigned char UnknownData_5LCR[0x30]; // 0x0018(0x0030) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.FontData
// 0x0020
struct FFontData
{
struct FString FontFilename; // 0x0000(0x0010) (ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPrivate)
SlateCore_EFontHinting Hinting; // 0x0010(0x0001) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPrivate)
SlateCore_EFontLoadingPolicy LoadingPolicy; // 0x0011(0x0001) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPrivate)
unsigned char UnknownData_4P07[0x2]; // 0x0012(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
int SubFaceIndex; // 0x0014(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPrivate)
class UObject* FontFaceAsset; // 0x0018(0x0008) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPrivate)
};
// ScriptStruct SlateCore.TypefaceEntry
// 0x0028
struct FTypefaceEntry
{
struct FName Name; // 0x0000(0x0008) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FFontData Font; // 0x0008(0x0020) (HasGetValueTypeHash, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.Typeface
// 0x0010
struct FTypeface
{
TArray<struct FTypefaceEntry> Fonts; // 0x0000(0x0010) (ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.CompositeFallbackFont
// 0x0018
struct FCompositeFallbackFont
{
struct FTypeface Typeface; // 0x0000(0x0010) (NativeAccessSpecifierPublic)
float ScalingFactor; // 0x0010(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_F6UF[0x4]; // 0x0014(0x0004) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.CompositeSubFont
// 0x0020 (0x0038 - 0x0018)
struct FCompositeSubFont : public FCompositeFallbackFont
{
TArray<struct FInt32Range> CharacterRanges; // 0x0018(0x0010) (ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FString Cultures; // 0x0028(0x0010) (ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.CompositeFont
// 0x0038
struct FCompositeFont
{
struct FTypeface DefaultTypeface; // 0x0000(0x0010) (NativeAccessSpecifierPublic)
struct FCompositeFallbackFont FallbackTypeface; // 0x0010(0x0018) (NativeAccessSpecifierPublic)
TArray<struct FCompositeSubFont> SubTypefaces; // 0x0028(0x0010) (ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.CaptureLostEvent
// 0x0008
struct FCaptureLostEvent
{
unsigned char UnknownData_7YH9[0x8]; // 0x0000(0x0008) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.WindowStyle
// 0x1050 (0x1058 - 0x0008)
struct FWindowStyle : public FSlateWidgetStyle
{
struct FButtonStyle MinimizeButtonStyle; // 0x0008(0x0278) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FButtonStyle MaximizeButtonStyle; // 0x0280(0x0278) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FButtonStyle RestoreButtonStyle; // 0x04F8(0x0278) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FButtonStyle CloseButtonStyle; // 0x0770(0x0278) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FTextBlockStyle TitleTextStyle; // 0x09E8(0x0268) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ActiveTitleBrush; // 0x0C50(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush InactiveTitleBrush; // 0x0CD8(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush FlashTitleBrush; // 0x0D60(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor BackgroundColor; // 0x0DE8(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush OutlineBrush; // 0x0E10(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor OutlineColor; // 0x0E98(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BorderBrush; // 0x0EC0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundBrush; // 0x0F48(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush ChildBackgroundBrush; // 0x0FD0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.ScrollBorderStyle
// 0x0110 (0x0118 - 0x0008)
struct FScrollBorderStyle : public FSlateWidgetStyle
{
struct FSlateBrush TopShadowBrush; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BottomShadowBrush; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.ScrollBoxStyle
// 0x0220 (0x0228 - 0x0008)
struct FScrollBoxStyle : public FSlateWidgetStyle
{
struct FSlateBrush TopShadowBrush; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush BottomShadowBrush; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush LeftShadowBrush; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush RightShadowBrush; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.DockTabStyle
// 0x06F8 (0x0700 - 0x0008)
struct FDockTabStyle : public FSlateWidgetStyle
{
struct FButtonStyle CloseButtonStyle; // 0x0008(0x0278) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush NormalBrush; // 0x0280(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ActiveBrush; // 0x0308(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ColorOverlayTabBrush; // 0x0390(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ColorOverlayIconBrush; // 0x0418(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ForegroundBrush; // 0x04A0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush HoveredBrush; // 0x0528(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ContentAreaBrush; // 0x05B0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush TabWellBrush; // 0x0638(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FMargin TabPadding; // 0x06C0(0x0010) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
float OverlapWidth; // 0x06D0(0x0004) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_PRF1[0x4]; // 0x06D4(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FSlateColor FlashColor; // 0x06D8(0x0028) (Edit, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.SplitterStyle
// 0x0110 (0x0118 - 0x0008)
struct FSplitterStyle : public FSlateWidgetStyle
{
struct FSlateBrush HandleNormalBrush; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HandleHighlightBrush; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.TableColumnHeaderStyle
// 0x04C8 (0x04D0 - 0x0008)
struct FTableColumnHeaderStyle : public FSlateWidgetStyle
{
struct FSlateBrush SortPrimaryAscendingImage; // 0x0008(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush SortPrimaryDescendingImage; // 0x0090(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush SortSecondaryAscendingImage; // 0x0118(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush SortSecondaryDescendingImage; // 0x01A0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush NormalBrush; // 0x0228(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush HoveredBrush; // 0x02B0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush MenuDropdownImage; // 0x0338(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush MenuDropdownNormalBorderBrush; // 0x03C0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush MenuDropdownHoveredBorderBrush; // 0x0448(0x0088) (Edit, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.HeaderRowStyle
// 0x0B68 (0x0B70 - 0x0008)
struct FHeaderRowStyle : public FSlateWidgetStyle
{
struct FTableColumnHeaderStyle ColumnStyle; // 0x0008(0x04D0) (Edit, NativeAccessSpecifierPublic)
struct FTableColumnHeaderStyle LastColumnStyle; // 0x04D8(0x04D0) (Edit, NativeAccessSpecifierPublic)
struct FSplitterStyle ColumnSplitterStyle; // 0x09A8(0x0118) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush BackgroundBrush; // 0x0AC0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateColor ForegroundColor; // 0x0B48(0x0028) (Edit, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.InlineTextImageStyle
// 0x0090 (0x0098 - 0x0008)
struct FInlineTextImageStyle : public FSlateWidgetStyle
{
struct FSlateBrush Image; // 0x0008(0x0088) (Edit, NativeAccessSpecifierPublic)
int16_t Baseline; // 0x0090(0x0002) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_8BM2[0x6]; // 0x0092(0x0006) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.SliderStyle
// 0x0338 (0x0340 - 0x0008)
struct FSliderStyle : public FSlateWidgetStyle
{
struct FSlateBrush NormalBarImage; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HoveredBarImage; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DisabledBarImage; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush NormalThumbImage; // 0x01A0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush HoveredThumbImage; // 0x0228(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush DisabledThumbImage; // 0x02B0(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
float BarThickness; // 0x0338(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_8XPQ[0x4]; // 0x033C(0x0004) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.VolumeControlStyle
// 0x05E8 (0x05F0 - 0x0008)
struct FVolumeControlStyle : public FSlateWidgetStyle
{
struct FSliderStyle SliderStyle; // 0x0008(0x0340) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush HighVolumeImage; // 0x0348(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush MidVolumeImage; // 0x03D0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush LowVolumeImage; // 0x0458(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush NoVolumeImage; // 0x04E0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush MutedImage; // 0x0568(0x0088) (Edit, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.SearchBoxStyle
// 0x0A78 (0x0A80 - 0x0008)
struct FSearchBoxStyle : public FSlateWidgetStyle
{
struct FEditableTextBoxStyle TextBoxStyle; // 0x0008(0x07F0) (Edit, NativeAccessSpecifierPublic)
struct FSlateFontInfo ActiveFontInfo; // 0x07F8(0x0050) (Edit, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FSlateBrush UpArrowImage; // 0x0848(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush DownArrowImage; // 0x08D0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush GlassImage; // 0x0958(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ClearImage; // 0x09E0(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FMargin ImagePadding; // 0x0A68(0x0010) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
bool bLeftAlignButtons; // 0x0A78(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_YWEU[0x7]; // 0x0A79(0x0007) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.ExpandableAreaStyle
// 0x0118 (0x0120 - 0x0008)
struct FExpandableAreaStyle : public FSlateWidgetStyle
{
struct FSlateBrush CollapsedImage; // 0x0008(0x0088) (Edit, NativeAccessSpecifierPublic)
struct FSlateBrush ExpandedImage; // 0x0090(0x0088) (Edit, NativeAccessSpecifierPublic)
float RolloutAnimationSeconds; // 0x0118(0x0004) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_7978[0x4]; // 0x011C(0x0004) MISSED OFFSET (PADDING)
};
// ScriptStruct SlateCore.ProgressBarStyle
// 0x0198 (0x01A0 - 0x0008)
struct FProgressBarStyle : public FSlateWidgetStyle
{
struct FSlateBrush BackgroundImage; // 0x0008(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush FillImage; // 0x0090(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush MarqueeImage; // 0x0118(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.InlineEditableTextBlockStyle
// 0x0A58 (0x0A60 - 0x0008)
struct FInlineEditableTextBlockStyle : public FSlateWidgetStyle
{
struct FEditableTextBoxStyle EditableTextBoxStyle; // 0x0008(0x07F0) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FTextBlockStyle TextStyle; // 0x07F8(0x0268) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.HyperlinkStyle
// 0x04F0 (0x04F8 - 0x0008)
struct FHyperlinkStyle : public FSlateWidgetStyle
{
struct FButtonStyle UnderlineStyle; // 0x0008(0x0278) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FTextBlockStyle TextStyle; // 0x0280(0x0268) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FMargin Padding; // 0x04E8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
};
// ScriptStruct SlateCore.CheckBoxStyle
// 0x0578 (0x0580 - 0x0008)
struct FCheckBoxStyle : public FSlateWidgetStyle
{
TEnumAsByte<SlateCore_ESlateCheckBoxType> CheckBoxType; // 0x0008(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_G4N3[0x7]; // 0x0009(0x0007) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FSlateBrush UncheckedImage; // 0x0010(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush UncheckedHoveredImage; // 0x0098(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush UncheckedPressedImage; // 0x0120(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush CheckedImage; // 0x01A8(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush CheckedHoveredImage; // 0x0230(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush CheckedPressedImage; // 0x02B8(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush UndeterminedImage; // 0x0340(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush UndeterminedHoveredImage; // 0x03C8(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateBrush UndeterminedPressedImage; // 0x0450(0x0088) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FMargin Padding; // 0x04D8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateColor ForegroundColor; // 0x04E8(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateColor BorderBackgroundColor; // 0x0510(0x0028) (Edit, BlueprintVisible, NativeAccessSpecifierPublic)
struct FSlateSound CheckedSlateSound; // 0x0538(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateSound UncheckedSlateSound; // 0x0550(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
struct FSlateSound HoveredSlateSound; // 0x0568(0x0018) (Edit, BlueprintVisible, NoDestructor, NativeAccessSpecifierPublic)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"51001754+dmitrysolovev@users.noreply.github.com"
] |
51001754+dmitrysolovev@users.noreply.github.com
|
65bc2c401065fd7070888ce56f69bce85e27def2
|
588e257bcb02727829239d308fe2decbb016e184
|
/addons/ofxImGui/src/Gui.h
|
9cb84c7d4422969d767335e4cfd9197befc2de0f
|
[] |
no_license
|
museumsvictoria/EnergeticVibrationsProjectionMapping
|
1be0d463371cf3dcfe2129ae831b2ab1458cab77
|
2ea7e65bd2bd186b101ac2c5c1d9d9c8dec41217
|
refs/heads/master
| 2021-03-19T06:26:41.752386
| 2018-04-28T09:39:39
| 2018-04-28T09:39:39
| 102,068,860
| 9
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 709
|
h
|
#pragma once
#include "ofImage.h"
#include "ofPixels.h"
#include "ofTexture.h"
#include "BaseEngine.h"
#include "BaseTheme.h"
namespace ofxImGui
{
class Gui
{
public:
Gui();
~Gui();
void setup(BaseTheme* theme = nullptr);
void begin();
void end();
void close();
BaseEngine* engine;
float lastTime;
void setTheme(BaseTheme* theme);
void openThemeColorWindow();
BaseTheme* theme;
GLuint loadImage(ofImage& image);
GLuint loadImage(string imagePath);
GLuint loadPixels(string imagePath);
GLuint loadPixels(ofPixels& pixels);
GLuint loadTexture(string imagePath);
GLuint loadTexture(ofTexture& texture, string imagePath);
vector<ofTexture*> loadedTextures;
};
}
|
[
"joshpbatty@gmail.com"
] |
joshpbatty@gmail.com
|
d8a216571108388ba15a8b35796a1f409d023812
|
f01a504c3d3b373d8dc3343a7d4167c122dee740
|
/rogue/spriteaistate.h
|
ae6a2affc8dd9877be1845e19d4787daa91f9a80
|
[
"BSD-3-Clause"
] |
permissive
|
zork9/rogue
|
ac011884f3c5fae78e827915172f8ec79136fa69
|
b6fa9497e9a09636b4c91840c1248e0912a2014f
|
refs/heads/master
| 2016-09-05T13:39:55.067991
| 2015-04-29T08:41:04
| 2015-04-29T08:41:04
| 34,675,438
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 431
|
h
|
#ifndef _SPRITE_AI_STATE_H_
#define _SPRITE_AI_STATE_H_
class SpriteState;
class SpriteAIState
{
public:
SpriteAIState();
~SpriteAIState();
virtual void moving(SpriteAIState*);
virtual void nothing(SpriteAIState*);
virtual void attacking(SpriteAIState*);
virtual void running(SpriteAIState*);
protected:
friend class SpriteState;
void changeState(SpriteState*);
private:
SpriteState *_state;
};
#endif
|
[
"goon@thangorodrim.imp.net"
] |
goon@thangorodrim.imp.net
|
a0a0fce027e795d85b228941f2cb8b87c6a60673
|
c29b2bbeca1c84d205c5306da107e94f09acd0a2
|
/include/magicpenguin.h
|
6a3498736d41f3ddb3acb0315556b0b2939c7d88
|
[
"LicenseRef-scancode-mulanpsl-1.0-en",
"MulanPSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
feiyangqingyun/qucsdk
|
e5131db5e9c8241a8c467d3710f42d69c3415274
|
23b854d7214371a0055aaf5593bb5501f1bb26f8
|
refs/heads/master
| 2023-07-18T12:40:33.738727
| 2023-07-15T01:33:28
| 2023-07-15T01:33:28
| 214,094,389
| 527
| 199
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,065
|
h
|
#ifndef MAGICPENGUIN_H
#define MAGICPENGUIN_H
/**
* 魔幻企鹅 作者:feiyangqingyun(QQ:517216493) 2021-08-06
* 1. 可设置企鹅身体部位的各种颜色。
* 2. 可设置基准颜色应用所有。
*/
#include <QWidget>
#ifdef quc
class Q_DECL_EXPORT MagicPenguin : public QWidget
#else
class MagicPenguin : public QWidget
#endif
{
Q_OBJECT
public:
explicit MagicPenguin(QWidget *parent = 0);
protected:
void paintEvent(QPaintEvent *);
void drawBelly1(QPainter *painter);
void drawBelly2(QPainter *painter);
void drawBelly3(QPainter *painter);
void drawBelly4(QPainter *painter);
void drawBelly5(QPainter *painter);
void drawBelly6(QPainter *painter);
void drawShadow1(QPainter *painter);
void drawShadow2(QPainter *painter);
void drawRightFoot1(QPainter *painter);
void drawRightFoot2(QPainter *painter);
void drawCover1(QPainter *painter);
void drawCover2(QPainter *painter);
void drawLeftEye1(QPainter *painter);
void drawLeftEye2(QPainter *painter);
void drawLeftEye3(QPainter *painter);
void drawLeftEye4(QPainter *painter);
void drawRightEye1(QPainter *painter);
void drawRightEye2(QPainter *painter);
void drawRightEye3(QPainter *painter);
void drawRightEye4(QPainter *painter);
void drawMouth1(QPainter *painter);
void drawMouth2(QPainter *painter);
void drawMouth3(QPainter *painter);
void drawRightDot1(QPainter *painter);
void drawRightDot2(QPainter *painter);
void drawRightDot3(QPainter *painter);
void drawRightDot4(QPainter *painter);
void drawRightDot5(QPainter *painter);
void drawLeftHandArc(QPainter *painter);
void drawRightHandArc(QPainter *painter);
void drawBeautify1(QPainter *painter);
void drawBeautify2(QPainter *painter);
void drawBeautify3(QPainter *painter);
void drawLeftFoot1(QPainter *painter);
void drawLeftFoot2(QPainter *painter);
public:
QSize sizeHint() const;
QSize minimumSizeHint() const;
};
#endif // MAGICPENGUIN_H
|
[
"feiyangqingyun@163.com"
] |
feiyangqingyun@163.com
|
4bfdbbb8d66ccee2017934f56b14b4000fcfaa8f
|
5b50ab2701473189df078726981338ddf078d672
|
/Trie.h
|
b91a8cbcf6ed9d2c04c2cf5ac27256baf7cfbeff
|
[] |
no_license
|
jacob14916/genomics
|
e8d3377b75aa324ff1e75990cb0d3d646ba6b25a
|
fe769b8b54ca46ed5f2ad247b4f11531e14fa9f0
|
refs/heads/master
| 2020-04-27T11:05:28.821491
| 2019-03-15T05:58:46
| 2019-03-15T05:58:46
| 174,282,577
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,899
|
h
|
#ifndef TRIE_INCLUDED
#define TRIE_INCLUDED
#include <string>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
template<typename ValueType>
class Trie
{
public:
Trie() {
Node* rt = new Node;
root = rt;
}
~Trie() {
deleteNodeAndAllChildren(root);
}
void reset();
void insert(const string& key, const ValueType& value);
vector<ValueType> find(const string& key, bool exactMatchOnly) const;
// C++11 syntax for preventing copying and assignment
Trie(const Trie&) = delete;
Trie& operator=(const Trie&) = delete;
private:
struct NodePointerWithLabel;
struct Node {
Node() {
children = new list<NodePointerWithLabel>;
values = new vector<ValueType>;
}
~Node() {
delete children;
delete values;
}
list<NodePointerWithLabel>* children;
vector<ValueType>* values;
};
struct NodePointerWithLabel {
NodePointerWithLabel(Node* n, char l): node(n), label(l) {}
Node* node;
char label;
};
Node* root;
void deleteNodeAndAllChildren(Node* n);
vector<ValueType> findStartingFrom(Node* n, const string& key, int depth, bool exactMatchOnly) const;
};
template<typename ValueType>
void Trie<ValueType>::deleteNodeAndAllChildren(Node* n) {
for (typename list<NodePointerWithLabel>::iterator child = n->children->begin();
child != n->children->end(); child++) {
deleteNodeAndAllChildren((*child).node);
}
delete n;
}
template<typename ValueType>
void Trie<ValueType>::insert(const string& key, const ValueType& value) {
Node* current = root;
for (int i = 0; i < key.length(); i++) {
char c = key[i];
for (typename list<NodePointerWithLabel>::iterator child = current->children->begin();
true; // end condition handled inside the loop
child++)
{
if (child == current->children->end() || (*child).label > c)
{
Node *newnode = new Node;
current->children->insert(child, NodePointerWithLabel(newnode, c));
current = newnode;
break;
}
else if ((*child).label == c)
{
current = (*child).node;
break;
}
}
}
current->values->push_back(value);
}
template<typename ValueType>
vector<ValueType> Trie<ValueType>::find(const string& key, bool exactMatchOnly) const
{
vector<ValueType> vals;
if (key.length() > 0) {
char c = key[0];
for (typename list<NodePointerWithLabel>::iterator child = root->children->begin();
!(child == root->children->end() || (*child).label > c);
child++)
{
if ((*child).label == c)
{
vals = findStartingFrom((*child).node, key, 1, exactMatchOnly);
break;
}
}
}
return vals;
}
template<typename ValueType>
vector<ValueType> Trie<ValueType>::findStartingFrom(Node* n, const string& key, int depth, bool exactMatchOnly) const
{
if (depth == key.length()) {
return *(n->values);
}
char c = key[depth];
vector<ValueType> vals;
for(typename list<NodePointerWithLabel>::iterator child = n->children->begin();
!(child == n->children->end() || (exactMatchOnly && (*child).label > c));
child++)
{
bool childEMO = true;
if ((*child).label == c)
{
childEMO = exactMatchOnly;
} else if (exactMatchOnly) {
continue;
}
vector<ValueType> v = findStartingFrom((*child).node, key, depth+1, childEMO);
vals.insert(vals.end(), v.begin(), v.end());
}
return vals;
}
#endif // TRIE_INCLUDED
|
[
"jacob14916@users.noreply.github.com"
] |
jacob14916@users.noreply.github.com
|
503584e477c1f2287f115f7a0ee5394074d4529f
|
64a1533f4541b76181cd6d3cec3b28876c969250
|
/LADS/Storeman/DiscardPrologue.h
|
19612cfcab6636d7110b85dd16343b388d2a69e2
|
[] |
no_license
|
drkvogel/retrasst
|
df1db3330115f6e2eea7afdb869e070a28c1cae8
|
ee952fe39cf1a00998b00a09ca361fc7c83fa336
|
refs/heads/master
| 2020-05-16T22:53:26.565996
| 2014-08-01T16:52:16
| 2014-08-01T16:52:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 901
|
h
|
#ifndef DiscardPrologueH
#define DiscardPrologueH
#include <Classes.hpp>
#include <Controls.hpp>
#include <ExtCtrls.hpp>
#include <StdCtrls.hpp>
#include <string>
#include "DiscardContext.h"
class TfrmDiscardPrologue : public TForm
{
__published: // IDE-managed Components
TButton *btnOK;
TButton *btnCancel;
TRadioGroup *rgCryovialStatus;
TComboBox *cmbProject;
TLabel *Label1;
void __fastcall btnOKClick(TObject *Sender);
void __fastcall btnCancelClick(TObject *Sender);
void __fastcall rgCryovialStatusClick(TObject *Sender);
void __fastcall cmbProjectChange(TObject *Sender);
private: // User declarations
Discard::Context * m_context;
public: // User declarations
__fastcall TfrmDiscardPrologue(TComponent* Owner);
void init( Discard::Context * context );
void updateUI( );
};
extern PACKAGE TfrmDiscardPrologue *frmDiscardPrologue;
#endif
|
[
"chrisjbird@gmail.com"
] |
chrisjbird@gmail.com
|
20eeff5fee0f6d39926bab57ad1db0dadef2589a
|
f3121907c593d83c8738e44ac13ccf6af87b02b2
|
/jelly_bird/app/src/main/cpp/jellybird/engine/core/src/game/ui/view/View.cpp
|
4c8b38e69aeb1264a13c95e000d54f5cc53e12a8
|
[
"Apache-2.0"
] |
permissive
|
xavierfebrer/jelly_bird
|
044a3c982d7a4e6b54dcfddb14a42ba00d4a0591
|
2feea9007100366a76990ffd839e521acaf924fc
|
refs/heads/master
| 2021-06-26T20:05:16.229647
| 2020-10-19T21:15:59
| 2020-10-19T21:15:59
| 168,494,217
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 37
|
cpp
|
#include "../../../../include/View.h"
|
[
"xavierfebrer@gmail.com"
] |
xavierfebrer@gmail.com
|
8e4c0d4294df29f5caee21d5b4a854052565a0ec
|
ef432f1b63535630ba472d82e40b0ff216cb517a
|
/NFS2Prog.cpp
|
f5770be889c1364abdccfc72b4b139ba3438e8a4
|
[] |
no_license
|
noodle1983/winnfsd-nd
|
53e258f9b85d65e0c20cbfece4f22e19fb8d257f
|
c49277be0ad013d408898320dd2bcc456199f373
|
refs/heads/master
| 2016-09-06T02:50:16.568622
| 2010-08-14T10:10:53
| 2010-08-14T10:10:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,149
|
cpp
|
#include "NFSProg.h"
#include "FileTable.h"
#include <string.h>
#include <io.h>
#include <direct.h>
#include <sys/stat.h>
#include <windows.h>
enum
{
NFSPROC_NULL = 0,
NFSPROC_GETATTR = 1,
NFSPROC_SETATTR = 2,
NFSPROC_ROOT = 3,
NFSPROC_LOOKUP = 4,
NFSPROC_READLINK = 5,
NFSPROC_READ = 6,
NFSPROC_WRITECACHE = 7,
NFSPROC_WRITE = 8,
NFSPROC_CREATE = 9,
NFSPROC_REMOVE = 10,
NFSPROC_RENAME = 11,
NFSPROC_LINK = 12,
NFSPROC_SYMLINK = 13,
NFSPROC_MKDIR = 14,
NFSPROC_RMDIR = 15,
NFSPROC_READDIR = 16,
NFSPROC_STATFS = 17
};
enum
{
NFS_OK = 0,
NFSERR_PERM = 1,
NFSERR_NOENT = 2,
NFSERR_IO = 5,
NFSERR_NXIO = 6,
NFSERR_ACCES = 13,
NFSERR_EXIST = 17,
NFSERR_NODEV = 19,
NFSERR_NOTDIR = 20,
NFSERR_ISDIR = 21,
NFSERR_FBIG = 27,
NFSERR_NOSPC = 28,
NFSERR_ROFS = 30,
NFSERR_NAMETOOLONG = 63,
NFSERR_NOTEMPTY = 66,
NFSERR_DQUOT = 69,
NFSERR_STALE = 70,
NFSERR_WFLUSH = 99,
};
enum
{
NFNON = 0,
NFREG = 1,
NFDIR = 2,
NFBLK = 3,
NFCHR = 4,
NFLNK = 5,
};
typedef void(CNFS2Prog::*PPROC)(void);
CNFS2Prog::CNFS2Prog() : CRPCProg()
{
m_nUID = m_nGID = 0;
}
CNFS2Prog::~CNFS2Prog()
{
}
void CNFS2Prog::SetUserID(unsigned int nUID, unsigned int nGID)
{
m_nUID = nUID;
m_nGID = nGID;
}
int CNFS2Prog::Process(IInputStream *pInStream, IOutputStream *pOutStream, ProcessParam *pParam)
{
static PPROC pf[] = {&CNFS2Prog::ProcedureNULL, &CNFS2Prog::ProcedureGETATTR, &CNFS2Prog::ProcedureSETATTR, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureLOOKUP, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureREAD, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureWRITE, &CNFS2Prog::ProcedureCREATE, &CNFS2Prog::ProcedureREMOVE, &CNFS2Prog::ProcedureRENAME, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureNOTIMP, &CNFS2Prog::ProcedureMKDIR, &CNFS2Prog::ProcedureRMDIR, &CNFS2Prog::ProcedureREADDIR, &CNFS2Prog::ProcedureSTATFS};
PrintLog("NFS ");
if (pParam->nProc >= sizeof(pf) / sizeof(PPROC))
{
ProcedureNOTIMP();
PrintLog("\n");
return PRC_NOTIMP;
}
m_pInStream = pInStream;
m_pOutStream = pOutStream;
m_nResult = PRC_OK;
(this->*pf[pParam->nProc])();
PrintLog("\n");
return m_nResult;
}
void CNFS2Prog::ProcedureNULL(void)
{
PrintLog("NULL");
}
void CNFS2Prog::ProcedureGETATTR(void)
{
char *path;
PrintLog("GETATTR");
path = GetPath();
if (!CheckFile(path))
return;
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureSETATTR(void)
{
char *path;
unsigned long nMode, nAttr;
PrintLog("SETATTR");
path = GetPath();
if (!CheckFile(path))
return;
m_pInStream->Read(&nMode);
nAttr = 0;
if ((nMode & 0x100) != 0)
nAttr |= S_IREAD;
if ((nMode & 0x80) != 0)
nAttr |= S_IWRITE;
_chmod(path, nAttr);
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureLOOKUP(void)
{
char *path;
PrintLog("LOOKUP");
path = GetFullPath();
if (!CheckFile(path))
return;
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(GetFileHandle(path), FHSIZE);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureREAD(void)
{
char *path;
unsigned long nOffset, nCount, nTotalCount;
FILE *file;
char *pBuffer;
unsigned char opaque[3] = {0, 0, 0};
PrintLog("READ");
path = GetPath();
if (!CheckFile(path))
return;
m_pInStream->Read(&nOffset);
m_pInStream->Read(&nCount);
m_pInStream->Read(&nTotalCount);
file = fopen(path, "rb");
fseek(file, nOffset, SEEK_SET);
pBuffer = new char[nCount];
nCount = fread(pBuffer, sizeof(char), nCount, file);
fclose(file);
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
m_pOutStream->Write(nCount); //length
m_pOutStream->Write(pBuffer, nCount); //contents
nCount &= 3;
if (nCount != 0)
m_pOutStream->Write(opaque, 4 - nCount); //opaque bytes
delete[] pBuffer;
}
void CNFS2Prog::ProcedureWRITE(void)
{
char *path;
unsigned long nBeginOffset, nOffset, nTotalCount, nCount;
FILE *file;
char *pBuffer;
PrintLog("WRITE");
path = GetPath();
if (!CheckFile(path))
return;
m_pInStream->Read(&nBeginOffset);
m_pInStream->Read(&nOffset);
m_pInStream->Read(&nTotalCount);
m_pInStream->Read(&nCount);
pBuffer = new char[nCount];
m_pInStream->Read(pBuffer, nCount);
file = fopen(path, "r+b");
fseek(file, nOffset, SEEK_SET);
nCount = fwrite(pBuffer, sizeof(char), nCount, file);
fclose(file);
delete[] pBuffer;
m_pOutStream->Write(NFS_OK);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureCREATE(void)
{
char *path;
FILE *file;
PrintLog("CREATE");
path = GetFullPath();
if (path == NULL)
return;
file = fopen(path, "wb");
fclose(file);
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(GetFileHandle(path), FHSIZE);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureREMOVE(void)
{
char *path;
PrintLog("REMOVE");
path = GetFullPath();
if (!CheckFile(path))
return;
remove(path);
m_pOutStream->Write(NFS_OK);
}
void CNFS2Prog::ProcedureRENAME(void)
{
char *path;
char pathFrom[MAXPATHLEN], *pathTo;
PrintLog("RENAME");
path = GetFullPath();
if (!CheckFile(path))
return;
strcpy(pathFrom, path);
pathTo = GetFullPath();
RenameFile(pathFrom, pathTo);
m_pOutStream->Write(NFS_OK);
}
void CNFS2Prog::ProcedureMKDIR(void)
{
char *path;
PrintLog("MKDIR");
path = GetFullPath();
if (path == NULL)
return;
_mkdir(path);
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(GetFileHandle(path), FHSIZE);
WriteFileAttributes(path);
}
void CNFS2Prog::ProcedureRMDIR(void)
{
char *path;
PrintLog("RMDIR");
path = GetFullPath();
if (!CheckFile(path))
return;
_rmdir(path);
m_pOutStream->Write(NFS_OK);
}
void CNFS2Prog::ProcedureREADDIR(void)
{
unsigned char opaque[3] = {0, 0, 0};
char *path, filePath[MAXPATHLEN + 1];
int handle;
struct _finddata_t fileinfo;
unsigned long count;
unsigned int nLen;
PrintLog("READDIR");
path = GetPath();
if (!CheckFile(path))
return;
m_pOutStream->Write(NFS_OK);
sprintf(filePath, "%s\\*", path);
count = 0;
handle = _findfirst(filePath, &fileinfo);
if (handle)
{
do
{
m_pOutStream->Write(1); //value follows
sprintf(filePath, "%s\\%s", path, fileinfo.name);
m_pOutStream->Write(GetFileID(filePath)); //file id
m_pOutStream->Write(nLen = strlen(fileinfo.name));
m_pOutStream->Write(fileinfo.name, nLen);
nLen &= 3;
if (nLen != 0)
m_pOutStream->Write(opaque, 4 - nLen); //opaque bytes
m_pOutStream->Write(++count); //cookie
} while (_findnext(handle, &fileinfo) == 0);
_findclose(handle);
}
m_pOutStream->Write(0); //no value follows
m_pOutStream->Write(1); //EOF
}
void CNFS2Prog::ProcedureSTATFS(void)
{
char *path;
int nDrive;
struct _diskfree_t data;
PrintLog("STATFS");
path = GetPath();
if (!CheckFile(path))
return;
if (path[0] >= 'a' && path[0] <= 'z')
nDrive = path[0] - 'a' + 1;
else if (path[0] >= 'A' && path[0] <= 'Z')
nDrive = path[0] - 'A' + 1;
else
{
m_pOutStream->Write(NFSERR_NOENT);
return;
}
_getdiskfree(nDrive, &data);
m_pOutStream->Write(NFS_OK);
m_pOutStream->Write(data.sectors_per_cluster * data.bytes_per_sector); //transfer size
m_pOutStream->Write(data.sectors_per_cluster * data.bytes_per_sector); //block size
m_pOutStream->Write(data.total_clusters); //total blocks
m_pOutStream->Write(data.avail_clusters); //free blocks
m_pOutStream->Write(data.avail_clusters); //available blocks
}
void CNFS2Prog::ProcedureNOTIMP(void)
{
PrintLog("NOTIMP");
m_nResult = PRC_NOTIMP;
}
char *CNFS2Prog::GetPath(void)
{
unsigned char fhandle[FHSIZE];
char *path;
m_pInStream->Read(fhandle, FHSIZE);
path = GetFilePath(fhandle);
if (path == NULL)
return NULL;
PrintLog(" %s", path);
return path;
}
char *CNFS2Prog::GetFullPath(void)
{
char *path;
static char filePath[MAXPATHLEN + 1];
unsigned int nLen1, nBytes;
unsigned long nLen2;
path = GetPath();
if (path == NULL)
return NULL;
nLen1 = strlen(path);
m_pInStream->Read(&nLen2);
sprintf(filePath, "%s\\", path);
m_pInStream->Read(filePath + nLen1 + 1, nLen2);
filePath[nLen1 + 1 + nLen2] = '\0';
PrintLog("%s", filePath + nLen1);
if ((nLen2 & 3) != 0)
m_pInStream->Read(&nBytes, 4 - (nLen2 & 3));
return filePath;
}
bool CNFS2Prog::CheckFile(char *path)
{
if (path == NULL)
{
m_pOutStream->Write(NFSERR_STALE);
return false;
}
if (!FileExists(path))
{
m_pOutStream->Write(NFSERR_NOENT);
return false;
}
return true;
}
bool CNFS2Prog::WriteFileAttributes(char *path)
{
struct stat data;
unsigned long nValue;
if (stat(path, &data) != 0)
return false;
switch (data.st_mode & S_IFMT)
{
case S_IFREG:
nValue = NFREG;
break;
case S_IFDIR:
nValue = NFDIR;
break;
case S_IFCHR:
nValue = NFCHR;
break;
default:
nValue = NFNON;
break;
}
m_pOutStream->Write(nValue); //type
if (nValue == NFREG)
nValue = 0x8000;
else if (nValue == NFDIR)
nValue = 0x4000;
else
nValue = 0;
if ((data.st_mode & S_IREAD) != 0)
nValue |= 0x124;
if ((data.st_mode & S_IWRITE) != 0)
nValue |= 0x92;
//if ((data.st_mode & S_IEXEC) != 0)
nValue |= 0x49;
m_pOutStream->Write(nValue); //mode
m_pOutStream->Write(data.st_nlink); //nlink
m_pOutStream->Write(m_nUID); //uid
m_pOutStream->Write(m_nGID); //gid
m_pOutStream->Write(data.st_size); //size
m_pOutStream->Write(8192); //blocksize
m_pOutStream->Write(0); //rdev
m_pOutStream->Write((data.st_size + 8191) / 8192); //blocks
m_pOutStream->Write(4); //fsid
m_pOutStream->Write(GetFileID(path)); //fileid
m_pOutStream->Write(data.st_atime); //atime
m_pOutStream->Write(0); //atime
m_pOutStream->Write(data.st_mtime); //mtime
m_pOutStream->Write(0); //mtime
m_pOutStream->Write(data.st_ctime); //ctime
m_pOutStream->Write(0); //ctime
return true;
}
|
[
"noodle1983@126.com"
] |
noodle1983@126.com
|
1d3a402d63d843f087e99664cab9b05a48e026a6
|
1a1a4fa7baf5c4773eb14f6d88725d9847c704b1
|
/gfeSounds_006.cpp
|
cbca5c02b2ca2fe9c3f3c60d8bf01ff02ba1a002
|
[
"MIT"
] |
permissive
|
gfreundl/GTX328
|
b65dd9b4e0100fd9354dba4282d0dcfb9a80c433
|
87b183ed68b7e31f83cee260700776d822a106e2
|
refs/heads/master
| 2021-06-15T11:18:46.305927
| 2021-05-28T10:01:21
| 2021-05-28T10:01:21
| 202,541,156
| 0
| 1
| null | 2019-08-15T14:04:24
| 2019-08-15T12:55:34
|
C++
|
UTF-8
|
C++
| false
| false
| 60,202
|
cpp
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Windows.h>
#include <math.h>
#include <time.h>
#include "XPLMUtilities.h"
#include "XPLMDataAccess.h"
#include "XPLMProcessing.h"
#include "XPLMPlugin.h"
//OpenAL
#include <al.h>
#include <alc.h>
/*
001 creates an authentic fuel pump sound for piston engine planes, original sound from SR22
sound includes startup and shutdown sequence
002 start external program when X-plane has loaded
used for BFF CL driver
003 renamed to gfeSounds, 64bit port
migrated previous Button2Dataref functions here
rocker and momentary switches, King avionics, autopilot
004 requires XPLM200 preprocessor definition
custom command radio master volume up/down
custom command BFF driver load
changed generator from integer to array
combined HSI and NAV1 OBS input to accomodate RealityXP GNS430
005 drive flaps fully up/down when handle pushed up/down more than 1 second
CommandRefs for all rocker switches
006 COM1 and COM2 volume control with analog potentiometers
Open Issues
engine sound src location to bottom front r left/right for multi-engine
ADF Timer stops after button press
adjust throttle scaling ?
ELEV TRIM for Mooney to be programmed
*/
#define XPLM200
#define A_FUELPUMP_1 "fuelpump_1.wav" //pump winding up
#define A_FUELPUMP_2 "fuelpump_2.wav" //continous run
#define A_FUELPUMP_3 "fuelpump_3.wav" //pump winding down
XPLMDataRef d_joystick_axis_reverse = NULL;
XPLMDataRef d_joystick_axis_assignments = NULL;
XPLMDataRef d_joystick_axis_values = NULL;
XPLMDataRef d_joystick_axis_minimum = NULL;
XPLMDataRef d_joystick_axis_maximum = NULL;
XPLMDataRef d_joystick_button_values = NULL;
XPLMDataRef d_fuel_pump = NULL;
XPLMDataRef d_battery_on = NULL;
XPLMDataRef d_landing_lights_on = NULL;
XPLMDataRef d_generator_on = NULL;
XPLMDataRef d_avionics_on = NULL;
XPLMDataRef d_taxi_light_on = NULL;
XPLMDataRef d_beacon_lights_on = NULL;
XPLMDataRef d_nav_lights_on = NULL;
XPLMDataRef d_strobe_lights_on = NULL;
XPLMDataRef d_ice_pitot_heat_on_pilot = NULL;
XPLMDataRef d_carb_heat_ratio = NULL;
XPLMDataRef d_parking_brake_ratio = NULL;
XPLMDataRef d_alternate_static_air_ratio = NULL;
XPLMDataRef d_audio_marker_enabled = NULL;
XPLMDataRef d_audio_dme_enabled = NULL;
XPLMDataRef d_DME_slave_source = NULL;
XPLMDataRef d_adf1_right_is_selected = NULL;
XPLMDataRef d_dme_power = NULL;
XPLMDataRef d_DME_mode = NULL;
XPLMDataRef d_adf1_standby_frequency_hz = NULL;
XPLMDataRef d_dme_frequency_hz = NULL;
XPLMDataRef d_nav2_power = NULL;
XPLMDataRef d_com2_power = NULL;
XPLMDataRef d_nav1_obs_deg_mag_pilot = NULL;
XPLMDataRef d_hsi_obs_deg_mag_pilot = NULL;
XPLMDataRef d_heading_dial_deg_mag_pilot = NULL;
XPLMDataRef d_nav2_obs_deg_mag_pilot = NULL;
XPLMDataRef d_adf1_card_heading_deg_mag_pilot= NULL;
XPLMDataRef d_annunciator_test_timeout = NULL;
XPLMDataRef d_annunciator_test_pressed = NULL;
XPLMDataRef d_fire_mode = NULL;
XPLMDataRef d_flight_director_mode = NULL;
XPLMDataRef d_adf1_power = NULL;
XPLMDataRef d_timer_is_running_sec = NULL;
XPLMDataRef d_timer_elapsed_time_sec = NULL;
XPLMDataRef d_adf2_power = NULL;
XPLMDataRef d_dg_drift_ele_deg = NULL;
XPLMDataRef d_left_brake_ratio = NULL;
XPLMDataRef d_right_brake_ratio = NULL;
XPLMDataRef d_radio_volume_ratio = NULL;
XPLMDataRef d_flap_ratio = NULL;
XPLMDataRef d_audio_volume_com1 = NULL;
XPLMDataRef d_audio_volume_com2 = NULL;
XPLMCommandRef c_servos_fdir_off = NULL;
XPLMCommandRef gfe_radios_vol_up = NULL;
XPLMCommandRef gfe_radios_vol_dn = NULL;
XPLMCommandRef gfe_adf_100_10_up = NULL;
XPLMCommandRef gfe_adf_100_10_down = NULL;
XPLMCommandRef gfe_adf_1_up = NULL;
XPLMCommandRef gfe_adf_1_down = NULL;
XPLMCommandRef gfe_hsi_obs_1_up = NULL;
XPLMCommandRef gfe_hsi_obs_1_down = NULL;
XPLMCommandRef gfe_hsi_obs_10_up = NULL;
XPLMCommandRef gfe_hsi_obs_10_down = NULL;
XPLMCommandRef gfe_hsi_hdg_1_up = NULL;
XPLMCommandRef gfe_hsi_hdg_1_down = NULL;
XPLMCommandRef gfe_hsi_hdg_10_up = NULL;
XPLMCommandRef gfe_hsi_hdg_10_down = NULL;
XPLMCommandRef gfe_obs2_1_up = NULL;
XPLMCommandRef gfe_obs2_1_down = NULL;
XPLMCommandRef gfe_obs2_10_up = NULL;
XPLMCommandRef gfe_obs2_10_down = NULL;
XPLMCommandRef gfe_rmi_1_up = NULL;
XPLMCommandRef gfe_rmi_1_down = NULL;
XPLMCommandRef gfe_rmi_10_up = NULL;
XPLMCommandRef gfe_rmi_10_down = NULL;
XPLMCommandRef gfe_ext_bff = NULL;
XPLMCommandRef gfe_flap_ratio_up = NULL;
XPLMCommandRef gfe_flap_ratio_down = NULL;
XPLMCommandRef gfe_land_light = NULL;
XPLMCommandRef gfe_battery = NULL;
XPLMCommandRef gfe_avionics = NULL;
XPLMCommandRef gfe_taxi_light = NULL;
XPLMCommandRef gfe_beacon_lights = NULL;
XPLMCommandRef gfe_nav_lights = NULL;
XPLMCommandRef gfe_strobe_lights = NULL;
XPLMCommandRef gfe_ice_pitot_heat_on_pilot = NULL;
XPLMCommandRef gfe_fuel_pump = NULL;
XPLMCommandRef gfe_generator_on = NULL;
XPLMCommandRef gfe_carb_heat_ratio = NULL;
XPLMCommandRef gfe_audio_marker_enabled = NULL;
XPLMCommandRef gfe_audio_dme_enabled = NULL;
XPLMCommandRef gfe_annunciator_test_timeout = NULL;
XPLMCommandRef gfe_dme_power = NULL;
XPLMCommandRef gfe_DME_slave_source = NULL;
XPLMCommandRef gfe_DME_mode_0 = NULL;
XPLMCommandRef gfe_DME_mode_1 = NULL;
XPLMCommandRef gfe_DME_mode_2 = NULL;
XPLMCommandRef gfe_KAP_test = NULL;
XPLMCommandRef gfe_KAP_FD = NULL;
int OLDjoystick_button_values[1600] = { 0 };
int joystick_button_values[1600] = { 0 };
float joystick_axis_values[500] = { 0.0 };
int fuel_pump;
int battery_on;
int landing_lights_on;
int generator_on;
int avionics_on;
int taxi_light_on;
int beacon_lights_on;
int nav_lights_on;
int strobe_lights_on;
int ice_pitot_heat_on_pilot;
int carb_heat_ratio;
int parking_brake_ratio;
int alternate_static_air_ratio;
int audio_marker_enabled;
int audio_dme_enabled;
int DME_slave_source;
int adf1_right_is_selected;
int dme_power;
int DME_mode;
int adf1_standby_frequency_hz;
int dme_frequency_hz;
int nav2_power;
int com2_power;
int nav1_obs_deg_mag_pilot;
int heading_dial_deg_mag_pilot;
int nav2_obs_deg_mag_pilot;
int adf1_card_heading_deg_mag_pilot = NULL;
int annunciator_test_timeout;
int fire_mode;
int flight_director_mode;
int fdtest = 0; //FD test mode
int adf1_power;
int timer_is_running_sec;
int timer_elapsed_time_sec;
int adf2_power;
int dg_drift_ele_deg;
int flaps_timer = 0;
int FuelPump[8] = {0};
int FuelPumpOld[8] = {0};
int i = 0;
int n = 0;
char gPluginDataFile[255]; //file path and name
DWORD timestamp; //timer for KAP150 test sequence
static ALuint snd_src[3]; // Sample source and buffer - this is one "sound" we play.
static ALuint snd_buffer[3];
static float pitch = 1.0f; // Start with 1.0 pitch - no pitch shift.
ALCdevice *my_dev = NULL; // We make our own device and context to play sound through.
ALCcontext *my_ctx= NULL;
ALCcontext *old_ctx = NULL; // have to save old AL context
char sAudioDevice[255]; // read device name from INI File
static float init_sound(float elapsed, float elapsed_sim, int counter, void * ref);
float MyFlightLoopCallback(float inElapsedSinceLastCall, float inElapsedTimeSinceLastFlightLoop, int inCounter, void *inRefcon);
float call_ext_FlightLoopCallback(float inElapsedSinceLastCall, float inElapsedTimeSinceLastFlightLoop, int inCounter, void *inRefcon);
int gfe_radios_vol_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_radios_vol_dn_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_adf_100_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_adf_100_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_adf_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_adf_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_obs_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_obs_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_obs_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_obs_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_hdg_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_hdg_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_hdg_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_hsi_hdg_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_obs2_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_obs2_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_obs2_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_obs2_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_rmi_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_rmi_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_rmi_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_rmi_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_ext_bff_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_flap_ratio_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_flap_ratio_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_land_light_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_battery_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_avionics_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_taxi_light_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_beacon_lights_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_nav_lights_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_strobe_lights_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_ice_pitot_heat_on_pilot_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_fuel_pump_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_generator_on_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_carb_heat_ratio_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_audio_marker_enabled_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_audio_dme_enabled_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_annunciator_test_timeout_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_dme_power_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_DME_slave_source_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_DME_mode_0_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_DME_mode_1_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_DME_mode_2_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
int gfe_KAP_test_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon);
/*-------------------------------- End of Declarations --------------------------------*/
PLUGIN_API int XPluginStart(char * name, char * sig, char * desc)
{
char *pFileName = "Resources\\plugins\\";
/// Setup texture and ini file locations
XPLMGetSystemPath(gPluginDataFile);
strcat(gPluginDataFile, pFileName);
strcpy(name,"gfe Sounds & Switches");
strcpy(sig,"gfe.sound_switches");
strcpy(desc,"Fuel pump sound, King avionics and other switches");
d_joystick_axis_reverse = XPLMFindDataRef("sim/joystick/joystick_axis_reverse");
d_joystick_axis_assignments = XPLMFindDataRef("sim/joystick/joystick_axis_assignments");
d_joystick_axis_minimum = XPLMFindDataRef("sim/joystick/joystick_axis_minimum");
d_joystick_axis_maximum = XPLMFindDataRef("sim/joystick/joystick_axis_maximum");
d_joystick_axis_values = XPLMFindDataRef("sim/joystick/joystick_axis_values");
d_joystick_button_values = XPLMFindDataRef("sim/joystick/joystick_button_values");
d_battery_on = XPLMFindDataRef("sim/cockpit/electrical/battery_on");
d_fuel_pump = XPLMFindDataRef("sim/cockpit2/engine/actuators/fuel_pump_on");
d_landing_lights_on = XPLMFindDataRef("sim/cockpit/electrical/landing_lights_on");
d_generator_on = XPLMFindDataRef("sim/cockpit/electrical/generator_on");
d_avionics_on = XPLMFindDataRef("sim/cockpit/electrical/avionics_on");
d_taxi_light_on = XPLMFindDataRef("sim/cockpit/electrical/taxi_light_on");
d_beacon_lights_on = XPLMFindDataRef("sim/cockpit/electrical/beacon_lights_on");
d_nav_lights_on = XPLMFindDataRef("sim/cockpit/electrical/nav_lights_on");
d_strobe_lights_on = XPLMFindDataRef("sim/cockpit/electrical/strobe_lights_on");
d_ice_pitot_heat_on_pilot = XPLMFindDataRef("sim/cockpit2/ice/ice_pitot_heat_on_pilot");
d_carb_heat_ratio = XPLMFindDataRef("sim/cockpit2/engine/actuators/carb_heat_ratio");
d_parking_brake_ratio = XPLMFindDataRef("sim/cockpit2/controls/parking_brake_ratio");
d_alternate_static_air_ratio = XPLMFindDataRef("sim/cockpit2/switches/alternate_static_air_ratio");
d_audio_marker_enabled = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_marker_enabled");
d_audio_dme_enabled = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_dme_enabled");
d_DME_slave_source = XPLMFindDataRef("sim/cockpit2/radios/actuators/DME_slave_source");
d_adf1_right_is_selected = XPLMFindDataRef("sim/cockpit2/radios/actuators/adf1_right_is_selected");
d_dme_power = XPLMFindDataRef("sim/cockpit2/radios/actuators/dme_power");
d_DME_mode = XPLMFindDataRef("sim/cockpit2/radios/actuators/DME_mode");
d_adf1_standby_frequency_hz = XPLMFindDataRef("sim/cockpit2/radios/actuators/adf1_standby_frequency_hz");
d_dme_frequency_hz = XPLMFindDataRef("sim/cockpit2/radios/actuators/dme_frequency_hz");
d_nav2_power = XPLMFindDataRef("sim/cockpit2/radios/actuators/nav2_power");
d_com2_power = XPLMFindDataRef("sim/cockpit2/radios/actuators/com2_power");
d_nav1_obs_deg_mag_pilot = XPLMFindDataRef("sim/cockpit2/radios/actuators/nav1_obs_deg_mag_pilot");
d_hsi_obs_deg_mag_pilot = XPLMFindDataRef("sim/cockpit2/radios/actuators/hsi_obs_deg_mag_pilot");
d_heading_dial_deg_mag_pilot = XPLMFindDataRef("sim/cockpit2/autopilot/heading_dial_deg_mag_pilot");
d_nav2_obs_deg_mag_pilot = XPLMFindDataRef("sim/cockpit2/radios/actuators/nav2_obs_deg_mag_pilot");
d_adf1_card_heading_deg_mag_pilot = XPLMFindDataRef("sim/cockpit2/radios/actuators/adf1_card_heading_deg_mag_pilot");
d_annunciator_test_timeout = XPLMFindDataRef("sim/cockpit/warnings/annunciator_test_timeout");
d_annunciator_test_pressed = XPLMFindDataRef("sim/cockpit/warnings/d_annunciator_test_pressed");
d_fire_mode = XPLMFindDataRef("sim/cockpit2/weapons/fire_mode");
d_flight_director_mode = XPLMFindDataRef("sim/cockpit2/autopilot/flight_director_mode");
d_adf1_power = XPLMFindDataRef("sim/cockpit2/radios/actuators/adf1_power");
d_timer_is_running_sec = XPLMFindDataRef("sim/time/timer_is_running_sec");
d_timer_elapsed_time_sec = XPLMFindDataRef("sim/time/timer_elapsed_time_sec");
d_adf2_power = XPLMFindDataRef("sim/cockpit2/radios/actuators/adf2_power");
d_dg_drift_ele_deg = XPLMFindDataRef("sim/cockpit/gyros/dg_drift_ele_deg");
c_servos_fdir_off = XPLMFindCommand("sim/autopilot/servos_fdir_off");
d_left_brake_ratio = XPLMFindDataRef("sim/cockpit2/controls/left_brake_ratio");
d_right_brake_ratio = XPLMFindDataRef("sim/cockpit2/controls/right_brake_ratio");
d_radio_volume_ratio = XPLMFindDataRef("sim/operation/sound/radio_volume_ratio");
d_flap_ratio = XPLMFindDataRef("sim/cockpit2/controls/flap_ratio");
d_audio_volume_com1 = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_volume_com1");
d_audio_volume_com2 = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_volume_com2");
// Create custom commands
gfe_radios_vol_up = XPLMCreateCommand("gfe/Avionics/VolUp", "Radios Volume Up");
gfe_radios_vol_dn = XPLMCreateCommand("gfe/Avionics/VolDn", "Radios Volume Down");
gfe_adf_100_10_up = XPLMCreateCommand("gfe/Avionics/ADF_100_10_up", "ADF coarse up");
gfe_adf_100_10_down = XPLMCreateCommand("gfe/Avionics/100_10_down", "ADF coarse down");
gfe_adf_1_up = XPLMCreateCommand("gfe/Avionics/ADF_1_up", "ADF fine up");
gfe_adf_1_down = XPLMCreateCommand("gfe/Avionics/ADF_1_down", "ADF fine down");
gfe_hsi_obs_1_up = XPLMCreateCommand("gfe/Avionics/HSI_OBS_1_up", "HSI up");
gfe_hsi_obs_1_down = XPLMCreateCommand("gfe/Avionics/HSI_OBS_1_down", "HSI down");
gfe_hsi_obs_10_up = XPLMCreateCommand("gfe/Avionics/HSI_OBS_10_up", "HSI tens up");
gfe_hsi_obs_10_down = XPLMCreateCommand("gfe/Avionics/HSI_OBS_10_down", "HSI tens down");
gfe_hsi_hdg_1_up = XPLMCreateCommand("gfe/Avionics/HSI_HDG_1_up", "HDG up");
gfe_hsi_hdg_1_down = XPLMCreateCommand("gfe/Avionics/HSI_HDG_1_down", "HDG down");
gfe_hsi_hdg_10_up = XPLMCreateCommand("gfe/Avionics/HSI_HDG_10_up", "HDG tens up");
gfe_hsi_hdg_10_down = XPLMCreateCommand("gfe/Avionics/HSI_HDG_10_down", "HDG tens down");
gfe_obs2_1_up = XPLMCreateCommand("gfe/Avionics/OBS2_1_up", "OBS2 up");
gfe_obs2_1_down = XPLMCreateCommand("gfe/Avionics/OBS2_1_down", "OBS2 down");
gfe_obs2_10_up = XPLMCreateCommand("gfe/Avionics/OSB2_10_up", "OBS2 tens up");
gfe_obs2_10_down = XPLMCreateCommand("gfe/Avionics/OBS2_10_down", "OBS2 tens down");
gfe_rmi_1_up = XPLMCreateCommand("gfe/Avionics/RMI_1_up", "RMI up");
gfe_rmi_1_down = XPLMCreateCommand("gfe/Avionics/RMI_1_down", "RMI down");
gfe_rmi_10_up = XPLMCreateCommand("gfe/Avionics/RMI_10_up", "RMI tens up");
gfe_rmi_10_down = XPLMCreateCommand("gfe/Avionics/RMI_10_down", "RMI tens down");
gfe_ext_bff = XPLMCreateCommand("gfe/Externals/bff", "Load external programm BFF");
gfe_flap_ratio_up = XPLMCreateCommand("gfe/Controls/flaps_up", "Set flaps up");
gfe_flap_ratio_down = XPLMCreateCommand("gfe/Controls/flaps_down", "Set flaps down");
gfe_land_light = XPLMCreateCommand("gfe/Electrical/land_light", "Landing Light");
gfe_battery = XPLMCreateCommand("gfe/Electrical/Battery", "Battery");
gfe_avionics = XPLMCreateCommand("gfe/Electrical/Avionics", "Avionics");
gfe_taxi_light = XPLMCreateCommand("gfe/Electrical/taxi_light", "Taxi Light");
gfe_beacon_lights = XPLMCreateCommand("gfe/Electrical/beacon_lights", "Beacon Lights");
gfe_nav_lights = XPLMCreateCommand("gfe/Electrical/nav_lights", "Nav Lights");
gfe_strobe_lights = XPLMCreateCommand("gfe/Electrical/strobe_lights", "Strobe Lights");
gfe_ice_pitot_heat_on_pilot = XPLMCreateCommand("gfe/Electrical/ice_pitot_heat_on_pilot", "Pitot Heat");
gfe_fuel_pump = XPLMCreateCommand("gfe/Engine/fuel_pump", "Fuel Pump");
gfe_generator_on = XPLMCreateCommand("gfe/Electrical/generator_on", "Generator");
gfe_carb_heat_ratio = XPLMCreateCommand("gfe/Engine/carb_heat_ratio", "Carburetor Heat");
gfe_audio_marker_enabled = XPLMCreateCommand("gfe/Avionics/audio_marker_enabled", "Marker Mute");
gfe_audio_dme_enabled = XPLMCreateCommand("gfe/Avionics/audio_dme_enabled", "DME Audio");
gfe_annunciator_test_timeout = XPLMCreateCommand("gfe/Electrical/annunciator_test_timeout", "Annunciator Test");
gfe_dme_power = XPLMCreateCommand("gfe/Avionics/dme_power", "DME Power");
gfe_DME_slave_source = XPLMCreateCommand("gfe/Avionics/DME_slave_source", "DME Source");
gfe_DME_mode_0 = XPLMCreateCommand("gfe/Avionics/DME_mode_0", "DME Mode RMT");
gfe_DME_mode_1 = XPLMCreateCommand("gfe/Avionics/DME_mode_1", "DME Mode FREQ");
gfe_DME_mode_2 = XPLMCreateCommand("gfe/Avionics/DME_mode_2", "DME Mode GS/T");
gfe_KAP_test = XPLMCreateCommand("gfe/Avionics/KAP_test", "KAP 150 Test");
// Register custom commands
XPLMRegisterCommandHandler(gfe_radios_vol_up, gfe_radios_vol_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_radios_vol_dn, gfe_radios_vol_dn_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_adf_100_10_up, gfe_adf_100_10_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_adf_100_10_down, gfe_adf_100_10_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_adf_1_up, gfe_adf_1_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_adf_1_down, gfe_adf_1_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_obs_1_up, gfe_hsi_obs_1_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_obs_1_down, gfe_hsi_obs_1_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_obs_10_up, gfe_hsi_obs_10_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_obs_10_down, gfe_hsi_obs_10_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_hdg_1_up, gfe_hsi_hdg_1_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_hdg_1_down, gfe_hsi_hdg_1_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_hdg_10_up, gfe_hsi_hdg_10_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_hsi_hdg_10_down, gfe_hsi_hdg_10_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_obs2_1_up, gfe_obs2_1_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_obs2_1_down, gfe_obs2_1_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_obs2_10_up, gfe_obs2_10_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_obs2_10_down, gfe_obs2_10_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_rmi_1_up, gfe_rmi_1_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_rmi_1_down, gfe_rmi_1_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_rmi_10_up, gfe_rmi_10_up_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_rmi_10_down, gfe_rmi_10_down_Proc, 1, (void *)0);
XPLMRegisterCommandHandler(gfe_ext_bff, gfe_ext_bff_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_flap_ratio_up, gfe_flap_ratio_up_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_flap_ratio_down, gfe_flap_ratio_down_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_land_light, gfe_land_light_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_battery, gfe_battery_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_avionics, gfe_avionics_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_taxi_light, gfe_taxi_light_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_beacon_lights, gfe_beacon_lights_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_nav_lights, gfe_nav_lights_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_strobe_lights, gfe_strobe_lights_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_ice_pitot_heat_on_pilot, gfe_ice_pitot_heat_on_pilot_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_fuel_pump, gfe_fuel_pump_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_generator_on, gfe_generator_on_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_carb_heat_ratio, gfe_carb_heat_ratio_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_audio_marker_enabled, gfe_audio_marker_enabled_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_audio_dme_enabled, gfe_audio_dme_enabled_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_annunciator_test_timeout, gfe_annunciator_test_timeout_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_dme_power, gfe_dme_power_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_DME_slave_source, gfe_DME_slave_source_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_DME_mode_0, gfe_DME_mode_0_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_DME_mode_1, gfe_DME_mode_1_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_DME_mode_2, gfe_DME_mode_2_Proc, 1, (void*)0);
XPLMRegisterCommandHandler(gfe_KAP_test, gfe_KAP_test_Proc, 1, (void*)0);
// Launch external program once XPL has fully loaded
// Do deferred initialization. See http://www.xsquawkbox.net/xpsdk/mediawiki/DeferredInitialization
//XPLMRegisterFlightLoopCallback(call_ext_FlightLoopCallback,-1.0,NULL);
// Do deferred sound initialization. See http://www.xsquawkbox.net/xpsdk/mediawiki/DeferredInitialization
XPLMRegisterFlightLoopCallback(init_sound, -1.0, NULL);
//Register FlightLoop Callback for every 250msec
XPLMRegisterFlightLoopCallback(
MyFlightLoopCallback, /* Callback */
0.10, /* Interval */
NULL); /* refcon not used. */
//defaults for cold & dark start
XPLMSetDatai(d_battery_on, 0); //default to cold & dark
XPLMSetDatai(d_adf2_power, 0); //defaut ADF to non-timer mode
XPLMSetDatai(d_fire_mode, 3); //on Battery on, bring KAP150 in pre-test mode
int a[8] = { 0 }; //temp array for XPLMSetDatavi
XPLMSetDatavi(d_fuel_pump, a, 0, 8); //reset fuel pump oon start
return 1;
}
PLUGIN_API void XPluginStop(void)
{
XPLMUnregisterFlightLoopCallback(MyFlightLoopCallback, NULL);
//XPLMUnregisterFlightLoopCallback(call_ext_FlightLoopCallback, NULL);
XPLMUnregisterCommandHandler(gfe_radios_vol_up, gfe_radios_vol_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_radios_vol_dn, gfe_radios_vol_dn_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_adf_100_10_up, gfe_adf_100_10_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_adf_100_10_down, gfe_adf_100_10_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_adf_1_up, gfe_adf_1_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_adf_1_down, gfe_adf_1_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_obs_1_up, gfe_hsi_obs_1_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_obs_1_down, gfe_hsi_obs_1_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_obs_10_up, gfe_hsi_obs_10_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_obs_10_down, gfe_hsi_obs_10_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_hdg_1_up, gfe_hsi_hdg_1_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_hdg_1_down, gfe_hsi_hdg_1_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_hdg_10_up, gfe_hsi_hdg_10_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_hsi_hdg_10_down, gfe_hsi_hdg_10_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_obs2_1_up, gfe_obs2_1_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_obs2_1_down, gfe_obs2_1_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_obs2_10_up, gfe_obs2_10_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_obs2_10_down, gfe_obs2_10_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_rmi_1_up, gfe_rmi_1_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_rmi_1_down, gfe_rmi_1_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_rmi_10_up, gfe_rmi_10_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_rmi_10_down, gfe_rmi_10_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_ext_bff, gfe_ext_bff_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_flap_ratio_up, gfe_flap_ratio_up_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_flap_ratio_down, gfe_flap_ratio_down_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_land_light, gfe_land_light_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_battery, gfe_battery_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_avionics, gfe_avionics_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_taxi_light, gfe_taxi_light_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_beacon_lights, gfe_beacon_lights_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_nav_lights, gfe_nav_lights_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_strobe_lights, gfe_strobe_lights_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_ice_pitot_heat_on_pilot, gfe_ice_pitot_heat_on_pilot_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_fuel_pump, gfe_fuel_pump_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_generator_on, gfe_generator_on_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_carb_heat_ratio, gfe_carb_heat_ratio_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_audio_marker_enabled, gfe_audio_marker_enabled_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_audio_dme_enabled, gfe_audio_dme_enabled_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_annunciator_test_timeout, gfe_annunciator_test_timeout_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_dme_power, gfe_dme_power_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_DME_slave_source, gfe_DME_slave_source_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_DME_mode_0, gfe_DME_mode_0_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_DME_mode_1, gfe_DME_mode_1_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_DME_mode_2, gfe_DME_mode_2_Proc, 0, 0);
XPLMUnregisterCommandHandler(gfe_KAP_test, gfe_KAP_test_Proc, 0, 0);
// Cleanup: nuke our context if we have it. This is hacky and bad - we should really destroy
// our buffers and sources. I have _no_ idea if OpenAL will leak memory.
if(alcGetCurrentContext() != NULL)
{
//printf("0x%08x: deleting snd %d\n", XPLMGetMyID(),snd_buffer);
if(snd_src[0]) alDeleteSources(1,&snd_src[0]);
if(snd_buffer[0]) alDeleteBuffers(1,&snd_buffer[0]);
}
if(my_ctx)
{
//printf("0x%08x: deleting my context 0x%08x\n", XPLMGetMyID(),my_ctx);
alcMakeContextCurrent(NULL);
alcDestroyContext(my_ctx);
}
if(my_dev) alcCloseDevice(my_dev);
}
PLUGIN_API int XPluginEnable(void)
{
return 1;
}
PLUGIN_API void XPluginDisable(void)
{
}
PLUGIN_API void XPluginReceiveMessage(
XPLMPluginID inFromWho,
long inMessage,
void * inParam)
{
}
//Main flight loop
float MyFlightLoopCallback(
float inElapsedSinceLastCall,
float inElapsedTimeSinceLastFlightLoop,
int inCounter,
void * inRefcon)
{
static int nTick;
static int firstLoop;
XPLMSetDataf(d_parking_brake_ratio, 0.0); //unset parking brake
//read all joystick axis vaules and assigments
i = XPLMGetDatavf(d_joystick_axis_values, joystick_axis_values, 0, 500);
//edit response function to exponential parameter
//exponential function: y = x/n * pow(n,x) (with joystick value x = 0..1 and factor n = 1..20 and result 0..1)
//joystick_axis_values[6] = joystick_axis_values[6] / 20 * pow(20, joystick_axis_values[6]);
//joystick_axis_values[7] = joystick_axis_values[7] / 20 * pow(20, joystick_axis_values[7]);
//XPLMSetDataf(d_left_brake_ratio, joystick_axis_values[6]);
//XPLMSetDataf(d_right_brake_ratio, joystick_axis_values[7]);
for (i = 0; i < 1600; i++) //save last joystick state
{ //for detecting long press
OLDjoystick_button_values[i] = joystick_button_values[i];
}
//read all joystick button values
i = XPLMGetDatavi(d_joystick_button_values, joystick_button_values, 0, 1600);
//KAP150 Test sequence
/*
if ((joystick_button_values[1134] == 1) && (OLDjoystick_button_values[1134] == 0))
{
XPLMSetDatai(d_fire_mode, 2);
fire_mode = 2;
timestamp = GetTickCount();
}*/
if ((fire_mode == 2) && (GetTickCount() - timestamp > 2000))
{
XPLMSetDatai(d_fire_mode, 1);
fire_mode = 1;
}
if ((fire_mode == 1) && (GetTickCount() - timestamp > 5000))
{
XPLMSetDatai(d_fire_mode, 0);
fire_mode = 0;
XPLMSetDatai(d_flight_director_mode, 2);
fdtest = 1; //test cycle finished
/*no success in trying to play sound, servo activation gets persistent*/
/*XPLMCommandButtonPress(xplm_joy_ott_dis);
XPLMCommandButtonRelease(xplm_joy_ott_dis);*/
/*XPLMCommandOnce(XPLMFindCommand("sim/autopilot/servos_on"));
XPLMCommandOnce(c_servos_fdir_off);
XPLMCommandOnce(XPLMFindCommand("sim/autopilot/servos_toggle")); */
}
if ((fire_mode == 0) && (GetTickCount() - timestamp > 5050) && (fdtest))
{
XPLMSetDatai(d_flight_director_mode, 0);
fdtest = 0;
}
//ADF start timer on powering up, reset on power off
if (XPLMGetDatai(d_adf1_power) > 1 )
{
XPLMSetDatai(d_timer_is_running_sec, 1);
}
else
{
XPLMSetDatai(d_timer_is_running_sec, 0);
XPLMSetDatai(d_adf2_power, 0);
}
//ET mode with fake dataref, display timer when d_adf2_power=1
if ((joystick_button_values[483] == 1) && (OLDjoystick_button_values[483] == 0))
{
XPLMSetDatai(d_adf2_power, !XPLMGetDatai(d_adf2_power));
}
//reset timer
if ((joystick_button_values[480] == 1) && (OLDjoystick_button_values[480] == 0))
{
XPLMSetDataf(d_timer_elapsed_time_sec, 0.0);
}
//KA51 slaved gyro
if (joystick_button_values[1137] == 1)
{
XPLMSetDataf(d_dg_drift_ele_deg, 0.0);
}
if (joystick_button_values[1146] == 1)
{
XPLMSetDataf(d_dg_drift_ele_deg, XPLMGetDataf(d_dg_drift_ele_deg) - 0.2);
}
if (joystick_button_values[1136] == 1)
{
XPLMSetDataf(d_dg_drift_ele_deg, XPLMGetDataf(d_dg_drift_ele_deg) + 0.2);
}
//play pump sound when pump runs
i = XPLMGetDatavi(d_fuel_pump, FuelPump, 0, 8);
for (i=0;i<2;i++)
{
if ((FuelPump[i] == 1) && (FuelPumpOld[i] == 0)) //
{
alSourcef(snd_src[0],AL_PITCH,pitch); //play start sound
alSourcePlay(snd_src[0]);
FuelPumpOld[i] = 1; //"pump running" flag
firstLoop = 1;
}
else if ((FuelPump[i] == 1) && (FuelPumpOld[i] == 1)) //pump sound is already running
{
if ((nTick % 20 == 0) || (firstLoop)) //loop initially after startup and then every second
{
alSourceStop(snd_src[1]);
alSourcef(snd_src[1],AL_PITCH,pitch); //play continous sound
alSourcePlay(snd_src[1]);
firstLoop = 0;
}
}
else if ((FuelPump[i] == 0) && (FuelPumpOld[i] == 1)) //pump has been shut off but sound is still on
{
alSourceStop(snd_src[1]);
alSourcef(snd_src[2],AL_PITCH,pitch); //play shutoff sound
alSourcePlay(snd_src[2]);
FuelPumpOld[i] = 0;
}
}
//adjust COM1 and COM2 radio volume
XPLMSetDataf(d_audio_volume_com1, joystick_axis_values[226]);
XPLMSetDataf(d_audio_volume_com2, joystick_axis_values[76]);
nTick++;
return 0.10; // Return time interval after that we want to be called again
}
/*-------------------------------- Custom Commands --------------------------------*/
int gfe_radios_vol_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_radio_volume_ratio) <= 0.95)
{
XPLMSetDataf(d_radio_volume_ratio, XPLMGetDataf(d_radio_volume_ratio) + 0.05);
}
}
return 0;
}
int gfe_radios_vol_dn_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_radio_volume_ratio) >= 0.05)
{
XPLMSetDataf(d_radio_volume_ratio, XPLMGetDataf(d_radio_volume_ratio) - 0.05);
}
}
return 0;
}
int gfe_adf_100_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDatai(d_adf1_standby_frequency_hz) < 406)
{
XPLMSetDatai(d_adf1_standby_frequency_hz, XPLMGetDatai(d_adf1_standby_frequency_hz) + 10);
}
}
return 0;
}
int gfe_adf_100_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDatai(d_adf1_standby_frequency_hz) > 209)
{
XPLMSetDatai(d_adf1_standby_frequency_hz, XPLMGetDatai(d_adf1_standby_frequency_hz) - 10);
}
}
return 0;
}
int gfe_adf_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDatai(d_adf1_standby_frequency_hz) < 415)
{
XPLMSetDatai(d_adf1_standby_frequency_hz, XPLMGetDatai(d_adf1_standby_frequency_hz) + 1);
}
}
return 0;
}
int gfe_adf_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDatai(d_adf1_standby_frequency_hz) > 200)
{
XPLMSetDatai(d_adf1_standby_frequency_hz, XPLMGetDatai(d_adf1_standby_frequency_hz) - 1);
}
}
return 0;
}
int gfe_hsi_obs_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if ((XPLMGetDataf(d_nav1_obs_deg_mag_pilot) < 360.0) || (XPLMGetDataf(d_hsi_obs_deg_mag_pilot) < 360.0))
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, XPLMGetDataf(d_nav1_obs_deg_mag_pilot) + 1.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, XPLMGetDataf(d_hsi_obs_deg_mag_pilot) + 1.0);
}
else
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, 0.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_hsi_obs_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if ((XPLMGetDataf(d_nav1_obs_deg_mag_pilot) > 1.0) || (XPLMGetDataf(d_hsi_obs_deg_mag_pilot) > 1.0))
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, XPLMGetDataf(d_nav1_obs_deg_mag_pilot) - 1.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, XPLMGetDataf(d_hsi_obs_deg_mag_pilot) - 1.0);
}
else
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, 360.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_hsi_obs_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if ((XPLMGetDataf(d_nav1_obs_deg_mag_pilot) < 355.0) || (XPLMGetDataf(d_hsi_obs_deg_mag_pilot) < 355.0))
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, XPLMGetDataf(d_nav1_obs_deg_mag_pilot) + 5.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, XPLMGetDataf(d_hsi_obs_deg_mag_pilot) + 5.0);
}
else
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, 0.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_hsi_obs_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if ((XPLMGetDataf(d_nav1_obs_deg_mag_pilot) > 5.0) || (XPLMGetDataf(d_hsi_obs_deg_mag_pilot) > 5.0))
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, XPLMGetDataf(d_nav1_obs_deg_mag_pilot) - 5.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, XPLMGetDataf(d_hsi_obs_deg_mag_pilot) - 5.0);
}
else
{
XPLMSetDataf(d_nav1_obs_deg_mag_pilot, 360.0);
XPLMSetDataf(d_hsi_obs_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_hsi_hdg_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_heading_dial_deg_mag_pilot) < 360.0)
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, XPLMGetDataf(d_heading_dial_deg_mag_pilot) + 1.0);
}
else
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_hsi_hdg_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_heading_dial_deg_mag_pilot) > 1.0)
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, XPLMGetDataf(d_heading_dial_deg_mag_pilot) - 1.0);
}
else
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_hsi_hdg_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_heading_dial_deg_mag_pilot) < 355.0)
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, XPLMGetDataf(d_heading_dial_deg_mag_pilot) + 5.0);
}
else
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_hsi_hdg_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_heading_dial_deg_mag_pilot) > 5.0)
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, XPLMGetDataf(d_heading_dial_deg_mag_pilot) - 5.0);
}
else
{
XPLMSetDataf(d_heading_dial_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_obs2_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_nav2_obs_deg_mag_pilot) < 360.0)
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, XPLMGetDataf(d_nav2_obs_deg_mag_pilot) + 1.0);
}
else
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_obs2_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_nav2_obs_deg_mag_pilot) > 1.0)
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, XPLMGetDataf(d_nav2_obs_deg_mag_pilot) - 1.0);
}
else
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_obs2_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_nav2_obs_deg_mag_pilot) < 355.0)
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, XPLMGetDataf(d_nav2_obs_deg_mag_pilot) + 5.0);
}
else
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_obs2_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_nav2_obs_deg_mag_pilot) > 5.0)
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, XPLMGetDataf(d_nav2_obs_deg_mag_pilot) - 5.0);
}
else
{
XPLMSetDataf(d_nav2_obs_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_rmi_1_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) < 360.0)
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) + 1.0);
}
else
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_rmi_1_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) > 1.0)
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) - 1.0);
}
else
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_rmi_10_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) < 355.0)
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) + 5.0);
}
else
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, 0.0);
}
}
return 0;
}
int gfe_rmi_10_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
if (XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) > 5.0)
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, XPLMGetDataf(d_adf1_card_heading_deg_mag_pilot) - 5.0);
}
else
{
XPLMSetDataf(d_adf1_card_heading_deg_mag_pilot, 360.0);
}
}
return 0;
}
int gfe_ext_bff_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandEnd)
{
ShellExecute(NULL, NULL,
"\"C:\\BFF_Control_Loader_v1_300_Release2\\BFF_Control_LoaderX_v1_300.exe\"",
"\"C:\\BFF_Control_Loader_v1_300_Release2\\Configuration Manager\\Aircraft Config Files\\Cessna172-Xplane.cfg\"",
NULL, SW_MINIMIZE);
}
return 0;
}
int gfe_flap_ratio_up_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandBegin)
{
flaps_timer = time(0);
XPLMCommandButtonPress(xplm_joy_flapsup); //drive flaps one notch
XPLMCommandButtonRelease(xplm_joy_flapsup);
}
else if (inPhase == xplm_CommandContinue)
{
if (time(0) > (flaps_timer + 1)) //if presssed longer than 1 second
{
XPLMCommandButtonPress(xplm_joy_flapsup); //drive one more notch
}
}
else
{
XPLMCommandButtonRelease(xplm_joy_flapsup);
flaps_timer = 0;
}
return 0;
}
int gfe_flap_ratio_down_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandBegin)
{
flaps_timer = time(0);
XPLMCommandButtonPress(xplm_joy_flapsdn); //drive flaps one notch
XPLMCommandButtonRelease(xplm_joy_flapsdn);
}
else if (inPhase == xplm_CommandContinue)
{
if (time(0) > (flaps_timer + 1)) //if presssed longer than 1 second
{
XPLMCommandButtonPress(xplm_joy_flapsdn); //drive one more notch
}
}
else
{
XPLMCommandButtonRelease(xplm_joy_flapsdn);
flaps_timer = 0;
}
return 0;
}
int gfe_land_light_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_landing_lights_on, 1);
}
else
{
XPLMSetDatai(d_landing_lights_on, 0);
}
return 0;
}
int gfe_battery_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandBegin)
{
XPLMSetDatai(d_fire_mode, 3); //on Battery on, bring KAP150 in pre-test mode
}
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_battery_on, 1);
}
else
{
XPLMSetDatai(d_battery_on, 0);
}
return 0;
}
int gfe_avionics_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_avionics_on, 1);
}
else
{
XPLMSetDatai(d_avionics_on, 0);
}
return 0;
}
int gfe_taxi_light_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_taxi_light_on, 1);
}
else
{
XPLMSetDatai(d_taxi_light_on, 0);
}
return 0;
}
int gfe_beacon_lights_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_beacon_lights_on, 1);
}
else
{
XPLMSetDatai(d_beacon_lights_on, 0);
}
return 0;
}
int gfe_nav_lights_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_nav_lights_on, 1);
}
else
{
XPLMSetDatai(d_nav_lights_on, 0);
}
return 0;
}
int gfe_strobe_lights_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_strobe_lights_on, 1);
}
else
{
XPLMSetDatai(d_strobe_lights_on, 0);
}
return 0;
}
int gfe_ice_pitot_heat_on_pilot_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_ice_pitot_heat_on_pilot, 1);
}
else
{
XPLMSetDatai(d_ice_pitot_heat_on_pilot, 0);
}
return 0;
}
int gfe_fuel_pump_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
int a[8] = { 0 }; //temp array for XPLMSetDatavi
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
a[0] = 1;
}
else
{
a[0] = 0;
}
XPLMSetDatavi(d_fuel_pump, a, 0, 8);
return 0;
}
int gfe_generator_on_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
int a[8] = { 0 }; //temp array for XPLMSetDatavi
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
a[0] = 1;
}
else
{
a[0] = 0;
}
XPLMSetDatavi(d_generator_on, a, 0, 8);
return 0;
}
int gfe_carb_heat_ratio_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
float f[8] = { 0.0 }; //temp array for XPLMSetDatavf
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
f[0] = 1.0;
}
else
{
f[0] = 0.0;
}
XPLMSetDatavf(d_carb_heat_ratio, f, 0, 8);
return 0;
}
int gfe_audio_marker_enabled_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandBegin)
{
XPLMSetDatai(d_audio_marker_enabled, !XPLMGetDatai(d_audio_marker_enabled));
}
return 0;
}
int gfe_audio_dme_enabled_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandBegin)
{
XPLMSetDatai(d_audio_dme_enabled, !XPLMGetDatai(d_audio_dme_enabled));
}
return 0;
}
int gfe_annunciator_test_timeout_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if (inPhase == xplm_CommandBegin)
{
XPLMSetDataf(d_annunciator_test_timeout, 4.0); //annunciator test delay
}
return 0;
}
int gfe_dme_power_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_dme_power, 1);
}
else
{
XPLMSetDatai(d_dme_power, 0);
}
return 0;
}
int gfe_DME_slave_source_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_DME_slave_source, 0);
}
else
{
XPLMSetDatai(d_DME_slave_source, 1);
}
return 0;
}
int gfe_DME_mode_0_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_DME_mode, 0);
}
return 0;
}
int gfe_DME_mode_1_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_DME_mode, 1);
}
return 0;
}
int gfe_DME_mode_2_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_DME_mode, 2);
}
return 0;
}
int gfe_KAP_test_Proc(XPLMCommandRef inCommand, XPLMCommandPhase inPhase, void *inRefcon)
{
if ((inPhase == xplm_CommandBegin) || (inPhase == xplm_CommandContinue))
{
XPLMSetDatai(d_fire_mode, 2);
fire_mode = 2;
timestamp = GetTickCount();
}
return 0;
}
float call_ext_FlightLoopCallback(
float inElapsedSinceLastCall,
float inElapsedTimeSinceLastFlightLoop,
int inCounter,
void * inRefcon)
{
char sa[255]; //for test BFF launch
char sb[255];
strcpy(sa, "\"C:\\BFF_Control_Loader_v1_300_Release2\\BFF_Control_LoaderX_v1_300.exe\"");
strcpy(sb, "\"C:\\BFF_Control_Loader_v1_300_Release2\\Configuration Manager\\Aircraft Config Files\\Cessna172-Xplane.cfg\"");
ShellExecute(NULL, NULL, sa, sb, NULL, SW_MINIMIZE);
return 0.0f;
}
/*-------------------------------- OpenAL stuff --------------------------------*/
/**************************************************************************************************************
* WAVE FILE LOADING
**************************************************************************************************************/
// You can just use alutCreateBufferFromFile to load a wave file, but there seems to be a lot of problems with
// alut not beign available, being deprecated, etc. So...here's a stupid routine to load a wave file. I have
// tested this only on x86 machines, so if you find a bug on PPC please let me know.
// Macros to swap endian-values.
#define SWAP_32(value) \
(((((unsigned short)value)<<8) & 0xFF00) | \
((((unsigned short)value)>>8) & 0x00FF))
#define SWAP_16(value) \
(((((unsigned int)value)<<24) & 0xFF000000) | \
((((unsigned int)value)<< 8) & 0x00FF0000) | \
((((unsigned int)value)>> 8) & 0x0000FF00) | \
((((unsigned int)value)>>24) & 0x000000FF))
// Wave files are RIFF files, which are "chunky" - each section has an ID and a length. This lets us skip
// things we can't understand to find the parts we want. This header is common to all RIFF chunks.
struct chunk_header {
int id;
int size;
};
// WAVE file format info. We pass this through to OpenAL so we can support mono/stereo, 8/16/bit, etc.
struct format_info {
short format; // PCM = 1, not sure what other values are legal.
short num_channels;
int sample_rate;
int byte_rate;
short block_align;
short bits_per_sample;
};
// This utility returns the start of data for a chunk given a range of bytes it might be within. Pass 1 for
// swapped if the machine is not the same endian as the file.
static char * find_chunk(char * file_begin, char * file_end, int desired_id, int swapped)
{
while(file_begin < file_end)
{
chunk_header * h = (chunk_header *) file_begin;
if(h->id == desired_id && !swapped)
return file_begin+sizeof(chunk_header);
if(h->id == SWAP_32(desired_id) && swapped)
return file_begin+sizeof(chunk_header);
int chunk_size = swapped ? SWAP_32(h->size) : h->size;
char * next = file_begin + chunk_size + sizeof(chunk_header);
if(next > file_end || next <= file_begin)
return NULL;
file_begin = next;
}
return NULL;
}
// Given a chunk, find its end by going back to the header.
static char * chunk_end(char * chunk_start, int swapped)
{
chunk_header * h = (chunk_header *) (chunk_start - sizeof(chunk_header));
return chunk_start + (swapped ? SWAP_32(h->size) : h->size);
}
//#define FAIL(X) { XPLMDebugString(X); free(mem); return 0; }
#define RIFF_ID 0x46464952 // 'RIFF'
#define FMT_ID 0x20746D66 // 'FMT '
#define DATA_ID 0x61746164 // 'DATA'
ALuint load_wave(const char * file_name)
{
// First we open the file and copy it into a single large memory buffer for processing.
FILE * fi = fopen(file_name,"rb");
if(fi == NULL)
{
XPLMDebugString("WAVE file load failed - could not open.\n");
return 0;
}
fseek(fi,0,SEEK_END);
int file_size = ftell(fi);
fseek(fi,0,SEEK_SET);
char * mem = (char*) malloc(file_size);
if(mem == NULL)
{
XPLMDebugString("WAVE file load failed - could not allocate memory.\n");
fclose(fi);
return 0;
}
if (fread(mem, 1, file_size, fi) != file_size)
{
XPLMDebugString("WAVE file load failed - could not read file.\n");
free(mem);
fclose(fi);
return 0;
}
fclose(fi);
char * mem_end = mem + file_size;
// Second: find the RIFF chunk. Note that by searching for RIFF both normal
// and reversed, we can automatically determine the endian swap situation for
// this file regardless of what machine we are on.
int swapped = 0;
char * riff = find_chunk(mem, mem_end, RIFF_ID, 0);
if(riff == NULL)
{
riff = find_chunk(mem, mem_end, RIFF_ID, 1);
if(riff)
swapped = 1;
else
XPLMDebugString("Could not find RIFF chunk in wave file.\n");
}
// The wave chunk isn't really a chunk at all. It's just a "WAVE" tag followed by more chunks.
// confirm the WAVE ID and move on
if (riff[0] != 'W' ||
riff[1] != 'A' ||
riff[2] != 'V' ||
riff[3] != 'E')
XPLMDebugString("Could not find WAVE signature in wave file.\n");
char * format = find_chunk(riff+4, chunk_end(riff,swapped), FMT_ID, swapped);
if(format == NULL)
XPLMDebugString("Could not find FMT chunk in wave file.\n");
// Find the format chunk, and swap the values if needed. This gives us our real format.
format_info * fmt = (format_info *) format;
if(swapped)
{
fmt->format = SWAP_16(fmt->format);
fmt->num_channels = SWAP_16(fmt->num_channels);
fmt->sample_rate = SWAP_32(fmt->sample_rate);
fmt->byte_rate = SWAP_32(fmt->byte_rate);
fmt->block_align = SWAP_16(fmt->block_align);
fmt->bits_per_sample = SWAP_16(fmt->bits_per_sample);
}
// Reject things we don't understand...expand this code to support weirder audio formats.
if(fmt->format != 1)
XPLMDebugString("Wave file is not PCM format data.\n");
if(fmt->num_channels != 1 && fmt->num_channels != 2)
XPLMDebugString("Must have mono or stereo sound.\n");
if(fmt->bits_per_sample != 8 && fmt->bits_per_sample != 16)
XPLMDebugString("Must have 8 or 16 bit sounds.\n");
char * data = find_chunk(riff+4, chunk_end(riff,swapped), DATA_ID, swapped) ;
if(data == NULL)
XPLMDebugString("I could not find the DATA chunk.\n");
int sample_size = fmt->num_channels * fmt->bits_per_sample / 8;
int data_bytes = chunk_end(data,swapped) - data;
int data_samples = data_bytes / sample_size;
// If the file is swapped and we have 16-bit audio, we need to endian-swap the audio too or we'll
// get something that sounds just astoundingly bad!
if(fmt->bits_per_sample == 16 && swapped)
{
short * ptr = (short *) data;
int words = data_samples * fmt->num_channels;
while(words--)
{
*ptr = SWAP_16(*ptr);
++ptr;
}
}
// Finally, the OpenAL crud. Build a new OpenAL buffer and send the data to OpenAL, passing in
// OpenAL format enums based on the format chunk.
ALuint buf_id = 0;
alGenBuffers(1, &buf_id);
if(buf_id == 0)
XPLMDebugString("Could not generate buffer id.\n");
alBufferData(buf_id, fmt->bits_per_sample == 16 ?
(fmt->num_channels == 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16) :
(fmt->num_channels == 2 ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8),
data, data_bytes, fmt->sample_rate);
free(mem);
return buf_id;
}
// This is a stupid logging error function...useful for debugging, but not good error checking.
#define CHECK_ERR() __CHECK_ERR(__FILE__,__LINE__)
static void __CHECK_ERR(const char * f, int l)
{
ALuint e = alGetError();
if (e != AL_NO_ERROR)
printf("ERROR: %d (%s:%d\n", e, f, l);
}
// Initialization code.
float init_sound(float elapsed, float elapsed_sim, int counter, void * ref)
{
char* s;
char buf[255];
char filepath[255];
char wavfile[3][30];
strcpy(wavfile[0], A_FUELPUMP_1);
strcpy(wavfile[1], A_FUELPUMP_2);
strcpy(wavfile[2], A_FUELPUMP_3);
CHECK_ERR();
// We have to save the old context and restore it later, so that we don't interfere with X-Plane and other plugins.
old_ctx = alcGetCurrentContext();
if (old_ctx)
{
//printf("0x%08x: I found someone else's context 0x%08x.\n",XPLMGetMyID(), old_ctx);
XPLMDebugString("gfeSounds: found someone else's context.\n");
}
// Enumerate Audio Devices
s = (char *)alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
//try open specific device, if unavailable, revert to default device
my_dev = alcOpenDevice("Speakers (Realtek High Definition Audio)");
//my_dev = alcOpenDevice(sAudioDevice);
if (my_dev == NULL)
{
my_dev = alcOpenDevice(NULL);
}
if (my_dev == NULL)
{
XPLMDebugString("gfeSounds: Could not open the default OpenAL device.\n");
return 0;
}
my_ctx = alcCreateContext(my_dev, NULL);
if(my_ctx == NULL)
{
if(old_ctx)
alcMakeContextCurrent(old_ctx);
alcCloseDevice(my_dev);
my_dev = NULL;
XPLMDebugString("gfeSounds: Could not create a context.\n");
return 0;
}
// Make our context current, so that OpenAL commands affect our, um, stuff.
alcMakeContextCurrent(my_ctx);
/* printf("0x%08x: I created the context.\n",XPLMGetMyID(), my_ctx);
ALCint major_version, minor_version;
const char * al_hw=alcGetString(my_dev,ALC_DEVICE_SPECIFIER );
const char * al_ex=alcGetString(my_dev,ALC_EXTENSIONS);
alcGetIntegerv(NULL,ALC_MAJOR_VERSION,sizeof(major_version),&major_version);
alcGetIntegerv(NULL,ALC_MINOR_VERSION,sizeof(minor_version),&minor_version);
printf("OpenAL version : %d.%d\n",major_version,minor_version);
printf("OpenAL hardware : %s\n", (al_hw?al_hw:"(none)"));
printf("OpenAL extensions: %s\n", (al_ex?al_ex:"(none)"));
*/
CHECK_ERR();
ALfloat zero[3] = { 0 } ;
strcpy(filepath, gPluginDataFile);
for (i=0;i<3;i++)
{
strcpy(buf, filepath);
strcat(buf, wavfile[i]);
// Generate 1 source and load a buffer of audio.
alGenSources(1,&snd_src[i]);
CHECK_ERR();
snd_buffer[i] = load_wave(buf);
//printf("0x%08x: Loaded %d from %s\n", XPLMGetMyID(), snd_buffer[i],buf);
CHECK_ERR();
// Basic initializtion code to play a sound: specify the buffer the source is playing, as well as some
// sound parameters. This doesn't play the sound - it's just one-time initialization.
alSourcei(snd_src[i],AL_BUFFER,snd_buffer[i]);
alSourcef(snd_src[i],AL_PITCH,1.0f);
alSourcef(snd_src[i],AL_GAIN,1.0f);
alSourcei(snd_src[i],AL_LOOPING,0);
//zero[0] = -1.0;
//zero[1] = 1.0;
alSourcefv(snd_src[i],AL_POSITION, zero);
alSourcefv(snd_src[i],AL_VELOCITY, zero);
CHECK_ERR();
}
// Finally: put back the old context _if_ we had one. If old_ctx was null, X-Plane isn't using OpenAL.
if (old_ctx)
{
alcMakeContextCurrent(old_ctx);
}
return 0.0f;
}
|
[
"gfreundl@arri.de"
] |
gfreundl@arri.de
|
67486a8938253037c1dd4f720782b6625bb30bd3
|
f089ab62d8a6fd4d613b66cc6ea1e86fec2b8826
|
/src/mvs/mat.h
|
306c08fcec6dcaf21e74b56a5be9b131f8ecb3ae
|
[
"BSD-3-Clause"
] |
permissive
|
tsattler/colmap
|
7653c4838db23749ef20d8fe873d51500b0dc70d
|
38f1e96891a9f2770f84769350c3ebb496f44399
|
refs/heads/master
| 2021-07-13T05:23:28.280242
| 2019-03-03T16:06:56
| 2019-03-03T16:06:56
| 69,578,709
| 2
| 1
|
NOASSERTION
| 2023-09-05T08:30:59
| 2016-09-29T15:02:16
|
C
|
UTF-8
|
C++
| false
| false
| 5,763
|
h
|
// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of ETH Zurich and UNC Chapel Hill 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 HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: Johannes L. Schoenberger (jsch at inf.ethz.ch)
#ifndef COLMAP_SRC_MVS_MAT_H_
#define COLMAP_SRC_MVS_MAT_H_
#include <fstream>
#include <string>
#include <vector>
#include "util/endian.h"
#include "util/logging.h"
namespace colmap {
namespace mvs {
template <typename T>
class Mat {
public:
Mat();
Mat(const size_t width, const size_t height, const size_t depth);
size_t GetWidth() const;
size_t GetHeight() const;
size_t GetDepth() const;
size_t GetNumBytes() const;
T Get(const size_t row, const size_t col, const size_t slice = 0) const;
void GetSlice(const size_t row, const size_t col, T* values) const;
T* GetPtr();
const T* GetPtr() const;
const std::vector<T>& GetData() const;
void Set(const size_t row, const size_t col, const T value);
void Set(const size_t row, const size_t col, const size_t slice,
const T value);
void Fill(const T value);
void Read(const std::string& path);
void Write(const std::string& path) const;
protected:
size_t width_ = 0;
size_t height_ = 0;
size_t depth_ = 0;
std::vector<T> data_;
};
////////////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////////////
template <typename T>
Mat<T>::Mat() : Mat(0, 0, 0) {}
template <typename T>
Mat<T>::Mat(const size_t width, const size_t height, const size_t depth)
: width_(width), height_(height), depth_(depth) {
data_.resize(width_ * height_ * depth_, 0);
}
template <typename T>
size_t Mat<T>::GetWidth() const {
return width_;
}
template <typename T>
size_t Mat<T>::GetHeight() const {
return height_;
}
template <typename T>
size_t Mat<T>::GetDepth() const {
return depth_;
}
template <typename T>
size_t Mat<T>::GetNumBytes() const {
return data_.size() * sizeof(T);
}
template <typename T>
T Mat<T>::Get(const size_t row, const size_t col, const size_t slice) const {
return data_.at(slice * width_ * height_ + row * width_ + col);
}
template <typename T>
void Mat<T>::GetSlice(const size_t row, const size_t col, T* values) const {
for (size_t slice = 0; slice < depth_; ++slice) {
values[slice] = Get(row, col, slice);
}
}
template <typename T>
T* Mat<T>::GetPtr() {
return data_.data();
}
template <typename T>
const T* Mat<T>::GetPtr() const {
return data_.data();
}
template <typename T>
const std::vector<T>& Mat<T>::GetData() const {
return data_;
}
template <typename T>
void Mat<T>::Set(const size_t row, const size_t col, const T value) {
Set(row, col, 0, value);
}
template <typename T>
void Mat<T>::Set(const size_t row, const size_t col, const size_t slice,
const T value) {
data_.at(slice * width_ * height_ + row * width_ + col) = value;
}
template <typename T>
void Mat<T>::Fill(const T value) {
std::fill(data_.begin(), data_.end(), value);
}
template <typename T>
void Mat<T>::Read(const std::string& path) {
std::fstream text_file(path, std::ios::in | std::ios::binary);
CHECK(text_file.is_open()) << path;
char unused_char;
text_file >> width_ >> unused_char >> height_ >> unused_char >> depth_ >>
unused_char;
std::streampos pos = text_file.tellg();
text_file.close();
CHECK_GT(width_, 0);
CHECK_GT(height_, 0);
CHECK_GT(depth_, 0);
data_.resize(width_ * height_ * depth_);
std::fstream binary_file(path, std::ios::in | std::ios::binary);
CHECK(binary_file.is_open()) << path;
binary_file.seekg(pos);
ReadBinaryLittleEndian<T>(&binary_file, &data_);
binary_file.close();
}
template <typename T>
void Mat<T>::Write(const std::string& path) const {
std::fstream text_file(path, std::ios::out);
CHECK(text_file.is_open()) << path;
text_file << width_ << "&" << height_ << "&" << depth_ << "&";
text_file.close();
std::fstream binary_file(path,
std::ios::out | std::ios::binary | std::ios::app);
CHECK(binary_file.is_open()) << path;
WriteBinaryLittleEndian<T>(&binary_file, data_);
binary_file.close();
}
} // namespace mvs
} // namespace colmap
#endif // COLMAP_SRC_MVS_MAT_H_
|
[
"jsch@demuc.de"
] |
jsch@demuc.de
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.